1 // SPDX-License-Identifier: GPL-2.0
3 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
5 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
7 * Interactivity improvements by Mike Galbraith
8 * (C) 2007 Mike Galbraith <efault@gmx.de>
10 * Various enhancements by Dmitry Adamushko.
11 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
13 * Group scheduling enhancements by Srivatsa Vaddagiri
14 * Copyright IBM Corporation, 2007
15 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
17 * Scaled math optimizations by Thomas Gleixner
18 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
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>
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
52 #include <asm/switch_to.h>
54 #include <linux/sched/cond_resched.h>
58 #include "autogroup.h"
61 * The initial- and re-scaling of tunables is configurable
65 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
66 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
67 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
69 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
71 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
74 * Minimal preemption granularity for CPU-bound tasks:
76 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
78 unsigned int sysctl_sched_base_slice = 750000ULL;
79 static unsigned int normalized_sysctl_sched_base_slice = 750000ULL;
81 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
83 int sched_thermal_decay_shift;
84 static int __init setup_sched_thermal_decay_shift(char *str)
88 if (kstrtoint(str, 0, &_shift))
89 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
91 sched_thermal_decay_shift = clamp(_shift, 0, 10);
94 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
98 * For asym packing, by default the lower numbered CPU has higher priority.
100 int __weak arch_asym_cpu_priority(int cpu)
106 * The margin used when comparing utilization with CPU capacity.
110 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
113 * The margin used when comparing CPU capacities.
114 * is 'cap1' noticeably greater than 'cap2'
118 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
121 #ifdef CONFIG_CFS_BANDWIDTH
123 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
124 * each time a cfs_rq requests quota.
126 * Note: in the case that the slice exceeds the runtime remaining (either due
127 * to consumption or the quota being specified to be smaller than the slice)
128 * we will always only issue the remaining available time.
130 * (default: 5 msec, units: microseconds)
132 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
135 #ifdef CONFIG_NUMA_BALANCING
136 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
137 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
141 static struct ctl_table sched_fair_sysctls[] = {
142 #ifdef CONFIG_CFS_BANDWIDTH
144 .procname = "sched_cfs_bandwidth_slice_us",
145 .data = &sysctl_sched_cfs_bandwidth_slice,
146 .maxlen = sizeof(unsigned int),
148 .proc_handler = proc_dointvec_minmax,
149 .extra1 = SYSCTL_ONE,
152 #ifdef CONFIG_NUMA_BALANCING
154 .procname = "numa_balancing_promote_rate_limit_MBps",
155 .data = &sysctl_numa_balancing_promote_rate_limit,
156 .maxlen = sizeof(unsigned int),
158 .proc_handler = proc_dointvec_minmax,
159 .extra1 = SYSCTL_ZERO,
161 #endif /* CONFIG_NUMA_BALANCING */
165 static int __init sched_fair_sysctl_init(void)
167 register_sysctl_init("kernel", sched_fair_sysctls);
170 late_initcall(sched_fair_sysctl_init);
173 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
179 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
185 static inline void update_load_set(struct load_weight *lw, unsigned long w)
192 * Increase the granularity value when there are more CPUs,
193 * because with more CPUs the 'effective latency' as visible
194 * to users decreases. But the relationship is not linear,
195 * so pick a second-best guess by going with the log2 of the
198 * This idea comes from the SD scheduler of Con Kolivas:
200 static unsigned int get_update_sysctl_factor(void)
202 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
205 switch (sysctl_sched_tunable_scaling) {
206 case SCHED_TUNABLESCALING_NONE:
209 case SCHED_TUNABLESCALING_LINEAR:
212 case SCHED_TUNABLESCALING_LOG:
214 factor = 1 + ilog2(cpus);
221 static void update_sysctl(void)
223 unsigned int factor = get_update_sysctl_factor();
225 #define SET_SYSCTL(name) \
226 (sysctl_##name = (factor) * normalized_sysctl_##name)
227 SET_SYSCTL(sched_base_slice);
231 void __init sched_init_granularity(void)
236 #define WMULT_CONST (~0U)
237 #define WMULT_SHIFT 32
239 static void __update_inv_weight(struct load_weight *lw)
243 if (likely(lw->inv_weight))
246 w = scale_load_down(lw->weight);
248 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
250 else if (unlikely(!w))
251 lw->inv_weight = WMULT_CONST;
253 lw->inv_weight = WMULT_CONST / w;
257 * delta_exec * weight / lw.weight
259 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
261 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
262 * we're guaranteed shift stays positive because inv_weight is guaranteed to
263 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
265 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
266 * weight/lw.weight <= 1, and therefore our shift will also be positive.
268 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
270 u64 fact = scale_load_down(weight);
271 u32 fact_hi = (u32)(fact >> 32);
272 int shift = WMULT_SHIFT;
275 __update_inv_weight(lw);
277 if (unlikely(fact_hi)) {
283 fact = mul_u32_u32(fact, lw->inv_weight);
285 fact_hi = (u32)(fact >> 32);
292 return mul_u64_u32_shr(delta_exec, fact, shift);
298 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
300 if (unlikely(se->load.weight != NICE_0_LOAD))
301 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
306 const struct sched_class fair_sched_class;
308 /**************************************************************
309 * CFS operations on generic schedulable entities:
312 #ifdef CONFIG_FAIR_GROUP_SCHED
314 /* Walk up scheduling entities hierarchy */
315 #define for_each_sched_entity(se) \
316 for (; se; se = se->parent)
318 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
320 struct rq *rq = rq_of(cfs_rq);
321 int cpu = cpu_of(rq);
324 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
329 * Ensure we either appear before our parent (if already
330 * enqueued) or force our parent to appear after us when it is
331 * enqueued. The fact that we always enqueue bottom-up
332 * reduces this to two cases and a special case for the root
333 * cfs_rq. Furthermore, it also means that we will always reset
334 * tmp_alone_branch either when the branch is connected
335 * to a tree or when we reach the top of the tree
337 if (cfs_rq->tg->parent &&
338 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
340 * If parent is already on the list, we add the child
341 * just before. Thanks to circular linked property of
342 * the list, this means to put the child at the tail
343 * of the list that starts by parent.
345 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
346 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
348 * The branch is now connected to its tree so we can
349 * reset tmp_alone_branch to the beginning of the
352 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
356 if (!cfs_rq->tg->parent) {
358 * cfs rq without parent should be put
359 * at the tail of the list.
361 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
362 &rq->leaf_cfs_rq_list);
364 * We have reach the top of a tree so we can reset
365 * tmp_alone_branch to the beginning of the list.
367 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
372 * The parent has not already been added so we want to
373 * make sure that it will be put after us.
374 * tmp_alone_branch points to the begin of the branch
375 * where we will add parent.
377 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
379 * update tmp_alone_branch to points to the new begin
382 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
386 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
388 if (cfs_rq->on_list) {
389 struct rq *rq = rq_of(cfs_rq);
392 * With cfs_rq being unthrottled/throttled during an enqueue,
393 * it can happen the tmp_alone_branch points the a leaf that
394 * we finally want to del. In this case, tmp_alone_branch moves
395 * to the prev element but it will point to rq->leaf_cfs_rq_list
396 * at the end of the enqueue.
398 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
399 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
401 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
406 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
408 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
411 /* Iterate thr' all leaf cfs_rq's on a runqueue */
412 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
413 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
416 /* Do the two (enqueued) entities belong to the same group ? */
417 static inline struct cfs_rq *
418 is_same_group(struct sched_entity *se, struct sched_entity *pse)
420 if (se->cfs_rq == pse->cfs_rq)
426 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
432 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
434 int se_depth, pse_depth;
437 * preemption test can be made between sibling entities who are in the
438 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
439 * both tasks until we find their ancestors who are siblings of common
443 /* First walk up until both entities are at same depth */
444 se_depth = (*se)->depth;
445 pse_depth = (*pse)->depth;
447 while (se_depth > pse_depth) {
449 *se = parent_entity(*se);
452 while (pse_depth > se_depth) {
454 *pse = parent_entity(*pse);
457 while (!is_same_group(*se, *pse)) {
458 *se = parent_entity(*se);
459 *pse = parent_entity(*pse);
463 static int tg_is_idle(struct task_group *tg)
468 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
470 return cfs_rq->idle > 0;
473 static int se_is_idle(struct sched_entity *se)
475 if (entity_is_task(se))
476 return task_has_idle_policy(task_of(se));
477 return cfs_rq_is_idle(group_cfs_rq(se));
480 #else /* !CONFIG_FAIR_GROUP_SCHED */
482 #define for_each_sched_entity(se) \
483 for (; se; se = NULL)
485 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
490 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
494 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
498 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
499 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
501 static inline struct sched_entity *parent_entity(struct sched_entity *se)
507 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
511 static inline int tg_is_idle(struct task_group *tg)
516 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
521 static int se_is_idle(struct sched_entity *se)
526 #endif /* CONFIG_FAIR_GROUP_SCHED */
528 static __always_inline
529 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
531 /**************************************************************
532 * Scheduling class tree data structure manipulation methods:
535 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
537 s64 delta = (s64)(vruntime - max_vruntime);
539 max_vruntime = vruntime;
544 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
546 s64 delta = (s64)(vruntime - min_vruntime);
548 min_vruntime = vruntime;
553 static inline bool entity_before(const struct sched_entity *a,
554 const struct sched_entity *b)
556 return (s64)(a->vruntime - b->vruntime) < 0;
559 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
561 return (s64)(se->vruntime - cfs_rq->min_vruntime);
564 #define __node_2_se(node) \
565 rb_entry((node), struct sched_entity, run_node)
568 * Compute virtual time from the per-task service numbers:
570 * Fair schedulers conserve lag:
574 * Where lag_i is given by:
576 * lag_i = S - s_i = w_i * (V - v_i)
578 * Where S is the ideal service time and V is it's virtual time counterpart.
582 * \Sum w_i * (V - v_i) = 0
583 * \Sum w_i * V - w_i * v_i = 0
585 * From which we can solve an expression for V in v_i (which we have in
588 * \Sum v_i * w_i \Sum v_i * w_i
589 * V = -------------- = --------------
592 * Specifically, this is the weighted average of all entity virtual runtimes.
594 * [[ NOTE: this is only equal to the ideal scheduler under the condition
595 * that join/leave operations happen at lag_i = 0, otherwise the
596 * virtual time has non-continguous motion equivalent to:
600 * Also see the comment in place_entity() that deals with this. ]]
602 * However, since v_i is u64, and the multiplcation could easily overflow
603 * transform it into a relative form that uses smaller quantities:
605 * Substitute: v_i == (v_i - v0) + v0
607 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
608 * V = ---------------------------- = --------------------- + v0
611 * Which we track using:
613 * v0 := cfs_rq->min_vruntime
614 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
615 * \Sum w_i := cfs_rq->avg_load
617 * Since min_vruntime is a monotonic increasing variable that closely tracks
618 * the per-task service, these deltas: (v_i - v), will be in the order of the
619 * maximal (virtual) lag induced in the system due to quantisation.
621 * Also, we use scale_load_down() to reduce the size.
623 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
626 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
628 unsigned long weight = scale_load_down(se->load.weight);
629 s64 key = entity_key(cfs_rq, se);
631 cfs_rq->avg_vruntime += key * weight;
632 cfs_rq->avg_load += weight;
636 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
638 unsigned long weight = scale_load_down(se->load.weight);
639 s64 key = entity_key(cfs_rq, se);
641 cfs_rq->avg_vruntime -= key * weight;
642 cfs_rq->avg_load -= weight;
646 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
649 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
651 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
655 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
656 * For this to be so, the result of this function must have a left bias.
658 u64 avg_vruntime(struct cfs_rq *cfs_rq)
660 struct sched_entity *curr = cfs_rq->curr;
661 s64 avg = cfs_rq->avg_vruntime;
662 long load = cfs_rq->avg_load;
664 if (curr && curr->on_rq) {
665 unsigned long weight = scale_load_down(curr->load.weight);
667 avg += entity_key(cfs_rq, curr) * weight;
672 /* sign flips effective floor / ceil */
675 avg = div_s64(avg, load);
678 return cfs_rq->min_vruntime + avg;
682 * lag_i = S - s_i = w_i * (V - v_i)
684 * However, since V is approximated by the weighted average of all entities it
685 * is possible -- by addition/removal/reweight to the tree -- to move V around
686 * and end up with a larger lag than we started with.
688 * Limit this to either double the slice length with a minimum of TICK_NSEC
689 * since that is the timing granularity.
691 * EEVDF gives the following limit for a steady state system:
693 * -r_max < lag < max(r_max, q)
695 * XXX could add max_slice to the augmented data to track this.
697 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
701 SCHED_WARN_ON(!se->on_rq);
702 lag = avg_vruntime(cfs_rq) - se->vruntime;
704 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
705 se->vlag = clamp(lag, -limit, limit);
709 * Entity is eligible once it received less service than it ought to have,
712 * lag_i = S - s_i = w_i*(V - v_i)
714 * lag_i >= 0 -> V >= v_i
717 * V = ------------------ + v
720 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
722 * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
723 * to the loss in precision caused by the division.
725 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
727 struct sched_entity *curr = cfs_rq->curr;
728 s64 avg = cfs_rq->avg_vruntime;
729 long load = cfs_rq->avg_load;
731 if (curr && curr->on_rq) {
732 unsigned long weight = scale_load_down(curr->load.weight);
734 avg += entity_key(cfs_rq, curr) * weight;
738 return avg >= entity_key(cfs_rq, se) * load;
741 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
743 u64 min_vruntime = cfs_rq->min_vruntime;
745 * open coded max_vruntime() to allow updating avg_vruntime
747 s64 delta = (s64)(vruntime - min_vruntime);
749 avg_vruntime_update(cfs_rq, delta);
750 min_vruntime = vruntime;
755 static void update_min_vruntime(struct cfs_rq *cfs_rq)
757 struct sched_entity *se = __pick_first_entity(cfs_rq);
758 struct sched_entity *curr = cfs_rq->curr;
760 u64 vruntime = cfs_rq->min_vruntime;
764 vruntime = curr->vruntime;
771 vruntime = se->vruntime;
773 vruntime = min_vruntime(vruntime, se->vruntime);
776 /* ensure we never gain time by being placed backwards. */
777 u64_u32_store(cfs_rq->min_vruntime,
778 __update_min_vruntime(cfs_rq, vruntime));
781 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
783 return entity_before(__node_2_se(a), __node_2_se(b));
786 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
788 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
791 struct sched_entity *rse = __node_2_se(node);
792 if (deadline_gt(min_deadline, se, rse))
793 se->min_deadline = rse->min_deadline;
798 * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
800 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
802 u64 old_min_deadline = se->min_deadline;
803 struct rb_node *node = &se->run_node;
805 se->min_deadline = se->deadline;
806 __update_min_deadline(se, node->rb_right);
807 __update_min_deadline(se, node->rb_left);
809 return se->min_deadline == old_min_deadline;
812 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
813 run_node, min_deadline, min_deadline_update);
816 * Enqueue an entity into the rb-tree:
818 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
820 avg_vruntime_add(cfs_rq, se);
821 se->min_deadline = se->deadline;
822 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
823 __entity_less, &min_deadline_cb);
826 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
828 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
830 avg_vruntime_sub(cfs_rq, se);
833 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
835 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
840 return __node_2_se(left);
844 * Earliest Eligible Virtual Deadline First
846 * In order to provide latency guarantees for different request sizes
847 * EEVDF selects the best runnable task from two criteria:
849 * 1) the task must be eligible (must be owed service)
851 * 2) from those tasks that meet 1), we select the one
852 * with the earliest virtual deadline.
854 * We can do this in O(log n) time due to an augmented RB-tree. The
855 * tree keeps the entries sorted on service, but also functions as a
856 * heap based on the deadline by keeping:
858 * se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
860 * Which allows an EDF like search on (sub)trees.
862 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
864 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
865 struct sched_entity *curr = cfs_rq->curr;
866 struct sched_entity *best = NULL;
868 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
872 * Once selected, run a task until it either becomes non-eligible or
873 * until it gets a new slice. See the HACK in set_next_entity().
875 if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
879 struct sched_entity *se = __node_2_se(node);
882 * If this entity is not eligible, try the left subtree.
884 if (!entity_eligible(cfs_rq, se)) {
885 node = node->rb_left;
890 * If this entity has an earlier deadline than the previous
891 * best, take this one. If it also has the earliest deadline
892 * of its subtree, we're done.
894 if (!best || deadline_gt(deadline, best, se)) {
896 if (best->deadline == best->min_deadline)
901 * If the earlest deadline in this subtree is in the fully
902 * eligible left half of our space, go there.
905 __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
906 node = node->rb_left;
910 node = node->rb_right;
913 if (!best || (curr && deadline_gt(deadline, best, curr)))
916 if (unlikely(!best)) {
917 struct sched_entity *left = __pick_first_entity(cfs_rq);
919 pr_err("EEVDF scheduling fail, picking leftmost\n");
927 #ifdef CONFIG_SCHED_DEBUG
928 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
930 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
935 return __node_2_se(last);
938 /**************************************************************
939 * Scheduling class statistics methods:
942 int sched_update_scaling(void)
944 unsigned int factor = get_update_sysctl_factor();
946 #define WRT_SYSCTL(name) \
947 (normalized_sysctl_##name = sysctl_##name / (factor))
948 WRT_SYSCTL(sched_base_slice);
956 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
959 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
960 * this is probably good enough.
962 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
964 if ((s64)(se->vruntime - se->deadline) < 0)
968 * For EEVDF the virtual time slope is determined by w_i (iow.
969 * nice) while the request time r_i is determined by
970 * sysctl_sched_base_slice.
972 se->slice = sysctl_sched_base_slice;
975 * EEVDF: vd_i = ve_i + r_i / w_i
977 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
980 * The task has consumed its request, reschedule.
982 if (cfs_rq->nr_running > 1) {
983 resched_curr(rq_of(cfs_rq));
984 clear_buddies(cfs_rq, se);
991 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
992 static unsigned long task_h_load(struct task_struct *p);
993 static unsigned long capacity_of(int cpu);
995 /* Give new sched_entity start runnable values to heavy its load in infant time */
996 void init_entity_runnable_average(struct sched_entity *se)
998 struct sched_avg *sa = &se->avg;
1000 memset(sa, 0, sizeof(*sa));
1003 * Tasks are initialized with full load to be seen as heavy tasks until
1004 * they get a chance to stabilize to their real load level.
1005 * Group entities are initialized with zero load to reflect the fact that
1006 * nothing has been attached to the task group yet.
1008 if (entity_is_task(se))
1009 sa->load_avg = scale_load_down(se->load.weight);
1011 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1015 * With new tasks being created, their initial util_avgs are extrapolated
1016 * based on the cfs_rq's current util_avg:
1018 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1020 * However, in many cases, the above util_avg does not give a desired
1021 * value. Moreover, the sum of the util_avgs may be divergent, such
1022 * as when the series is a harmonic series.
1024 * To solve this problem, we also cap the util_avg of successive tasks to
1025 * only 1/2 of the left utilization budget:
1027 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1029 * where n denotes the nth task and cpu_scale the CPU capacity.
1031 * For example, for a CPU with 1024 of capacity, a simplest series from
1032 * the beginning would be like:
1034 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1035 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1037 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1038 * if util_avg > util_avg_cap.
1040 void post_init_entity_util_avg(struct task_struct *p)
1042 struct sched_entity *se = &p->se;
1043 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1044 struct sched_avg *sa = &se->avg;
1045 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1046 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1048 if (p->sched_class != &fair_sched_class) {
1050 * For !fair tasks do:
1052 update_cfs_rq_load_avg(now, cfs_rq);
1053 attach_entity_load_avg(cfs_rq, se);
1054 switched_from_fair(rq, p);
1056 * such that the next switched_to_fair() has the
1059 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1064 if (cfs_rq->avg.util_avg != 0) {
1065 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
1066 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1068 if (sa->util_avg > cap)
1075 sa->runnable_avg = sa->util_avg;
1078 #else /* !CONFIG_SMP */
1079 void init_entity_runnable_average(struct sched_entity *se)
1082 void post_init_entity_util_avg(struct task_struct *p)
1085 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1088 #endif /* CONFIG_SMP */
1091 * Update the current task's runtime statistics.
1093 static void update_curr(struct cfs_rq *cfs_rq)
1095 struct sched_entity *curr = cfs_rq->curr;
1096 u64 now = rq_clock_task(rq_of(cfs_rq));
1099 if (unlikely(!curr))
1102 delta_exec = now - curr->exec_start;
1103 if (unlikely((s64)delta_exec <= 0))
1106 curr->exec_start = now;
1108 if (schedstat_enabled()) {
1109 struct sched_statistics *stats;
1111 stats = __schedstats_from_se(curr);
1112 __schedstat_set(stats->exec_max,
1113 max(delta_exec, stats->exec_max));
1116 curr->sum_exec_runtime += delta_exec;
1117 schedstat_add(cfs_rq->exec_clock, delta_exec);
1119 curr->vruntime += calc_delta_fair(delta_exec, curr);
1120 update_deadline(cfs_rq, curr);
1121 update_min_vruntime(cfs_rq);
1123 if (entity_is_task(curr)) {
1124 struct task_struct *curtask = task_of(curr);
1126 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1127 cgroup_account_cputime(curtask, delta_exec);
1128 account_group_exec_runtime(curtask, delta_exec);
1131 account_cfs_rq_runtime(cfs_rq, delta_exec);
1134 static void update_curr_fair(struct rq *rq)
1136 update_curr(cfs_rq_of(&rq->curr->se));
1140 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1142 struct sched_statistics *stats;
1143 struct task_struct *p = NULL;
1145 if (!schedstat_enabled())
1148 stats = __schedstats_from_se(se);
1150 if (entity_is_task(se))
1153 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1157 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1159 struct sched_statistics *stats;
1160 struct task_struct *p = NULL;
1162 if (!schedstat_enabled())
1165 stats = __schedstats_from_se(se);
1168 * When the sched_schedstat changes from 0 to 1, some sched se
1169 * maybe already in the runqueue, the se->statistics.wait_start
1170 * will be 0.So it will let the delta wrong. We need to avoid this
1173 if (unlikely(!schedstat_val(stats->wait_start)))
1176 if (entity_is_task(se))
1179 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1183 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1185 struct sched_statistics *stats;
1186 struct task_struct *tsk = NULL;
1188 if (!schedstat_enabled())
1191 stats = __schedstats_from_se(se);
1193 if (entity_is_task(se))
1196 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1200 * Task is being enqueued - update stats:
1203 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1205 if (!schedstat_enabled())
1209 * Are we enqueueing a waiting task? (for current tasks
1210 * a dequeue/enqueue event is a NOP)
1212 if (se != cfs_rq->curr)
1213 update_stats_wait_start_fair(cfs_rq, se);
1215 if (flags & ENQUEUE_WAKEUP)
1216 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1220 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1223 if (!schedstat_enabled())
1227 * Mark the end of the wait period if dequeueing a
1230 if (se != cfs_rq->curr)
1231 update_stats_wait_end_fair(cfs_rq, se);
1233 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1234 struct task_struct *tsk = task_of(se);
1237 /* XXX racy against TTWU */
1238 state = READ_ONCE(tsk->__state);
1239 if (state & TASK_INTERRUPTIBLE)
1240 __schedstat_set(tsk->stats.sleep_start,
1241 rq_clock(rq_of(cfs_rq)));
1242 if (state & TASK_UNINTERRUPTIBLE)
1243 __schedstat_set(tsk->stats.block_start,
1244 rq_clock(rq_of(cfs_rq)));
1249 * We are picking a new current task - update its stats:
1252 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1255 * We are starting a new run period:
1257 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1260 /**************************************************
1261 * Scheduling class queueing methods:
1264 static inline bool is_core_idle(int cpu)
1266 #ifdef CONFIG_SCHED_SMT
1269 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1273 if (!idle_cpu(sibling))
1282 #define NUMA_IMBALANCE_MIN 2
1285 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1288 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1289 * threshold. Above this threshold, individual tasks may be contending
1290 * for both memory bandwidth and any shared HT resources. This is an
1291 * approximation as the number of running tasks may not be related to
1292 * the number of busy CPUs due to sched_setaffinity.
1294 if (dst_running > imb_numa_nr)
1298 * Allow a small imbalance based on a simple pair of communicating
1299 * tasks that remain local when the destination is lightly loaded.
1301 if (imbalance <= NUMA_IMBALANCE_MIN)
1306 #endif /* CONFIG_NUMA */
1308 #ifdef CONFIG_NUMA_BALANCING
1310 * Approximate time to scan a full NUMA task in ms. The task scan period is
1311 * calculated based on the tasks virtual memory size and
1312 * numa_balancing_scan_size.
1314 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1315 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1317 /* Portion of address space to scan in MB */
1318 unsigned int sysctl_numa_balancing_scan_size = 256;
1320 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1321 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1323 /* The page with hint page fault latency < threshold in ms is considered hot */
1324 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1327 refcount_t refcount;
1329 spinlock_t lock; /* nr_tasks, tasks */
1334 struct rcu_head rcu;
1335 unsigned long total_faults;
1336 unsigned long max_faults_cpu;
1338 * faults[] array is split into two regions: faults_mem and faults_cpu.
1340 * Faults_cpu is used to decide whether memory should move
1341 * towards the CPU. As a consequence, these stats are weighted
1342 * more by CPU use than by memory faults.
1344 unsigned long faults[];
1348 * For functions that can be called in multiple contexts that permit reading
1349 * ->numa_group (see struct task_struct for locking rules).
1351 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1353 return rcu_dereference_check(p->numa_group, p == current ||
1354 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1357 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1359 return rcu_dereference_protected(p->numa_group, p == current);
1362 static inline unsigned long group_faults_priv(struct numa_group *ng);
1363 static inline unsigned long group_faults_shared(struct numa_group *ng);
1365 static unsigned int task_nr_scan_windows(struct task_struct *p)
1367 unsigned long rss = 0;
1368 unsigned long nr_scan_pages;
1371 * Calculations based on RSS as non-present and empty pages are skipped
1372 * by the PTE scanner and NUMA hinting faults should be trapped based
1375 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1376 rss = get_mm_rss(p->mm);
1378 rss = nr_scan_pages;
1380 rss = round_up(rss, nr_scan_pages);
1381 return rss / nr_scan_pages;
1384 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1385 #define MAX_SCAN_WINDOW 2560
1387 static unsigned int task_scan_min(struct task_struct *p)
1389 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1390 unsigned int scan, floor;
1391 unsigned int windows = 1;
1393 if (scan_size < MAX_SCAN_WINDOW)
1394 windows = MAX_SCAN_WINDOW / scan_size;
1395 floor = 1000 / windows;
1397 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1398 return max_t(unsigned int, floor, scan);
1401 static unsigned int task_scan_start(struct task_struct *p)
1403 unsigned long smin = task_scan_min(p);
1404 unsigned long period = smin;
1405 struct numa_group *ng;
1407 /* Scale the maximum scan period with the amount of shared memory. */
1409 ng = rcu_dereference(p->numa_group);
1411 unsigned long shared = group_faults_shared(ng);
1412 unsigned long private = group_faults_priv(ng);
1414 period *= refcount_read(&ng->refcount);
1415 period *= shared + 1;
1416 period /= private + shared + 1;
1420 return max(smin, period);
1423 static unsigned int task_scan_max(struct task_struct *p)
1425 unsigned long smin = task_scan_min(p);
1427 struct numa_group *ng;
1429 /* Watch for min being lower than max due to floor calculations */
1430 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1432 /* Scale the maximum scan period with the amount of shared memory. */
1433 ng = deref_curr_numa_group(p);
1435 unsigned long shared = group_faults_shared(ng);
1436 unsigned long private = group_faults_priv(ng);
1437 unsigned long period = smax;
1439 period *= refcount_read(&ng->refcount);
1440 period *= shared + 1;
1441 period /= private + shared + 1;
1443 smax = max(smax, period);
1446 return max(smin, smax);
1449 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1451 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1452 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1455 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1457 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1458 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1461 /* Shared or private faults. */
1462 #define NR_NUMA_HINT_FAULT_TYPES 2
1464 /* Memory and CPU locality */
1465 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1467 /* Averaged statistics, and temporary buffers. */
1468 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1470 pid_t task_numa_group_id(struct task_struct *p)
1472 struct numa_group *ng;
1476 ng = rcu_dereference(p->numa_group);
1485 * The averaged statistics, shared & private, memory & CPU,
1486 * occupy the first half of the array. The second half of the
1487 * array is for current counters, which are averaged into the
1488 * first set by task_numa_placement.
1490 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1492 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1495 static inline unsigned long task_faults(struct task_struct *p, int nid)
1497 if (!p->numa_faults)
1500 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1501 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1504 static inline unsigned long group_faults(struct task_struct *p, int nid)
1506 struct numa_group *ng = deref_task_numa_group(p);
1511 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1512 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1515 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1517 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1518 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1521 static inline unsigned long group_faults_priv(struct numa_group *ng)
1523 unsigned long faults = 0;
1526 for_each_online_node(node) {
1527 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1533 static inline unsigned long group_faults_shared(struct numa_group *ng)
1535 unsigned long faults = 0;
1538 for_each_online_node(node) {
1539 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1546 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1547 * considered part of a numa group's pseudo-interleaving set. Migrations
1548 * between these nodes are slowed down, to allow things to settle down.
1550 #define ACTIVE_NODE_FRACTION 3
1552 static bool numa_is_active_node(int nid, struct numa_group *ng)
1554 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1557 /* Handle placement on systems where not all nodes are directly connected. */
1558 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1559 int lim_dist, bool task)
1561 unsigned long score = 0;
1565 * All nodes are directly connected, and the same distance
1566 * from each other. No need for fancy placement algorithms.
1568 if (sched_numa_topology_type == NUMA_DIRECT)
1571 /* sched_max_numa_distance may be changed in parallel. */
1572 max_dist = READ_ONCE(sched_max_numa_distance);
1574 * This code is called for each node, introducing N^2 complexity,
1575 * which should be ok given the number of nodes rarely exceeds 8.
1577 for_each_online_node(node) {
1578 unsigned long faults;
1579 int dist = node_distance(nid, node);
1582 * The furthest away nodes in the system are not interesting
1583 * for placement; nid was already counted.
1585 if (dist >= max_dist || node == nid)
1589 * On systems with a backplane NUMA topology, compare groups
1590 * of nodes, and move tasks towards the group with the most
1591 * memory accesses. When comparing two nodes at distance
1592 * "hoplimit", only nodes closer by than "hoplimit" are part
1593 * of each group. Skip other nodes.
1595 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1598 /* Add up the faults from nearby nodes. */
1600 faults = task_faults(p, node);
1602 faults = group_faults(p, node);
1605 * On systems with a glueless mesh NUMA topology, there are
1606 * no fixed "groups of nodes". Instead, nodes that are not
1607 * directly connected bounce traffic through intermediate
1608 * nodes; a numa_group can occupy any set of nodes.
1609 * The further away a node is, the less the faults count.
1610 * This seems to result in good task placement.
1612 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1613 faults *= (max_dist - dist);
1614 faults /= (max_dist - LOCAL_DISTANCE);
1624 * These return the fraction of accesses done by a particular task, or
1625 * task group, on a particular numa node. The group weight is given a
1626 * larger multiplier, in order to group tasks together that are almost
1627 * evenly spread out between numa nodes.
1629 static inline unsigned long task_weight(struct task_struct *p, int nid,
1632 unsigned long faults, total_faults;
1634 if (!p->numa_faults)
1637 total_faults = p->total_numa_faults;
1642 faults = task_faults(p, nid);
1643 faults += score_nearby_nodes(p, nid, dist, true);
1645 return 1000 * faults / total_faults;
1648 static inline unsigned long group_weight(struct task_struct *p, int nid,
1651 struct numa_group *ng = deref_task_numa_group(p);
1652 unsigned long faults, total_faults;
1657 total_faults = ng->total_faults;
1662 faults = group_faults(p, nid);
1663 faults += score_nearby_nodes(p, nid, dist, false);
1665 return 1000 * faults / total_faults;
1669 * If memory tiering mode is enabled, cpupid of slow memory page is
1670 * used to record scan time instead of CPU and PID. When tiering mode
1671 * is disabled at run time, the scan time (in cpupid) will be
1672 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1673 * access out of array bound.
1675 static inline bool cpupid_valid(int cpupid)
1677 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1681 * For memory tiering mode, if there are enough free pages (more than
1682 * enough watermark defined here) in fast memory node, to take full
1683 * advantage of fast memory capacity, all recently accessed slow
1684 * memory pages will be migrated to fast memory node without
1685 * considering hot threshold.
1687 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1690 unsigned long enough_wmark;
1692 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1693 pgdat->node_present_pages >> 4);
1694 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1695 struct zone *zone = pgdat->node_zones + z;
1697 if (!populated_zone(zone))
1700 if (zone_watermark_ok(zone, 0,
1701 wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1709 * For memory tiering mode, when page tables are scanned, the scan
1710 * time will be recorded in struct page in addition to make page
1711 * PROT_NONE for slow memory page. So when the page is accessed, in
1712 * hint page fault handler, the hint page fault latency is calculated
1715 * hint page fault latency = hint page fault time - scan time
1717 * The smaller the hint page fault latency, the higher the possibility
1718 * for the page to be hot.
1720 static int numa_hint_fault_latency(struct page *page)
1722 int last_time, time;
1724 time = jiffies_to_msecs(jiffies);
1725 last_time = xchg_page_access_time(page, time);
1727 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1731 * For memory tiering mode, too high promotion/demotion throughput may
1732 * hurt application latency. So we provide a mechanism to rate limit
1733 * the number of pages that are tried to be promoted.
1735 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1736 unsigned long rate_limit, int nr)
1738 unsigned long nr_cand;
1739 unsigned int now, start;
1741 now = jiffies_to_msecs(jiffies);
1742 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1743 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1744 start = pgdat->nbp_rl_start;
1745 if (now - start > MSEC_PER_SEC &&
1746 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1747 pgdat->nbp_rl_nr_cand = nr_cand;
1748 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1753 #define NUMA_MIGRATION_ADJUST_STEPS 16
1755 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1756 unsigned long rate_limit,
1757 unsigned int ref_th)
1759 unsigned int now, start, th_period, unit_th, th;
1760 unsigned long nr_cand, ref_cand, diff_cand;
1762 now = jiffies_to_msecs(jiffies);
1763 th_period = sysctl_numa_balancing_scan_period_max;
1764 start = pgdat->nbp_th_start;
1765 if (now - start > th_period &&
1766 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1767 ref_cand = rate_limit *
1768 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1769 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1770 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1771 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1772 th = pgdat->nbp_threshold ? : ref_th;
1773 if (diff_cand > ref_cand * 11 / 10)
1774 th = max(th - unit_th, unit_th);
1775 else if (diff_cand < ref_cand * 9 / 10)
1776 th = min(th + unit_th, ref_th * 2);
1777 pgdat->nbp_th_nr_cand = nr_cand;
1778 pgdat->nbp_threshold = th;
1782 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1783 int src_nid, int dst_cpu)
1785 struct numa_group *ng = deref_curr_numa_group(p);
1786 int dst_nid = cpu_to_node(dst_cpu);
1787 int last_cpupid, this_cpupid;
1790 * The pages in slow memory node should be migrated according
1791 * to hot/cold instead of private/shared.
1793 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1794 !node_is_toptier(src_nid)) {
1795 struct pglist_data *pgdat;
1796 unsigned long rate_limit;
1797 unsigned int latency, th, def_th;
1799 pgdat = NODE_DATA(dst_nid);
1800 if (pgdat_free_space_enough(pgdat)) {
1801 /* workload changed, reset hot threshold */
1802 pgdat->nbp_threshold = 0;
1806 def_th = sysctl_numa_balancing_hot_threshold;
1807 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1809 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1811 th = pgdat->nbp_threshold ? : def_th;
1812 latency = numa_hint_fault_latency(page);
1816 return !numa_promotion_rate_limit(pgdat, rate_limit,
1817 thp_nr_pages(page));
1820 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1821 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1823 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1824 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1828 * Allow first faults or private faults to migrate immediately early in
1829 * the lifetime of a task. The magic number 4 is based on waiting for
1830 * two full passes of the "multi-stage node selection" test that is
1833 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1834 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1838 * Multi-stage node selection is used in conjunction with a periodic
1839 * migration fault to build a temporal task<->page relation. By using
1840 * a two-stage filter we remove short/unlikely relations.
1842 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1843 * a task's usage of a particular page (n_p) per total usage of this
1844 * page (n_t) (in a given time-span) to a probability.
1846 * Our periodic faults will sample this probability and getting the
1847 * same result twice in a row, given these samples are fully
1848 * independent, is then given by P(n)^2, provided our sample period
1849 * is sufficiently short compared to the usage pattern.
1851 * This quadric squishes small probabilities, making it less likely we
1852 * act on an unlikely task<->page relation.
1854 if (!cpupid_pid_unset(last_cpupid) &&
1855 cpupid_to_nid(last_cpupid) != dst_nid)
1858 /* Always allow migrate on private faults */
1859 if (cpupid_match_pid(p, last_cpupid))
1862 /* A shared fault, but p->numa_group has not been set up yet. */
1867 * Destination node is much more heavily used than the source
1868 * node? Allow migration.
1870 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1871 ACTIVE_NODE_FRACTION)
1875 * Distribute memory according to CPU & memory use on each node,
1876 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1878 * faults_cpu(dst) 3 faults_cpu(src)
1879 * --------------- * - > ---------------
1880 * faults_mem(dst) 4 faults_mem(src)
1882 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1883 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1887 * 'numa_type' describes the node at the moment of load balancing.
1890 /* The node has spare capacity that can be used to run more tasks. */
1893 * The node is fully used and the tasks don't compete for more CPU
1894 * cycles. Nevertheless, some tasks might wait before running.
1898 * The node is overloaded and can't provide expected CPU cycles to all
1904 /* Cached statistics for all CPUs within a node */
1907 unsigned long runnable;
1909 /* Total compute capacity of CPUs on a node */
1910 unsigned long compute_capacity;
1911 unsigned int nr_running;
1912 unsigned int weight;
1913 enum numa_type node_type;
1917 struct task_numa_env {
1918 struct task_struct *p;
1920 int src_cpu, src_nid;
1921 int dst_cpu, dst_nid;
1924 struct numa_stats src_stats, dst_stats;
1929 struct task_struct *best_task;
1934 static unsigned long cpu_load(struct rq *rq);
1935 static unsigned long cpu_runnable(struct rq *rq);
1938 numa_type numa_classify(unsigned int imbalance_pct,
1939 struct numa_stats *ns)
1941 if ((ns->nr_running > ns->weight) &&
1942 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
1943 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
1944 return node_overloaded;
1946 if ((ns->nr_running < ns->weight) ||
1947 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
1948 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
1949 return node_has_spare;
1951 return node_fully_busy;
1954 #ifdef CONFIG_SCHED_SMT
1955 /* Forward declarations of select_idle_sibling helpers */
1956 static inline bool test_idle_cores(int cpu);
1957 static inline int numa_idle_core(int idle_core, int cpu)
1959 if (!static_branch_likely(&sched_smt_present) ||
1960 idle_core >= 0 || !test_idle_cores(cpu))
1964 * Prefer cores instead of packing HT siblings
1965 * and triggering future load balancing.
1967 if (is_core_idle(cpu))
1973 static inline int numa_idle_core(int idle_core, int cpu)
1980 * Gather all necessary information to make NUMA balancing placement
1981 * decisions that are compatible with standard load balancer. This
1982 * borrows code and logic from update_sg_lb_stats but sharing a
1983 * common implementation is impractical.
1985 static void update_numa_stats(struct task_numa_env *env,
1986 struct numa_stats *ns, int nid,
1989 int cpu, idle_core = -1;
1991 memset(ns, 0, sizeof(*ns));
1995 for_each_cpu(cpu, cpumask_of_node(nid)) {
1996 struct rq *rq = cpu_rq(cpu);
1998 ns->load += cpu_load(rq);
1999 ns->runnable += cpu_runnable(rq);
2000 ns->util += cpu_util_cfs(cpu);
2001 ns->nr_running += rq->cfs.h_nr_running;
2002 ns->compute_capacity += capacity_of(cpu);
2004 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2005 if (READ_ONCE(rq->numa_migrate_on) ||
2006 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2009 if (ns->idle_cpu == -1)
2012 idle_core = numa_idle_core(idle_core, cpu);
2017 ns->weight = cpumask_weight(cpumask_of_node(nid));
2019 ns->node_type = numa_classify(env->imbalance_pct, ns);
2022 ns->idle_cpu = idle_core;
2025 static void task_numa_assign(struct task_numa_env *env,
2026 struct task_struct *p, long imp)
2028 struct rq *rq = cpu_rq(env->dst_cpu);
2030 /* Check if run-queue part of active NUMA balance. */
2031 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2033 int start = env->dst_cpu;
2035 /* Find alternative idle CPU. */
2036 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2037 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2038 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2043 rq = cpu_rq(env->dst_cpu);
2044 if (!xchg(&rq->numa_migrate_on, 1))
2048 /* Failed to find an alternative idle CPU */
2054 * Clear previous best_cpu/rq numa-migrate flag, since task now
2055 * found a better CPU to move/swap.
2057 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2058 rq = cpu_rq(env->best_cpu);
2059 WRITE_ONCE(rq->numa_migrate_on, 0);
2063 put_task_struct(env->best_task);
2068 env->best_imp = imp;
2069 env->best_cpu = env->dst_cpu;
2072 static bool load_too_imbalanced(long src_load, long dst_load,
2073 struct task_numa_env *env)
2076 long orig_src_load, orig_dst_load;
2077 long src_capacity, dst_capacity;
2080 * The load is corrected for the CPU capacity available on each node.
2083 * ------------ vs ---------
2084 * src_capacity dst_capacity
2086 src_capacity = env->src_stats.compute_capacity;
2087 dst_capacity = env->dst_stats.compute_capacity;
2089 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2091 orig_src_load = env->src_stats.load;
2092 orig_dst_load = env->dst_stats.load;
2094 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2096 /* Would this change make things worse? */
2097 return (imb > old_imb);
2101 * Maximum NUMA importance can be 1998 (2*999);
2102 * SMALLIMP @ 30 would be close to 1998/64.
2103 * Used to deter task migration.
2108 * This checks if the overall compute and NUMA accesses of the system would
2109 * be improved if the source tasks was migrated to the target dst_cpu taking
2110 * into account that it might be best if task running on the dst_cpu should
2111 * be exchanged with the source task
2113 static bool task_numa_compare(struct task_numa_env *env,
2114 long taskimp, long groupimp, bool maymove)
2116 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2117 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2118 long imp = p_ng ? groupimp : taskimp;
2119 struct task_struct *cur;
2120 long src_load, dst_load;
2121 int dist = env->dist;
2124 bool stopsearch = false;
2126 if (READ_ONCE(dst_rq->numa_migrate_on))
2130 cur = rcu_dereference(dst_rq->curr);
2131 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2135 * Because we have preemption enabled we can get migrated around and
2136 * end try selecting ourselves (current == env->p) as a swap candidate.
2138 if (cur == env->p) {
2144 if (maymove && moveimp >= env->best_imp)
2150 /* Skip this swap candidate if cannot move to the source cpu. */
2151 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2155 * Skip this swap candidate if it is not moving to its preferred
2156 * node and the best task is.
2158 if (env->best_task &&
2159 env->best_task->numa_preferred_nid == env->src_nid &&
2160 cur->numa_preferred_nid != env->src_nid) {
2165 * "imp" is the fault differential for the source task between the
2166 * source and destination node. Calculate the total differential for
2167 * the source task and potential destination task. The more negative
2168 * the value is, the more remote accesses that would be expected to
2169 * be incurred if the tasks were swapped.
2171 * If dst and source tasks are in the same NUMA group, or not
2172 * in any group then look only at task weights.
2174 cur_ng = rcu_dereference(cur->numa_group);
2175 if (cur_ng == p_ng) {
2177 * Do not swap within a group or between tasks that have
2178 * no group if there is spare capacity. Swapping does
2179 * not address the load imbalance and helps one task at
2180 * the cost of punishing another.
2182 if (env->dst_stats.node_type == node_has_spare)
2185 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2186 task_weight(cur, env->dst_nid, dist);
2188 * Add some hysteresis to prevent swapping the
2189 * tasks within a group over tiny differences.
2195 * Compare the group weights. If a task is all by itself
2196 * (not part of a group), use the task weight instead.
2199 imp += group_weight(cur, env->src_nid, dist) -
2200 group_weight(cur, env->dst_nid, dist);
2202 imp += task_weight(cur, env->src_nid, dist) -
2203 task_weight(cur, env->dst_nid, dist);
2206 /* Discourage picking a task already on its preferred node */
2207 if (cur->numa_preferred_nid == env->dst_nid)
2211 * Encourage picking a task that moves to its preferred node.
2212 * This potentially makes imp larger than it's maximum of
2213 * 1998 (see SMALLIMP and task_weight for why) but in this
2214 * case, it does not matter.
2216 if (cur->numa_preferred_nid == env->src_nid)
2219 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2226 * Prefer swapping with a task moving to its preferred node over a
2229 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2230 env->best_task->numa_preferred_nid != env->src_nid) {
2235 * If the NUMA importance is less than SMALLIMP,
2236 * task migration might only result in ping pong
2237 * of tasks and also hurt performance due to cache
2240 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2244 * In the overloaded case, try and keep the load balanced.
2246 load = task_h_load(env->p) - task_h_load(cur);
2250 dst_load = env->dst_stats.load + load;
2251 src_load = env->src_stats.load - load;
2253 if (load_too_imbalanced(src_load, dst_load, env))
2257 /* Evaluate an idle CPU for a task numa move. */
2259 int cpu = env->dst_stats.idle_cpu;
2261 /* Nothing cached so current CPU went idle since the search. */
2266 * If the CPU is no longer truly idle and the previous best CPU
2267 * is, keep using it.
2269 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2270 idle_cpu(env->best_cpu)) {
2271 cpu = env->best_cpu;
2277 task_numa_assign(env, cur, imp);
2280 * If a move to idle is allowed because there is capacity or load
2281 * balance improves then stop the search. While a better swap
2282 * candidate may exist, a search is not free.
2284 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2288 * If a swap candidate must be identified and the current best task
2289 * moves its preferred node then stop the search.
2291 if (!maymove && env->best_task &&
2292 env->best_task->numa_preferred_nid == env->src_nid) {
2301 static void task_numa_find_cpu(struct task_numa_env *env,
2302 long taskimp, long groupimp)
2304 bool maymove = false;
2308 * If dst node has spare capacity, then check if there is an
2309 * imbalance that would be overruled by the load balancer.
2311 if (env->dst_stats.node_type == node_has_spare) {
2312 unsigned int imbalance;
2313 int src_running, dst_running;
2316 * Would movement cause an imbalance? Note that if src has
2317 * more running tasks that the imbalance is ignored as the
2318 * move improves the imbalance from the perspective of the
2319 * CPU load balancer.
2321 src_running = env->src_stats.nr_running - 1;
2322 dst_running = env->dst_stats.nr_running + 1;
2323 imbalance = max(0, dst_running - src_running);
2324 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2327 /* Use idle CPU if there is no imbalance */
2330 if (env->dst_stats.idle_cpu >= 0) {
2331 env->dst_cpu = env->dst_stats.idle_cpu;
2332 task_numa_assign(env, NULL, 0);
2337 long src_load, dst_load, load;
2339 * If the improvement from just moving env->p direction is better
2340 * than swapping tasks around, check if a move is possible.
2342 load = task_h_load(env->p);
2343 dst_load = env->dst_stats.load + load;
2344 src_load = env->src_stats.load - load;
2345 maymove = !load_too_imbalanced(src_load, dst_load, env);
2348 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2349 /* Skip this CPU if the source task cannot migrate */
2350 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2354 if (task_numa_compare(env, taskimp, groupimp, maymove))
2359 static int task_numa_migrate(struct task_struct *p)
2361 struct task_numa_env env = {
2364 .src_cpu = task_cpu(p),
2365 .src_nid = task_node(p),
2367 .imbalance_pct = 112,
2373 unsigned long taskweight, groupweight;
2374 struct sched_domain *sd;
2375 long taskimp, groupimp;
2376 struct numa_group *ng;
2381 * Pick the lowest SD_NUMA domain, as that would have the smallest
2382 * imbalance and would be the first to start moving tasks about.
2384 * And we want to avoid any moving of tasks about, as that would create
2385 * random movement of tasks -- counter the numa conditions we're trying
2389 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2391 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2392 env.imb_numa_nr = sd->imb_numa_nr;
2397 * Cpusets can break the scheduler domain tree into smaller
2398 * balance domains, some of which do not cross NUMA boundaries.
2399 * Tasks that are "trapped" in such domains cannot be migrated
2400 * elsewhere, so there is no point in (re)trying.
2402 if (unlikely(!sd)) {
2403 sched_setnuma(p, task_node(p));
2407 env.dst_nid = p->numa_preferred_nid;
2408 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2409 taskweight = task_weight(p, env.src_nid, dist);
2410 groupweight = group_weight(p, env.src_nid, dist);
2411 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2412 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2413 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2414 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2416 /* Try to find a spot on the preferred nid. */
2417 task_numa_find_cpu(&env, taskimp, groupimp);
2420 * Look at other nodes in these cases:
2421 * - there is no space available on the preferred_nid
2422 * - the task is part of a numa_group that is interleaved across
2423 * multiple NUMA nodes; in order to better consolidate the group,
2424 * we need to check other locations.
2426 ng = deref_curr_numa_group(p);
2427 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2428 for_each_node_state(nid, N_CPU) {
2429 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2432 dist = node_distance(env.src_nid, env.dst_nid);
2433 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2435 taskweight = task_weight(p, env.src_nid, dist);
2436 groupweight = group_weight(p, env.src_nid, dist);
2439 /* Only consider nodes where both task and groups benefit */
2440 taskimp = task_weight(p, nid, dist) - taskweight;
2441 groupimp = group_weight(p, nid, dist) - groupweight;
2442 if (taskimp < 0 && groupimp < 0)
2447 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2448 task_numa_find_cpu(&env, taskimp, groupimp);
2453 * If the task is part of a workload that spans multiple NUMA nodes,
2454 * and is migrating into one of the workload's active nodes, remember
2455 * this node as the task's preferred numa node, so the workload can
2457 * A task that migrated to a second choice node will be better off
2458 * trying for a better one later. Do not set the preferred node here.
2461 if (env.best_cpu == -1)
2464 nid = cpu_to_node(env.best_cpu);
2466 if (nid != p->numa_preferred_nid)
2467 sched_setnuma(p, nid);
2470 /* No better CPU than the current one was found. */
2471 if (env.best_cpu == -1) {
2472 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2476 best_rq = cpu_rq(env.best_cpu);
2477 if (env.best_task == NULL) {
2478 ret = migrate_task_to(p, env.best_cpu);
2479 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2481 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2485 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2486 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2489 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2490 put_task_struct(env.best_task);
2494 /* Attempt to migrate a task to a CPU on the preferred node. */
2495 static void numa_migrate_preferred(struct task_struct *p)
2497 unsigned long interval = HZ;
2499 /* This task has no NUMA fault statistics yet */
2500 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2503 /* Periodically retry migrating the task to the preferred node */
2504 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2505 p->numa_migrate_retry = jiffies + interval;
2507 /* Success if task is already running on preferred CPU */
2508 if (task_node(p) == p->numa_preferred_nid)
2511 /* Otherwise, try migrate to a CPU on the preferred node */
2512 task_numa_migrate(p);
2516 * Find out how many nodes the workload is actively running on. Do this by
2517 * tracking the nodes from which NUMA hinting faults are triggered. This can
2518 * be different from the set of nodes where the workload's memory is currently
2521 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2523 unsigned long faults, max_faults = 0;
2524 int nid, active_nodes = 0;
2526 for_each_node_state(nid, N_CPU) {
2527 faults = group_faults_cpu(numa_group, nid);
2528 if (faults > max_faults)
2529 max_faults = faults;
2532 for_each_node_state(nid, N_CPU) {
2533 faults = group_faults_cpu(numa_group, nid);
2534 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2538 numa_group->max_faults_cpu = max_faults;
2539 numa_group->active_nodes = active_nodes;
2543 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2544 * increments. The more local the fault statistics are, the higher the scan
2545 * period will be for the next scan window. If local/(local+remote) ratio is
2546 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2547 * the scan period will decrease. Aim for 70% local accesses.
2549 #define NUMA_PERIOD_SLOTS 10
2550 #define NUMA_PERIOD_THRESHOLD 7
2553 * Increase the scan period (slow down scanning) if the majority of
2554 * our memory is already on our local node, or if the majority of
2555 * the page accesses are shared with other processes.
2556 * Otherwise, decrease the scan period.
2558 static void update_task_scan_period(struct task_struct *p,
2559 unsigned long shared, unsigned long private)
2561 unsigned int period_slot;
2562 int lr_ratio, ps_ratio;
2565 unsigned long remote = p->numa_faults_locality[0];
2566 unsigned long local = p->numa_faults_locality[1];
2569 * If there were no record hinting faults then either the task is
2570 * completely idle or all activity is in areas that are not of interest
2571 * to automatic numa balancing. Related to that, if there were failed
2572 * migration then it implies we are migrating too quickly or the local
2573 * node is overloaded. In either case, scan slower
2575 if (local + shared == 0 || p->numa_faults_locality[2]) {
2576 p->numa_scan_period = min(p->numa_scan_period_max,
2577 p->numa_scan_period << 1);
2579 p->mm->numa_next_scan = jiffies +
2580 msecs_to_jiffies(p->numa_scan_period);
2586 * Prepare to scale scan period relative to the current period.
2587 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2588 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2589 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2591 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2592 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2593 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2595 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2597 * Most memory accesses are local. There is no need to
2598 * do fast NUMA scanning, since memory is already local.
2600 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2603 diff = slot * period_slot;
2604 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2606 * Most memory accesses are shared with other tasks.
2607 * There is no point in continuing fast NUMA scanning,
2608 * since other tasks may just move the memory elsewhere.
2610 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2613 diff = slot * period_slot;
2616 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2617 * yet they are not on the local NUMA node. Speed up
2618 * NUMA scanning to get the memory moved over.
2620 int ratio = max(lr_ratio, ps_ratio);
2621 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2624 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2625 task_scan_min(p), task_scan_max(p));
2626 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2630 * Get the fraction of time the task has been running since the last
2631 * NUMA placement cycle. The scheduler keeps similar statistics, but
2632 * decays those on a 32ms period, which is orders of magnitude off
2633 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2634 * stats only if the task is so new there are no NUMA statistics yet.
2636 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2638 u64 runtime, delta, now;
2639 /* Use the start of this time slice to avoid calculations. */
2640 now = p->se.exec_start;
2641 runtime = p->se.sum_exec_runtime;
2643 if (p->last_task_numa_placement) {
2644 delta = runtime - p->last_sum_exec_runtime;
2645 *period = now - p->last_task_numa_placement;
2647 /* Avoid time going backwards, prevent potential divide error: */
2648 if (unlikely((s64)*period < 0))
2651 delta = p->se.avg.load_sum;
2652 *period = LOAD_AVG_MAX;
2655 p->last_sum_exec_runtime = runtime;
2656 p->last_task_numa_placement = now;
2662 * Determine the preferred nid for a task in a numa_group. This needs to
2663 * be done in a way that produces consistent results with group_weight,
2664 * otherwise workloads might not converge.
2666 static int preferred_group_nid(struct task_struct *p, int nid)
2671 /* Direct connections between all NUMA nodes. */
2672 if (sched_numa_topology_type == NUMA_DIRECT)
2676 * On a system with glueless mesh NUMA topology, group_weight
2677 * scores nodes according to the number of NUMA hinting faults on
2678 * both the node itself, and on nearby nodes.
2680 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2681 unsigned long score, max_score = 0;
2682 int node, max_node = nid;
2684 dist = sched_max_numa_distance;
2686 for_each_node_state(node, N_CPU) {
2687 score = group_weight(p, node, dist);
2688 if (score > max_score) {
2697 * Finding the preferred nid in a system with NUMA backplane
2698 * interconnect topology is more involved. The goal is to locate
2699 * tasks from numa_groups near each other in the system, and
2700 * untangle workloads from different sides of the system. This requires
2701 * searching down the hierarchy of node groups, recursively searching
2702 * inside the highest scoring group of nodes. The nodemask tricks
2703 * keep the complexity of the search down.
2705 nodes = node_states[N_CPU];
2706 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2707 unsigned long max_faults = 0;
2708 nodemask_t max_group = NODE_MASK_NONE;
2711 /* Are there nodes at this distance from each other? */
2712 if (!find_numa_distance(dist))
2715 for_each_node_mask(a, nodes) {
2716 unsigned long faults = 0;
2717 nodemask_t this_group;
2718 nodes_clear(this_group);
2720 /* Sum group's NUMA faults; includes a==b case. */
2721 for_each_node_mask(b, nodes) {
2722 if (node_distance(a, b) < dist) {
2723 faults += group_faults(p, b);
2724 node_set(b, this_group);
2725 node_clear(b, nodes);
2729 /* Remember the top group. */
2730 if (faults > max_faults) {
2731 max_faults = faults;
2732 max_group = this_group;
2734 * subtle: at the smallest distance there is
2735 * just one node left in each "group", the
2736 * winner is the preferred nid.
2741 /* Next round, evaluate the nodes within max_group. */
2749 static void task_numa_placement(struct task_struct *p)
2751 int seq, nid, max_nid = NUMA_NO_NODE;
2752 unsigned long max_faults = 0;
2753 unsigned long fault_types[2] = { 0, 0 };
2754 unsigned long total_faults;
2755 u64 runtime, period;
2756 spinlock_t *group_lock = NULL;
2757 struct numa_group *ng;
2760 * The p->mm->numa_scan_seq field gets updated without
2761 * exclusive access. Use READ_ONCE() here to ensure
2762 * that the field is read in a single access:
2764 seq = READ_ONCE(p->mm->numa_scan_seq);
2765 if (p->numa_scan_seq == seq)
2767 p->numa_scan_seq = seq;
2768 p->numa_scan_period_max = task_scan_max(p);
2770 total_faults = p->numa_faults_locality[0] +
2771 p->numa_faults_locality[1];
2772 runtime = numa_get_avg_runtime(p, &period);
2774 /* If the task is part of a group prevent parallel updates to group stats */
2775 ng = deref_curr_numa_group(p);
2777 group_lock = &ng->lock;
2778 spin_lock_irq(group_lock);
2781 /* Find the node with the highest number of faults */
2782 for_each_online_node(nid) {
2783 /* Keep track of the offsets in numa_faults array */
2784 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2785 unsigned long faults = 0, group_faults = 0;
2788 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2789 long diff, f_diff, f_weight;
2791 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2792 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2793 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2794 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2796 /* Decay existing window, copy faults since last scan */
2797 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2798 fault_types[priv] += p->numa_faults[membuf_idx];
2799 p->numa_faults[membuf_idx] = 0;
2802 * Normalize the faults_from, so all tasks in a group
2803 * count according to CPU use, instead of by the raw
2804 * number of faults. Tasks with little runtime have
2805 * little over-all impact on throughput, and thus their
2806 * faults are less important.
2808 f_weight = div64_u64(runtime << 16, period + 1);
2809 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2811 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2812 p->numa_faults[cpubuf_idx] = 0;
2814 p->numa_faults[mem_idx] += diff;
2815 p->numa_faults[cpu_idx] += f_diff;
2816 faults += p->numa_faults[mem_idx];
2817 p->total_numa_faults += diff;
2820 * safe because we can only change our own group
2822 * mem_idx represents the offset for a given
2823 * nid and priv in a specific region because it
2824 * is at the beginning of the numa_faults array.
2826 ng->faults[mem_idx] += diff;
2827 ng->faults[cpu_idx] += f_diff;
2828 ng->total_faults += diff;
2829 group_faults += ng->faults[mem_idx];
2834 if (faults > max_faults) {
2835 max_faults = faults;
2838 } else if (group_faults > max_faults) {
2839 max_faults = group_faults;
2844 /* Cannot migrate task to CPU-less node */
2845 max_nid = numa_nearest_node(max_nid, N_CPU);
2848 numa_group_count_active_nodes(ng);
2849 spin_unlock_irq(group_lock);
2850 max_nid = preferred_group_nid(p, max_nid);
2854 /* Set the new preferred node */
2855 if (max_nid != p->numa_preferred_nid)
2856 sched_setnuma(p, max_nid);
2859 update_task_scan_period(p, fault_types[0], fault_types[1]);
2862 static inline int get_numa_group(struct numa_group *grp)
2864 return refcount_inc_not_zero(&grp->refcount);
2867 static inline void put_numa_group(struct numa_group *grp)
2869 if (refcount_dec_and_test(&grp->refcount))
2870 kfree_rcu(grp, rcu);
2873 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2876 struct numa_group *grp, *my_grp;
2877 struct task_struct *tsk;
2879 int cpu = cpupid_to_cpu(cpupid);
2882 if (unlikely(!deref_curr_numa_group(p))) {
2883 unsigned int size = sizeof(struct numa_group) +
2884 NR_NUMA_HINT_FAULT_STATS *
2885 nr_node_ids * sizeof(unsigned long);
2887 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2891 refcount_set(&grp->refcount, 1);
2892 grp->active_nodes = 1;
2893 grp->max_faults_cpu = 0;
2894 spin_lock_init(&grp->lock);
2897 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2898 grp->faults[i] = p->numa_faults[i];
2900 grp->total_faults = p->total_numa_faults;
2903 rcu_assign_pointer(p->numa_group, grp);
2907 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2909 if (!cpupid_match_pid(tsk, cpupid))
2912 grp = rcu_dereference(tsk->numa_group);
2916 my_grp = deref_curr_numa_group(p);
2921 * Only join the other group if its bigger; if we're the bigger group,
2922 * the other task will join us.
2924 if (my_grp->nr_tasks > grp->nr_tasks)
2928 * Tie-break on the grp address.
2930 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2933 /* Always join threads in the same process. */
2934 if (tsk->mm == current->mm)
2937 /* Simple filter to avoid false positives due to PID collisions */
2938 if (flags & TNF_SHARED)
2941 /* Update priv based on whether false sharing was detected */
2944 if (join && !get_numa_group(grp))
2952 WARN_ON_ONCE(irqs_disabled());
2953 double_lock_irq(&my_grp->lock, &grp->lock);
2955 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2956 my_grp->faults[i] -= p->numa_faults[i];
2957 grp->faults[i] += p->numa_faults[i];
2959 my_grp->total_faults -= p->total_numa_faults;
2960 grp->total_faults += p->total_numa_faults;
2965 spin_unlock(&my_grp->lock);
2966 spin_unlock_irq(&grp->lock);
2968 rcu_assign_pointer(p->numa_group, grp);
2970 put_numa_group(my_grp);
2979 * Get rid of NUMA statistics associated with a task (either current or dead).
2980 * If @final is set, the task is dead and has reached refcount zero, so we can
2981 * safely free all relevant data structures. Otherwise, there might be
2982 * concurrent reads from places like load balancing and procfs, and we should
2983 * reset the data back to default state without freeing ->numa_faults.
2985 void task_numa_free(struct task_struct *p, bool final)
2987 /* safe: p either is current or is being freed by current */
2988 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
2989 unsigned long *numa_faults = p->numa_faults;
2990 unsigned long flags;
2997 spin_lock_irqsave(&grp->lock, flags);
2998 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2999 grp->faults[i] -= p->numa_faults[i];
3000 grp->total_faults -= p->total_numa_faults;
3003 spin_unlock_irqrestore(&grp->lock, flags);
3004 RCU_INIT_POINTER(p->numa_group, NULL);
3005 put_numa_group(grp);
3009 p->numa_faults = NULL;
3012 p->total_numa_faults = 0;
3013 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3019 * Got a PROT_NONE fault for a page on @node.
3021 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3023 struct task_struct *p = current;
3024 bool migrated = flags & TNF_MIGRATED;
3025 int cpu_node = task_node(current);
3026 int local = !!(flags & TNF_FAULT_LOCAL);
3027 struct numa_group *ng;
3030 if (!static_branch_likely(&sched_numa_balancing))
3033 /* for example, ksmd faulting in a user's mm */
3038 * NUMA faults statistics are unnecessary for the slow memory
3039 * node for memory tiering mode.
3041 if (!node_is_toptier(mem_node) &&
3042 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3043 !cpupid_valid(last_cpupid)))
3046 /* Allocate buffer to track faults on a per-node basis */
3047 if (unlikely(!p->numa_faults)) {
3048 int size = sizeof(*p->numa_faults) *
3049 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3051 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3052 if (!p->numa_faults)
3055 p->total_numa_faults = 0;
3056 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3060 * First accesses are treated as private, otherwise consider accesses
3061 * to be private if the accessing pid has not changed
3063 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3066 priv = cpupid_match_pid(p, last_cpupid);
3067 if (!priv && !(flags & TNF_NO_GROUP))
3068 task_numa_group(p, last_cpupid, flags, &priv);
3072 * If a workload spans multiple NUMA nodes, a shared fault that
3073 * occurs wholly within the set of nodes that the workload is
3074 * actively using should be counted as local. This allows the
3075 * scan rate to slow down when a workload has settled down.
3077 ng = deref_curr_numa_group(p);
3078 if (!priv && !local && ng && ng->active_nodes > 1 &&
3079 numa_is_active_node(cpu_node, ng) &&
3080 numa_is_active_node(mem_node, ng))
3084 * Retry to migrate task to preferred node periodically, in case it
3085 * previously failed, or the scheduler moved us.
3087 if (time_after(jiffies, p->numa_migrate_retry)) {
3088 task_numa_placement(p);
3089 numa_migrate_preferred(p);
3093 p->numa_pages_migrated += pages;
3094 if (flags & TNF_MIGRATE_FAIL)
3095 p->numa_faults_locality[2] += pages;
3097 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3098 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3099 p->numa_faults_locality[local] += pages;
3102 static void reset_ptenuma_scan(struct task_struct *p)
3105 * We only did a read acquisition of the mmap sem, so
3106 * p->mm->numa_scan_seq is written to without exclusive access
3107 * and the update is not guaranteed to be atomic. That's not
3108 * much of an issue though, since this is just used for
3109 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3110 * expensive, to avoid any form of compiler optimizations:
3112 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3113 p->mm->numa_scan_offset = 0;
3116 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3120 * Allow unconditional access first two times, so that all the (pages)
3121 * of VMAs get prot_none fault introduced irrespective of accesses.
3122 * This is also done to avoid any side effect of task scanning
3123 * amplifying the unfairness of disjoint set of VMAs' access.
3125 if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3128 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3129 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3133 * Complete a scan that has already started regardless of PID access, or
3134 * some VMAs may never be scanned in multi-threaded applications:
3136 if (mm->numa_scan_offset > vma->vm_start) {
3137 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3144 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3147 * The expensive part of numa migration is done from task_work context.
3148 * Triggered from task_tick_numa().
3150 static void task_numa_work(struct callback_head *work)
3152 unsigned long migrate, next_scan, now = jiffies;
3153 struct task_struct *p = current;
3154 struct mm_struct *mm = p->mm;
3155 u64 runtime = p->se.sum_exec_runtime;
3156 struct vm_area_struct *vma;
3157 unsigned long start, end;
3158 unsigned long nr_pte_updates = 0;
3159 long pages, virtpages;
3160 struct vma_iterator vmi;
3161 bool vma_pids_skipped;
3162 bool vma_pids_forced = false;
3164 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3168 * Who cares about NUMA placement when they're dying.
3170 * NOTE: make sure not to dereference p->mm before this check,
3171 * exit_task_work() happens _after_ exit_mm() so we could be called
3172 * without p->mm even though we still had it when we enqueued this
3175 if (p->flags & PF_EXITING)
3178 if (!mm->numa_next_scan) {
3179 mm->numa_next_scan = now +
3180 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3184 * Enforce maximal scan/migration frequency..
3186 migrate = mm->numa_next_scan;
3187 if (time_before(now, migrate))
3190 if (p->numa_scan_period == 0) {
3191 p->numa_scan_period_max = task_scan_max(p);
3192 p->numa_scan_period = task_scan_start(p);
3195 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3196 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3200 * Delay this task enough that another task of this mm will likely win
3201 * the next time around.
3203 p->node_stamp += 2 * TICK_NSEC;
3205 pages = sysctl_numa_balancing_scan_size;
3206 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3207 virtpages = pages * 8; /* Scan up to this much virtual space */
3212 if (!mmap_read_trylock(mm))
3216 * VMAs are skipped if the current PID has not trapped a fault within
3217 * the VMA recently. Allow scanning to be forced if there is no
3218 * suitable VMA remaining.
3220 vma_pids_skipped = false;
3223 start = mm->numa_scan_offset;
3224 vma_iter_init(&vmi, mm, start);
3225 vma = vma_next(&vmi);
3227 reset_ptenuma_scan(p);
3229 vma_iter_set(&vmi, start);
3230 vma = vma_next(&vmi);
3234 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3235 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3236 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3241 * Shared library pages mapped by multiple processes are not
3242 * migrated as it is expected they are cache replicated. Avoid
3243 * hinting faults in read-only file-backed mappings or the vdso
3244 * as migrating the pages will be of marginal benefit.
3247 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3248 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3253 * Skip inaccessible VMAs to avoid any confusion between
3254 * PROT_NONE and NUMA hinting ptes
3256 if (!vma_is_accessible(vma)) {
3257 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3261 /* Initialise new per-VMA NUMAB state. */
3262 if (!vma->numab_state) {
3263 vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3265 if (!vma->numab_state)
3268 vma->numab_state->next_scan = now +
3269 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3271 /* Reset happens after 4 times scan delay of scan start */
3272 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
3273 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3276 * Ensure prev_scan_seq does not match numa_scan_seq,
3277 * to prevent VMAs being skipped prematurely on the
3280 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3284 * Scanning the VMA's of short lived tasks add more overhead. So
3285 * delay the scan for new VMAs.
3287 if (mm->numa_scan_seq && time_before(jiffies,
3288 vma->numab_state->next_scan)) {
3289 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3293 /* RESET access PIDs regularly for old VMAs. */
3294 if (mm->numa_scan_seq &&
3295 time_after(jiffies, vma->numab_state->pids_active_reset)) {
3296 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3297 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3298 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3299 vma->numab_state->pids_active[1] = 0;
3302 /* Do not rescan VMAs twice within the same sequence. */
3303 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3304 mm->numa_scan_offset = vma->vm_end;
3305 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3310 * Do not scan the VMA if task has not accessed it, unless no other
3311 * VMA candidate exists.
3313 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3314 vma_pids_skipped = true;
3315 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3320 start = max(start, vma->vm_start);
3321 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3322 end = min(end, vma->vm_end);
3323 nr_pte_updates = change_prot_numa(vma, start, end);
3326 * Try to scan sysctl_numa_balancing_size worth of
3327 * hpages that have at least one present PTE that
3328 * is not already pte-numa. If the VMA contains
3329 * areas that are unused or already full of prot_numa
3330 * PTEs, scan up to virtpages, to skip through those
3334 pages -= (end - start) >> PAGE_SHIFT;
3335 virtpages -= (end - start) >> PAGE_SHIFT;
3338 if (pages <= 0 || virtpages <= 0)
3342 } while (end != vma->vm_end);
3344 /* VMA scan is complete, do not scan until next sequence. */
3345 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3348 * Only force scan within one VMA at a time, to limit the
3349 * cost of scanning a potentially uninteresting VMA.
3351 if (vma_pids_forced)
3353 } for_each_vma(vmi, vma);
3356 * If no VMAs are remaining and VMAs were skipped due to the PID
3357 * not accessing the VMA previously, then force a scan to ensure
3360 if (!vma && !vma_pids_forced && vma_pids_skipped) {
3361 vma_pids_forced = true;
3367 * It is possible to reach the end of the VMA list but the last few
3368 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3369 * would find the !migratable VMA on the next scan but not reset the
3370 * scanner to the start so check it now.
3373 mm->numa_scan_offset = start;
3375 reset_ptenuma_scan(p);
3376 mmap_read_unlock(mm);
3379 * Make sure tasks use at least 32x as much time to run other code
3380 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3381 * Usually update_task_scan_period slows down scanning enough; on an
3382 * overloaded system we need to limit overhead on a per task basis.
3384 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3385 u64 diff = p->se.sum_exec_runtime - runtime;
3386 p->node_stamp += 32 * diff;
3390 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3393 struct mm_struct *mm = p->mm;
3396 mm_users = atomic_read(&mm->mm_users);
3397 if (mm_users == 1) {
3398 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3399 mm->numa_scan_seq = 0;
3403 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3404 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3405 p->numa_migrate_retry = 0;
3406 /* Protect against double add, see task_tick_numa and task_numa_work */
3407 p->numa_work.next = &p->numa_work;
3408 p->numa_faults = NULL;
3409 p->numa_pages_migrated = 0;
3410 p->total_numa_faults = 0;
3411 RCU_INIT_POINTER(p->numa_group, NULL);
3412 p->last_task_numa_placement = 0;
3413 p->last_sum_exec_runtime = 0;
3415 init_task_work(&p->numa_work, task_numa_work);
3417 /* New address space, reset the preferred nid */
3418 if (!(clone_flags & CLONE_VM)) {
3419 p->numa_preferred_nid = NUMA_NO_NODE;
3424 * New thread, keep existing numa_preferred_nid which should be copied
3425 * already by arch_dup_task_struct but stagger when scans start.
3430 delay = min_t(unsigned int, task_scan_max(current),
3431 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3432 delay += 2 * TICK_NSEC;
3433 p->node_stamp = delay;
3438 * Drive the periodic memory faults..
3440 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3442 struct callback_head *work = &curr->numa_work;
3446 * We don't care about NUMA placement if we don't have memory.
3448 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3452 * Using runtime rather than walltime has the dual advantage that
3453 * we (mostly) drive the selection from busy threads and that the
3454 * task needs to have done some actual work before we bother with
3457 now = curr->se.sum_exec_runtime;
3458 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3460 if (now > curr->node_stamp + period) {
3461 if (!curr->node_stamp)
3462 curr->numa_scan_period = task_scan_start(curr);
3463 curr->node_stamp += period;
3465 if (!time_before(jiffies, curr->mm->numa_next_scan))
3466 task_work_add(curr, work, TWA_RESUME);
3470 static void update_scan_period(struct task_struct *p, int new_cpu)
3472 int src_nid = cpu_to_node(task_cpu(p));
3473 int dst_nid = cpu_to_node(new_cpu);
3475 if (!static_branch_likely(&sched_numa_balancing))
3478 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3481 if (src_nid == dst_nid)
3485 * Allow resets if faults have been trapped before one scan
3486 * has completed. This is most likely due to a new task that
3487 * is pulled cross-node due to wakeups or load balancing.
3489 if (p->numa_scan_seq) {
3491 * Avoid scan adjustments if moving to the preferred
3492 * node or if the task was not previously running on
3493 * the preferred node.
3495 if (dst_nid == p->numa_preferred_nid ||
3496 (p->numa_preferred_nid != NUMA_NO_NODE &&
3497 src_nid != p->numa_preferred_nid))
3501 p->numa_scan_period = task_scan_start(p);
3505 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3509 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3513 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3517 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3521 #endif /* CONFIG_NUMA_BALANCING */
3524 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3526 update_load_add(&cfs_rq->load, se->load.weight);
3528 if (entity_is_task(se)) {
3529 struct rq *rq = rq_of(cfs_rq);
3531 account_numa_enqueue(rq, task_of(se));
3532 list_add(&se->group_node, &rq->cfs_tasks);
3535 cfs_rq->nr_running++;
3537 cfs_rq->idle_nr_running++;
3541 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3543 update_load_sub(&cfs_rq->load, se->load.weight);
3545 if (entity_is_task(se)) {
3546 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3547 list_del_init(&se->group_node);
3550 cfs_rq->nr_running--;
3552 cfs_rq->idle_nr_running--;
3556 * Signed add and clamp on underflow.
3558 * Explicitly do a load-store to ensure the intermediate value never hits
3559 * memory. This allows lockless observations without ever seeing the negative
3562 #define add_positive(_ptr, _val) do { \
3563 typeof(_ptr) ptr = (_ptr); \
3564 typeof(_val) val = (_val); \
3565 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3569 if (val < 0 && res > var) \
3572 WRITE_ONCE(*ptr, res); \
3576 * Unsigned subtract and clamp on underflow.
3578 * Explicitly do a load-store to ensure the intermediate value never hits
3579 * memory. This allows lockless observations without ever seeing the negative
3582 #define sub_positive(_ptr, _val) do { \
3583 typeof(_ptr) ptr = (_ptr); \
3584 typeof(*ptr) val = (_val); \
3585 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3589 WRITE_ONCE(*ptr, res); \
3593 * Remove and clamp on negative, from a local variable.
3595 * A variant of sub_positive(), which does not use explicit load-store
3596 * and is thus optimized for local variable updates.
3598 #define lsub_positive(_ptr, _val) do { \
3599 typeof(_ptr) ptr = (_ptr); \
3600 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3605 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3607 cfs_rq->avg.load_avg += se->avg.load_avg;
3608 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3612 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3614 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3615 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3616 /* See update_cfs_rq_load_avg() */
3617 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3618 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3622 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3624 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3627 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3628 unsigned long weight)
3630 unsigned long old_weight = se->load.weight;
3633 /* commit outstanding execution time */
3634 if (cfs_rq->curr == se)
3635 update_curr(cfs_rq);
3637 avg_vruntime_sub(cfs_rq, se);
3638 update_load_sub(&cfs_rq->load, se->load.weight);
3640 dequeue_load_avg(cfs_rq, se);
3642 update_load_set(&se->load, weight);
3646 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3647 * we need to scale se->vlag when w_i changes.
3649 se->vlag = div_s64(se->vlag * old_weight, weight);
3651 s64 deadline = se->deadline - se->vruntime;
3653 * When the weight changes, the virtual time slope changes and
3654 * we should adjust the relative virtual deadline accordingly.
3656 deadline = div_s64(deadline * old_weight, weight);
3657 se->deadline = se->vruntime + deadline;
3662 u32 divider = get_pelt_divider(&se->avg);
3664 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3668 enqueue_load_avg(cfs_rq, se);
3670 update_load_add(&cfs_rq->load, se->load.weight);
3671 if (cfs_rq->curr != se)
3672 avg_vruntime_add(cfs_rq, se);
3676 void reweight_task(struct task_struct *p, int prio)
3678 struct sched_entity *se = &p->se;
3679 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3680 struct load_weight *load = &se->load;
3681 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3683 reweight_entity(cfs_rq, se, weight);
3684 load->inv_weight = sched_prio_to_wmult[prio];
3687 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3689 #ifdef CONFIG_FAIR_GROUP_SCHED
3692 * All this does is approximate the hierarchical proportion which includes that
3693 * global sum we all love to hate.
3695 * That is, the weight of a group entity, is the proportional share of the
3696 * group weight based on the group runqueue weights. That is:
3698 * tg->weight * grq->load.weight
3699 * ge->load.weight = ----------------------------- (1)
3700 * \Sum grq->load.weight
3702 * Now, because computing that sum is prohibitively expensive to compute (been
3703 * there, done that) we approximate it with this average stuff. The average
3704 * moves slower and therefore the approximation is cheaper and more stable.
3706 * So instead of the above, we substitute:
3708 * grq->load.weight -> grq->avg.load_avg (2)
3710 * which yields the following:
3712 * tg->weight * grq->avg.load_avg
3713 * ge->load.weight = ------------------------------ (3)
3716 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3718 * That is shares_avg, and it is right (given the approximation (2)).
3720 * The problem with it is that because the average is slow -- it was designed
3721 * to be exactly that of course -- this leads to transients in boundary
3722 * conditions. In specific, the case where the group was idle and we start the
3723 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3724 * yielding bad latency etc..
3726 * Now, in that special case (1) reduces to:
3728 * tg->weight * grq->load.weight
3729 * ge->load.weight = ----------------------------- = tg->weight (4)
3732 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3734 * So what we do is modify our approximation (3) to approach (4) in the (near)
3739 * tg->weight * grq->load.weight
3740 * --------------------------------------------------- (5)
3741 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3743 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3744 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3747 * tg->weight * grq->load.weight
3748 * ge->load.weight = ----------------------------- (6)
3753 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3754 * max(grq->load.weight, grq->avg.load_avg)
3756 * And that is shares_weight and is icky. In the (near) UP case it approaches
3757 * (4) while in the normal case it approaches (3). It consistently
3758 * overestimates the ge->load.weight and therefore:
3760 * \Sum ge->load.weight >= tg->weight
3764 static long calc_group_shares(struct cfs_rq *cfs_rq)
3766 long tg_weight, tg_shares, load, shares;
3767 struct task_group *tg = cfs_rq->tg;
3769 tg_shares = READ_ONCE(tg->shares);
3771 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3773 tg_weight = atomic_long_read(&tg->load_avg);
3775 /* Ensure tg_weight >= load */
3776 tg_weight -= cfs_rq->tg_load_avg_contrib;
3779 shares = (tg_shares * load);
3781 shares /= tg_weight;
3784 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3785 * of a group with small tg->shares value. It is a floor value which is
3786 * assigned as a minimum load.weight to the sched_entity representing
3787 * the group on a CPU.
3789 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3790 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3791 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3792 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3795 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3797 #endif /* CONFIG_SMP */
3800 * Recomputes the group entity based on the current state of its group
3803 static void update_cfs_group(struct sched_entity *se)
3805 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3811 if (throttled_hierarchy(gcfs_rq))
3815 shares = READ_ONCE(gcfs_rq->tg->shares);
3817 if (likely(se->load.weight == shares))
3820 shares = calc_group_shares(gcfs_rq);
3823 reweight_entity(cfs_rq_of(se), se, shares);
3826 #else /* CONFIG_FAIR_GROUP_SCHED */
3827 static inline void update_cfs_group(struct sched_entity *se)
3830 #endif /* CONFIG_FAIR_GROUP_SCHED */
3832 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3834 struct rq *rq = rq_of(cfs_rq);
3836 if (&rq->cfs == cfs_rq) {
3838 * There are a few boundary cases this might miss but it should
3839 * get called often enough that that should (hopefully) not be
3842 * It will not get called when we go idle, because the idle
3843 * thread is a different class (!fair), nor will the utilization
3844 * number include things like RT tasks.
3846 * As is, the util number is not freq-invariant (we'd have to
3847 * implement arch_scale_freq_capacity() for that).
3849 * See cpu_util_cfs().
3851 cpufreq_update_util(rq, flags);
3856 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3864 if (sa->runnable_sum)
3868 * _avg must be null when _sum are null because _avg = _sum / divider
3869 * Make sure that rounding and/or propagation of PELT values never
3872 SCHED_WARN_ON(sa->load_avg ||
3879 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3881 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3882 cfs_rq->last_update_time_copy);
3884 #ifdef CONFIG_FAIR_GROUP_SCHED
3886 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
3887 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
3888 * bottom-up, we only have to test whether the cfs_rq before us on the list
3890 * If cfs_rq is not on the list, test whether a child needs its to be added to
3891 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
3893 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
3895 struct cfs_rq *prev_cfs_rq;
3896 struct list_head *prev;
3898 if (cfs_rq->on_list) {
3899 prev = cfs_rq->leaf_cfs_rq_list.prev;
3901 struct rq *rq = rq_of(cfs_rq);
3903 prev = rq->tmp_alone_branch;
3906 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
3908 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
3911 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
3913 if (cfs_rq->load.weight)
3916 if (!load_avg_is_decayed(&cfs_rq->avg))
3919 if (child_cfs_rq_on_list(cfs_rq))
3926 * update_tg_load_avg - update the tg's load avg
3927 * @cfs_rq: the cfs_rq whose avg changed
3929 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3930 * However, because tg->load_avg is a global value there are performance
3933 * In order to avoid having to look at the other cfs_rq's, we use a
3934 * differential update where we store the last value we propagated. This in
3935 * turn allows skipping updates if the differential is 'small'.
3937 * Updating tg's load_avg is necessary before update_cfs_share().
3939 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
3945 * No need to update load_avg for root_task_group as it is not used.
3947 if (cfs_rq->tg == &root_task_group)
3951 * For migration heavy workloads, access to tg->load_avg can be
3952 * unbound. Limit the update rate to at most once per ms.
3954 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
3955 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
3958 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3959 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3960 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3961 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3962 cfs_rq->last_update_tg_load_avg = now;
3967 * Called within set_task_rq() right before setting a task's CPU. The
3968 * caller only guarantees p->pi_lock is held; no other assumptions,
3969 * including the state of rq->lock, should be made.
3971 void set_task_rq_fair(struct sched_entity *se,
3972 struct cfs_rq *prev, struct cfs_rq *next)
3974 u64 p_last_update_time;
3975 u64 n_last_update_time;
3977 if (!sched_feat(ATTACH_AGE_LOAD))
3981 * We are supposed to update the task to "current" time, then its up to
3982 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3983 * getting what current time is, so simply throw away the out-of-date
3984 * time. This will result in the wakee task is less decayed, but giving
3985 * the wakee more load sounds not bad.
3987 if (!(se->avg.last_update_time && prev))
3990 p_last_update_time = cfs_rq_last_update_time(prev);
3991 n_last_update_time = cfs_rq_last_update_time(next);
3993 __update_load_avg_blocked_se(p_last_update_time, se);
3994 se->avg.last_update_time = n_last_update_time;
3998 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3999 * propagate its contribution. The key to this propagation is the invariant
4000 * that for each group:
4002 * ge->avg == grq->avg (1)
4004 * _IFF_ we look at the pure running and runnable sums. Because they
4005 * represent the very same entity, just at different points in the hierarchy.
4007 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4008 * and simply copies the running/runnable sum over (but still wrong, because
4009 * the group entity and group rq do not have their PELT windows aligned).
4011 * However, update_tg_cfs_load() is more complex. So we have:
4013 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4015 * And since, like util, the runnable part should be directly transferable,
4016 * the following would _appear_ to be the straight forward approach:
4018 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4020 * And per (1) we have:
4022 * ge->avg.runnable_avg == grq->avg.runnable_avg
4026 * ge->load.weight * grq->avg.load_avg
4027 * ge->avg.load_avg = ----------------------------------- (4)
4030 * Except that is wrong!
4032 * Because while for entities historical weight is not important and we
4033 * really only care about our future and therefore can consider a pure
4034 * runnable sum, runqueues can NOT do this.
4036 * We specifically want runqueues to have a load_avg that includes
4037 * historical weights. Those represent the blocked load, the load we expect
4038 * to (shortly) return to us. This only works by keeping the weights as
4039 * integral part of the sum. We therefore cannot decompose as per (3).
4041 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4042 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4043 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4044 * runnable section of these tasks overlap (or not). If they were to perfectly
4045 * align the rq as a whole would be runnable 2/3 of the time. If however we
4046 * always have at least 1 runnable task, the rq as a whole is always runnable.
4048 * So we'll have to approximate.. :/
4050 * Given the constraint:
4052 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4054 * We can construct a rule that adds runnable to a rq by assuming minimal
4057 * On removal, we'll assume each task is equally runnable; which yields:
4059 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4061 * XXX: only do this for the part of runnable > running ?
4065 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4067 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4068 u32 new_sum, divider;
4070 /* Nothing to update */
4075 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4076 * See ___update_load_avg() for details.
4078 divider = get_pelt_divider(&cfs_rq->avg);
4081 /* Set new sched_entity's utilization */
4082 se->avg.util_avg = gcfs_rq->avg.util_avg;
4083 new_sum = se->avg.util_avg * divider;
4084 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4085 se->avg.util_sum = new_sum;
4087 /* Update parent cfs_rq utilization */
4088 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4089 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4091 /* See update_cfs_rq_load_avg() */
4092 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4093 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4097 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4099 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4100 u32 new_sum, divider;
4102 /* Nothing to update */
4107 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4108 * See ___update_load_avg() for details.
4110 divider = get_pelt_divider(&cfs_rq->avg);
4112 /* Set new sched_entity's runnable */
4113 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4114 new_sum = se->avg.runnable_avg * divider;
4115 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4116 se->avg.runnable_sum = new_sum;
4118 /* Update parent cfs_rq runnable */
4119 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4120 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4121 /* See update_cfs_rq_load_avg() */
4122 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4123 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4127 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4129 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4130 unsigned long load_avg;
4138 gcfs_rq->prop_runnable_sum = 0;
4141 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4142 * See ___update_load_avg() for details.
4144 divider = get_pelt_divider(&cfs_rq->avg);
4146 if (runnable_sum >= 0) {
4148 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4149 * the CPU is saturated running == runnable.
4151 runnable_sum += se->avg.load_sum;
4152 runnable_sum = min_t(long, runnable_sum, divider);
4155 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4156 * assuming all tasks are equally runnable.
4158 if (scale_load_down(gcfs_rq->load.weight)) {
4159 load_sum = div_u64(gcfs_rq->avg.load_sum,
4160 scale_load_down(gcfs_rq->load.weight));
4163 /* But make sure to not inflate se's runnable */
4164 runnable_sum = min(se->avg.load_sum, load_sum);
4168 * runnable_sum can't be lower than running_sum
4169 * Rescale running sum to be in the same range as runnable sum
4170 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4171 * runnable_sum is in [0 : LOAD_AVG_MAX]
4173 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4174 runnable_sum = max(runnable_sum, running_sum);
4176 load_sum = se_weight(se) * runnable_sum;
4177 load_avg = div_u64(load_sum, divider);
4179 delta_avg = load_avg - se->avg.load_avg;
4183 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4185 se->avg.load_sum = runnable_sum;
4186 se->avg.load_avg = load_avg;
4187 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4188 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4189 /* See update_cfs_rq_load_avg() */
4190 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4191 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4194 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4196 cfs_rq->propagate = 1;
4197 cfs_rq->prop_runnable_sum += runnable_sum;
4200 /* Update task and its cfs_rq load average */
4201 static inline int propagate_entity_load_avg(struct sched_entity *se)
4203 struct cfs_rq *cfs_rq, *gcfs_rq;
4205 if (entity_is_task(se))
4208 gcfs_rq = group_cfs_rq(se);
4209 if (!gcfs_rq->propagate)
4212 gcfs_rq->propagate = 0;
4214 cfs_rq = cfs_rq_of(se);
4216 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4218 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4219 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4220 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4222 trace_pelt_cfs_tp(cfs_rq);
4223 trace_pelt_se_tp(se);
4229 * Check if we need to update the load and the utilization of a blocked
4232 static inline bool skip_blocked_update(struct sched_entity *se)
4234 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4237 * If sched_entity still have not zero load or utilization, we have to
4240 if (se->avg.load_avg || se->avg.util_avg)
4244 * If there is a pending propagation, we have to update the load and
4245 * the utilization of the sched_entity:
4247 if (gcfs_rq->propagate)
4251 * Otherwise, the load and the utilization of the sched_entity is
4252 * already zero and there is no pending propagation, so it will be a
4253 * waste of time to try to decay it:
4258 #else /* CONFIG_FAIR_GROUP_SCHED */
4260 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4262 static inline int propagate_entity_load_avg(struct sched_entity *se)
4267 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4269 #endif /* CONFIG_FAIR_GROUP_SCHED */
4271 #ifdef CONFIG_NO_HZ_COMMON
4272 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4274 u64 throttled = 0, now, lut;
4275 struct cfs_rq *cfs_rq;
4279 if (load_avg_is_decayed(&se->avg))
4282 cfs_rq = cfs_rq_of(se);
4286 is_idle = is_idle_task(rcu_dereference(rq->curr));
4290 * The lag estimation comes with a cost we don't want to pay all the
4291 * time. Hence, limiting to the case where the source CPU is idle and
4292 * we know we are at the greatest risk to have an outdated clock.
4298 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4300 * last_update_time (the cfs_rq's last_update_time)
4301 * = cfs_rq_clock_pelt()@cfs_rq_idle
4302 * = rq_clock_pelt()@cfs_rq_idle
4303 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4305 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4306 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4308 * rq_idle_lag (delta between now and rq's update)
4309 * = sched_clock_cpu() - rq_clock()@rq_idle
4311 * We can then write:
4313 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4314 * sched_clock_cpu() - rq_clock()@rq_idle
4316 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4317 * rq_clock()@rq_idle is rq->clock_idle
4318 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4319 * is cfs_rq->throttled_pelt_idle
4322 #ifdef CONFIG_CFS_BANDWIDTH
4323 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4324 /* The clock has been stopped for throttling */
4325 if (throttled == U64_MAX)
4328 now = u64_u32_load(rq->clock_pelt_idle);
4330 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4331 * is observed the old clock_pelt_idle value and the new clock_idle,
4332 * which lead to an underestimation. The opposite would lead to an
4336 lut = cfs_rq_last_update_time(cfs_rq);
4341 * cfs_rq->avg.last_update_time is more recent than our
4342 * estimation, let's use it.
4346 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4348 __update_load_avg_blocked_se(now, se);
4351 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4355 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4356 * @now: current time, as per cfs_rq_clock_pelt()
4357 * @cfs_rq: cfs_rq to update
4359 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4360 * avg. The immediate corollary is that all (fair) tasks must be attached.
4362 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4364 * Return: true if the load decayed or we removed load.
4366 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4367 * call update_tg_load_avg() when this function returns true.
4370 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4372 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4373 struct sched_avg *sa = &cfs_rq->avg;
4376 if (cfs_rq->removed.nr) {
4378 u32 divider = get_pelt_divider(&cfs_rq->avg);
4380 raw_spin_lock(&cfs_rq->removed.lock);
4381 swap(cfs_rq->removed.util_avg, removed_util);
4382 swap(cfs_rq->removed.load_avg, removed_load);
4383 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4384 cfs_rq->removed.nr = 0;
4385 raw_spin_unlock(&cfs_rq->removed.lock);
4388 sub_positive(&sa->load_avg, r);
4389 sub_positive(&sa->load_sum, r * divider);
4390 /* See sa->util_sum below */
4391 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4394 sub_positive(&sa->util_avg, r);
4395 sub_positive(&sa->util_sum, r * divider);
4397 * Because of rounding, se->util_sum might ends up being +1 more than
4398 * cfs->util_sum. Although this is not a problem by itself, detaching
4399 * a lot of tasks with the rounding problem between 2 updates of
4400 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4401 * cfs_util_avg is not.
4402 * Check that util_sum is still above its lower bound for the new
4403 * util_avg. Given that period_contrib might have moved since the last
4404 * sync, we are only sure that util_sum must be above or equal to
4405 * util_avg * minimum possible divider
4407 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4409 r = removed_runnable;
4410 sub_positive(&sa->runnable_avg, r);
4411 sub_positive(&sa->runnable_sum, r * divider);
4412 /* See sa->util_sum above */
4413 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4414 sa->runnable_avg * PELT_MIN_DIVIDER);
4417 * removed_runnable is the unweighted version of removed_load so we
4418 * can use it to estimate removed_load_sum.
4420 add_tg_cfs_propagate(cfs_rq,
4421 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4426 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4427 u64_u32_store_copy(sa->last_update_time,
4428 cfs_rq->last_update_time_copy,
4429 sa->last_update_time);
4434 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4435 * @cfs_rq: cfs_rq to attach to
4436 * @se: sched_entity to attach
4438 * Must call update_cfs_rq_load_avg() before this, since we rely on
4439 * cfs_rq->avg.last_update_time being current.
4441 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4444 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4445 * See ___update_load_avg() for details.
4447 u32 divider = get_pelt_divider(&cfs_rq->avg);
4450 * When we attach the @se to the @cfs_rq, we must align the decay
4451 * window because without that, really weird and wonderful things can
4456 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4457 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4460 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4461 * period_contrib. This isn't strictly correct, but since we're
4462 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4465 se->avg.util_sum = se->avg.util_avg * divider;
4467 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4469 se->avg.load_sum = se->avg.load_avg * divider;
4470 if (se_weight(se) < se->avg.load_sum)
4471 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4473 se->avg.load_sum = 1;
4475 enqueue_load_avg(cfs_rq, se);
4476 cfs_rq->avg.util_avg += se->avg.util_avg;
4477 cfs_rq->avg.util_sum += se->avg.util_sum;
4478 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4479 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4481 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4483 cfs_rq_util_change(cfs_rq, 0);
4485 trace_pelt_cfs_tp(cfs_rq);
4489 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4490 * @cfs_rq: cfs_rq to detach from
4491 * @se: sched_entity to detach
4493 * Must call update_cfs_rq_load_avg() before this, since we rely on
4494 * cfs_rq->avg.last_update_time being current.
4496 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4498 dequeue_load_avg(cfs_rq, se);
4499 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4500 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4501 /* See update_cfs_rq_load_avg() */
4502 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4503 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4505 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4506 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4507 /* See update_cfs_rq_load_avg() */
4508 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4509 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4511 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4513 cfs_rq_util_change(cfs_rq, 0);
4515 trace_pelt_cfs_tp(cfs_rq);
4519 * Optional action to be done while updating the load average
4521 #define UPDATE_TG 0x1
4522 #define SKIP_AGE_LOAD 0x2
4523 #define DO_ATTACH 0x4
4524 #define DO_DETACH 0x8
4526 /* Update task and its cfs_rq load average */
4527 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4529 u64 now = cfs_rq_clock_pelt(cfs_rq);
4533 * Track task load average for carrying it to new CPU after migrated, and
4534 * track group sched_entity load average for task_h_load calc in migration
4536 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4537 __update_load_avg_se(now, cfs_rq, se);
4539 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4540 decayed |= propagate_entity_load_avg(se);
4542 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4545 * DO_ATTACH means we're here from enqueue_entity().
4546 * !last_update_time means we've passed through
4547 * migrate_task_rq_fair() indicating we migrated.
4549 * IOW we're enqueueing a task on a new CPU.
4551 attach_entity_load_avg(cfs_rq, se);
4552 update_tg_load_avg(cfs_rq);
4554 } else if (flags & DO_DETACH) {
4556 * DO_DETACH means we're here from dequeue_entity()
4557 * and we are migrating task out of the CPU.
4559 detach_entity_load_avg(cfs_rq, se);
4560 update_tg_load_avg(cfs_rq);
4561 } else if (decayed) {
4562 cfs_rq_util_change(cfs_rq, 0);
4564 if (flags & UPDATE_TG)
4565 update_tg_load_avg(cfs_rq);
4570 * Synchronize entity load avg of dequeued entity without locking
4573 static void sync_entity_load_avg(struct sched_entity *se)
4575 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4576 u64 last_update_time;
4578 last_update_time = cfs_rq_last_update_time(cfs_rq);
4579 __update_load_avg_blocked_se(last_update_time, se);
4583 * Task first catches up with cfs_rq, and then subtract
4584 * itself from the cfs_rq (task must be off the queue now).
4586 static void remove_entity_load_avg(struct sched_entity *se)
4588 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4589 unsigned long flags;
4592 * tasks cannot exit without having gone through wake_up_new_task() ->
4593 * enqueue_task_fair() which will have added things to the cfs_rq,
4594 * so we can remove unconditionally.
4597 sync_entity_load_avg(se);
4599 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4600 ++cfs_rq->removed.nr;
4601 cfs_rq->removed.util_avg += se->avg.util_avg;
4602 cfs_rq->removed.load_avg += se->avg.load_avg;
4603 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4604 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4607 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4609 return cfs_rq->avg.runnable_avg;
4612 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4614 return cfs_rq->avg.load_avg;
4617 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4619 static inline unsigned long task_util(struct task_struct *p)
4621 return READ_ONCE(p->se.avg.util_avg);
4624 static inline unsigned long _task_util_est(struct task_struct *p)
4626 struct util_est ue = READ_ONCE(p->se.avg.util_est);
4628 return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4631 static inline unsigned long task_util_est(struct task_struct *p)
4633 return max(task_util(p), _task_util_est(p));
4636 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4637 struct task_struct *p)
4639 unsigned int enqueued;
4641 if (!sched_feat(UTIL_EST))
4644 /* Update root cfs_rq's estimated utilization */
4645 enqueued = cfs_rq->avg.util_est.enqueued;
4646 enqueued += _task_util_est(p);
4647 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4649 trace_sched_util_est_cfs_tp(cfs_rq);
4652 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4653 struct task_struct *p)
4655 unsigned int enqueued;
4657 if (!sched_feat(UTIL_EST))
4660 /* Update root cfs_rq's estimated utilization */
4661 enqueued = cfs_rq->avg.util_est.enqueued;
4662 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4663 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4665 trace_sched_util_est_cfs_tp(cfs_rq);
4668 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4671 * Check if a (signed) value is within a specified (unsigned) margin,
4672 * based on the observation that:
4674 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4676 * NOTE: this only works when value + margin < INT_MAX.
4678 static inline bool within_margin(int value, int margin)
4680 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4683 static inline void util_est_update(struct cfs_rq *cfs_rq,
4684 struct task_struct *p,
4687 long last_ewma_diff, last_enqueued_diff;
4690 if (!sched_feat(UTIL_EST))
4694 * Skip update of task's estimated utilization when the task has not
4695 * yet completed an activation, e.g. being migrated.
4701 * If the PELT values haven't changed since enqueue time,
4702 * skip the util_est update.
4704 ue = p->se.avg.util_est;
4705 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4708 last_enqueued_diff = ue.enqueued;
4711 * Reset EWMA on utilization increases, the moving average is used only
4712 * to smooth utilization decreases.
4714 ue.enqueued = task_util(p);
4715 if (sched_feat(UTIL_EST_FASTUP)) {
4716 if (ue.ewma < ue.enqueued) {
4717 ue.ewma = ue.enqueued;
4723 * Skip update of task's estimated utilization when its members are
4724 * already ~1% close to its last activation value.
4726 last_ewma_diff = ue.enqueued - ue.ewma;
4727 last_enqueued_diff -= ue.enqueued;
4728 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4729 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4736 * To avoid overestimation of actual task utilization, skip updates if
4737 * we cannot grant there is idle time in this CPU.
4739 if (task_util(p) > arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))))
4743 * Update Task's estimated utilization
4745 * When *p completes an activation we can consolidate another sample
4746 * of the task size. This is done by storing the current PELT value
4747 * as ue.enqueued and by using this value to update the Exponential
4748 * Weighted Moving Average (EWMA):
4750 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4751 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4752 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4753 * = w * ( last_ewma_diff ) + ewma(t-1)
4754 * = w * (last_ewma_diff + ewma(t-1) / w)
4756 * Where 'w' is the weight of new samples, which is configured to be
4757 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4759 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4760 ue.ewma += last_ewma_diff;
4761 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4763 ue.enqueued |= UTIL_AVG_UNCHANGED;
4764 WRITE_ONCE(p->se.avg.util_est, ue);
4766 trace_sched_util_est_se_tp(&p->se);
4769 static inline int util_fits_cpu(unsigned long util,
4770 unsigned long uclamp_min,
4771 unsigned long uclamp_max,
4774 unsigned long capacity_orig, capacity_orig_thermal;
4775 unsigned long capacity = capacity_of(cpu);
4776 bool fits, uclamp_max_fits;
4779 * Check if the real util fits without any uclamp boost/cap applied.
4781 fits = fits_capacity(util, capacity);
4783 if (!uclamp_is_used())
4787 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4788 * uclamp_max. We only care about capacity pressure (by using
4789 * capacity_of()) for comparing against the real util.
4791 * If a task is boosted to 1024 for example, we don't want a tiny
4792 * pressure to skew the check whether it fits a CPU or not.
4794 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4795 * should fit a little cpu even if there's some pressure.
4797 * Only exception is for thermal pressure since it has a direct impact
4798 * on available OPP of the system.
4800 * We honour it for uclamp_min only as a drop in performance level
4801 * could result in not getting the requested minimum performance level.
4803 * For uclamp_max, we can tolerate a drop in performance level as the
4804 * goal is to cap the task. So it's okay if it's getting less.
4806 capacity_orig = arch_scale_cpu_capacity(cpu);
4807 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4810 * We want to force a task to fit a cpu as implied by uclamp_max.
4811 * But we do have some corner cases to cater for..
4817 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4820 * | | | | | | | (util somewhere in this region)
4823 * +----------------------------------------
4826 * In the above example if a task is capped to a specific performance
4827 * point, y, then when:
4829 * * util = 80% of x then it does not fit on cpu0 and should migrate
4831 * * util = 80% of y then it is forced to fit on cpu1 to honour
4832 * uclamp_max request.
4834 * which is what we're enforcing here. A task always fits if
4835 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4836 * the normal upmigration rules should withhold still.
4838 * Only exception is when we are on max capacity, then we need to be
4839 * careful not to block overutilized state. This is so because:
4841 * 1. There's no concept of capping at max_capacity! We can't go
4842 * beyond this performance level anyway.
4843 * 2. The system is being saturated when we're operating near
4844 * max capacity, it doesn't make sense to block overutilized.
4846 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4847 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4848 fits = fits || uclamp_max_fits;
4853 * | ___ (region a, capped, util >= uclamp_max)
4855 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4857 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
4858 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4860 * | | | | | | | (region c, boosted, util < uclamp_min)
4861 * +----------------------------------------
4864 * a) If util > uclamp_max, then we're capped, we don't care about
4865 * actual fitness value here. We only care if uclamp_max fits
4866 * capacity without taking margin/pressure into account.
4867 * See comment above.
4869 * b) If uclamp_min <= util <= uclamp_max, then the normal
4870 * fits_capacity() rules apply. Except we need to ensure that we
4871 * enforce we remain within uclamp_max, see comment above.
4873 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
4874 * need to take into account the boosted value fits the CPU without
4875 * taking margin/pressure into account.
4877 * Cases (a) and (b) are handled in the 'fits' variable already. We
4878 * just need to consider an extra check for case (c) after ensuring we
4879 * handle the case uclamp_min > uclamp_max.
4881 uclamp_min = min(uclamp_min, uclamp_max);
4882 if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
4888 static inline int task_fits_cpu(struct task_struct *p, int cpu)
4890 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
4891 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
4892 unsigned long util = task_util_est(p);
4894 * Return true only if the cpu fully fits the task requirements, which
4895 * include the utilization but also the performance hints.
4897 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
4900 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4902 if (!sched_asym_cpucap_active())
4905 if (!p || p->nr_cpus_allowed == 1) {
4906 rq->misfit_task_load = 0;
4910 if (task_fits_cpu(p, cpu_of(rq))) {
4911 rq->misfit_task_load = 0;
4916 * Make sure that misfit_task_load will not be null even if
4917 * task_h_load() returns 0.
4919 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4922 #else /* CONFIG_SMP */
4924 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4926 return !cfs_rq->nr_running;
4929 #define UPDATE_TG 0x0
4930 #define SKIP_AGE_LOAD 0x0
4931 #define DO_ATTACH 0x0
4932 #define DO_DETACH 0x0
4934 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4936 cfs_rq_util_change(cfs_rq, 0);
4939 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4942 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4944 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4946 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4952 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4955 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4958 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4960 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4962 #endif /* CONFIG_SMP */
4965 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4967 u64 vslice, vruntime = avg_vruntime(cfs_rq);
4970 se->slice = sysctl_sched_base_slice;
4971 vslice = calc_delta_fair(se->slice, se);
4974 * Due to how V is constructed as the weighted average of entities,
4975 * adding tasks with positive lag, or removing tasks with negative lag
4976 * will move 'time' backwards, this can screw around with the lag of
4979 * EEVDF: placement strategy #1 / #2
4981 if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
4982 struct sched_entity *curr = cfs_rq->curr;
4988 * If we want to place a task and preserve lag, we have to
4989 * consider the effect of the new entity on the weighted
4990 * average and compensate for this, otherwise lag can quickly
4993 * Lag is defined as:
4995 * lag_i = S - s_i = w_i * (V - v_i)
4997 * To avoid the 'w_i' term all over the place, we only track
5000 * vl_i = V - v_i <=> v_i = V - vl_i
5002 * And we take V to be the weighted average of all v:
5004 * V = (\Sum w_j*v_j) / W
5006 * Where W is: \Sum w_j
5008 * Then, the weighted average after adding an entity with lag
5011 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5012 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5013 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5014 * = (V*(W + w_i) - w_i*l) / (W + w_i)
5015 * = V - w_i*vl_i / (W + w_i)
5017 * And the actual lag after adding an entity with vl_i is:
5020 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5021 * = vl_i - w_i*vl_i / (W + w_i)
5023 * Which is strictly less than vl_i. So in order to preserve lag
5024 * we should inflate the lag before placement such that the
5025 * effective lag after placement comes out right.
5027 * As such, invert the above relation for vl'_i to get the vl_i
5028 * we need to use such that the lag after placement is the lag
5029 * we computed before dequeue.
5031 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5032 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5034 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5037 * vl_i = (W + w_i)*vl'_i / W
5039 load = cfs_rq->avg_load;
5040 if (curr && curr->on_rq)
5041 load += scale_load_down(curr->load.weight);
5043 lag *= load + scale_load_down(se->load.weight);
5044 if (WARN_ON_ONCE(!load))
5046 lag = div_s64(lag, load);
5049 se->vruntime = vruntime - lag;
5052 * When joining the competition; the exisiting tasks will be,
5053 * on average, halfway through their slice, as such start tasks
5054 * off with half a slice to ease into the competition.
5056 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5060 * EEVDF: vd_i = ve_i + r_i/w_i
5062 se->deadline = se->vruntime + vslice;
5065 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5066 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5068 static inline bool cfs_bandwidth_used(void);
5071 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5073 bool curr = cfs_rq->curr == se;
5076 * If we're the current task, we must renormalise before calling
5080 place_entity(cfs_rq, se, flags);
5082 update_curr(cfs_rq);
5085 * When enqueuing a sched_entity, we must:
5086 * - Update loads to have both entity and cfs_rq synced with now.
5087 * - For group_entity, update its runnable_weight to reflect the new
5088 * h_nr_running of its group cfs_rq.
5089 * - For group_entity, update its weight to reflect the new share of
5091 * - Add its new weight to cfs_rq->load.weight
5093 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5094 se_update_runnable(se);
5096 * XXX update_load_avg() above will have attached us to the pelt sum;
5097 * but update_cfs_group() here will re-adjust the weight and have to
5098 * undo/redo all that. Seems wasteful.
5100 update_cfs_group(se);
5103 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5104 * we can place the entity.
5107 place_entity(cfs_rq, se, flags);
5109 account_entity_enqueue(cfs_rq, se);
5111 /* Entity has migrated, no longer consider this task hot */
5112 if (flags & ENQUEUE_MIGRATED)
5115 check_schedstat_required();
5116 update_stats_enqueue_fair(cfs_rq, se, flags);
5118 __enqueue_entity(cfs_rq, se);
5121 if (cfs_rq->nr_running == 1) {
5122 check_enqueue_throttle(cfs_rq);
5123 if (!throttled_hierarchy(cfs_rq)) {
5124 list_add_leaf_cfs_rq(cfs_rq);
5126 #ifdef CONFIG_CFS_BANDWIDTH
5127 struct rq *rq = rq_of(cfs_rq);
5129 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5130 cfs_rq->throttled_clock = rq_clock(rq);
5131 if (!cfs_rq->throttled_clock_self)
5132 cfs_rq->throttled_clock_self = rq_clock(rq);
5138 static void __clear_buddies_next(struct sched_entity *se)
5140 for_each_sched_entity(se) {
5141 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5142 if (cfs_rq->next != se)
5145 cfs_rq->next = NULL;
5149 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5151 if (cfs_rq->next == se)
5152 __clear_buddies_next(se);
5155 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5158 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5160 int action = UPDATE_TG;
5162 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5163 action |= DO_DETACH;
5166 * Update run-time statistics of the 'current'.
5168 update_curr(cfs_rq);
5171 * When dequeuing a sched_entity, we must:
5172 * - Update loads to have both entity and cfs_rq synced with now.
5173 * - For group_entity, update its runnable_weight to reflect the new
5174 * h_nr_running of its group cfs_rq.
5175 * - Subtract its previous weight from cfs_rq->load.weight.
5176 * - For group entity, update its weight to reflect the new share
5177 * of its group cfs_rq.
5179 update_load_avg(cfs_rq, se, action);
5180 se_update_runnable(se);
5182 update_stats_dequeue_fair(cfs_rq, se, flags);
5184 clear_buddies(cfs_rq, se);
5186 update_entity_lag(cfs_rq, se);
5187 if (se != cfs_rq->curr)
5188 __dequeue_entity(cfs_rq, se);
5190 account_entity_dequeue(cfs_rq, se);
5192 /* return excess runtime on last dequeue */
5193 return_cfs_rq_runtime(cfs_rq);
5195 update_cfs_group(se);
5198 * Now advance min_vruntime if @se was the entity holding it back,
5199 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5200 * put back on, and if we advance min_vruntime, we'll be placed back
5201 * further than we started -- ie. we'll be penalized.
5203 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5204 update_min_vruntime(cfs_rq);
5206 if (cfs_rq->nr_running == 0)
5207 update_idle_cfs_rq_clock_pelt(cfs_rq);
5211 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5213 clear_buddies(cfs_rq, se);
5215 /* 'current' is not kept within the tree. */
5218 * Any task has to be enqueued before it get to execute on
5219 * a CPU. So account for the time it spent waiting on the
5222 update_stats_wait_end_fair(cfs_rq, se);
5223 __dequeue_entity(cfs_rq, se);
5224 update_load_avg(cfs_rq, se, UPDATE_TG);
5226 * HACK, stash a copy of deadline at the point of pick in vlag,
5227 * which isn't used until dequeue.
5229 se->vlag = se->deadline;
5232 update_stats_curr_start(cfs_rq, se);
5236 * Track our maximum slice length, if the CPU's load is at
5237 * least twice that of our own weight (i.e. dont track it
5238 * when there are only lesser-weight tasks around):
5240 if (schedstat_enabled() &&
5241 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5242 struct sched_statistics *stats;
5244 stats = __schedstats_from_se(se);
5245 __schedstat_set(stats->slice_max,
5246 max((u64)stats->slice_max,
5247 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5250 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5254 * Pick the next process, keeping these things in mind, in this order:
5255 * 1) keep things fair between processes/task groups
5256 * 2) pick the "next" process, since someone really wants that to run
5257 * 3) pick the "last" process, for cache locality
5258 * 4) do not run the "skip" process, if something else is available
5260 static struct sched_entity *
5261 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5264 * Enabling NEXT_BUDDY will affect latency but not fairness.
5266 if (sched_feat(NEXT_BUDDY) &&
5267 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5268 return cfs_rq->next;
5270 return pick_eevdf(cfs_rq);
5273 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5275 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5278 * If still on the runqueue then deactivate_task()
5279 * was not called and update_curr() has to be done:
5282 update_curr(cfs_rq);
5284 /* throttle cfs_rqs exceeding runtime */
5285 check_cfs_rq_runtime(cfs_rq);
5288 update_stats_wait_start_fair(cfs_rq, prev);
5289 /* Put 'current' back into the tree. */
5290 __enqueue_entity(cfs_rq, prev);
5291 /* in !on_rq case, update occurred at dequeue */
5292 update_load_avg(cfs_rq, prev, 0);
5294 cfs_rq->curr = NULL;
5298 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5301 * Update run-time statistics of the 'current'.
5303 update_curr(cfs_rq);
5306 * Ensure that runnable average is periodically updated.
5308 update_load_avg(cfs_rq, curr, UPDATE_TG);
5309 update_cfs_group(curr);
5311 #ifdef CONFIG_SCHED_HRTICK
5313 * queued ticks are scheduled to match the slice, so don't bother
5314 * validating it and just reschedule.
5317 resched_curr(rq_of(cfs_rq));
5321 * don't let the period tick interfere with the hrtick preemption
5323 if (!sched_feat(DOUBLE_TICK) &&
5324 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5330 /**************************************************
5331 * CFS bandwidth control machinery
5334 #ifdef CONFIG_CFS_BANDWIDTH
5336 #ifdef CONFIG_JUMP_LABEL
5337 static struct static_key __cfs_bandwidth_used;
5339 static inline bool cfs_bandwidth_used(void)
5341 return static_key_false(&__cfs_bandwidth_used);
5344 void cfs_bandwidth_usage_inc(void)
5346 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5349 void cfs_bandwidth_usage_dec(void)
5351 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5353 #else /* CONFIG_JUMP_LABEL */
5354 static bool cfs_bandwidth_used(void)
5359 void cfs_bandwidth_usage_inc(void) {}
5360 void cfs_bandwidth_usage_dec(void) {}
5361 #endif /* CONFIG_JUMP_LABEL */
5364 * default period for cfs group bandwidth.
5365 * default: 0.1s, units: nanoseconds
5367 static inline u64 default_cfs_period(void)
5369 return 100000000ULL;
5372 static inline u64 sched_cfs_bandwidth_slice(void)
5374 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5378 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5379 * directly instead of rq->clock to avoid adding additional synchronization
5382 * requires cfs_b->lock
5384 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5388 if (unlikely(cfs_b->quota == RUNTIME_INF))
5391 cfs_b->runtime += cfs_b->quota;
5392 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5394 cfs_b->burst_time += runtime;
5398 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5399 cfs_b->runtime_snap = cfs_b->runtime;
5402 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5404 return &tg->cfs_bandwidth;
5407 /* returns 0 on failure to allocate runtime */
5408 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5409 struct cfs_rq *cfs_rq, u64 target_runtime)
5411 u64 min_amount, amount = 0;
5413 lockdep_assert_held(&cfs_b->lock);
5415 /* note: this is a positive sum as runtime_remaining <= 0 */
5416 min_amount = target_runtime - cfs_rq->runtime_remaining;
5418 if (cfs_b->quota == RUNTIME_INF)
5419 amount = min_amount;
5421 start_cfs_bandwidth(cfs_b);
5423 if (cfs_b->runtime > 0) {
5424 amount = min(cfs_b->runtime, min_amount);
5425 cfs_b->runtime -= amount;
5430 cfs_rq->runtime_remaining += amount;
5432 return cfs_rq->runtime_remaining > 0;
5435 /* returns 0 on failure to allocate runtime */
5436 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5438 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5441 raw_spin_lock(&cfs_b->lock);
5442 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5443 raw_spin_unlock(&cfs_b->lock);
5448 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5450 /* dock delta_exec before expiring quota (as it could span periods) */
5451 cfs_rq->runtime_remaining -= delta_exec;
5453 if (likely(cfs_rq->runtime_remaining > 0))
5456 if (cfs_rq->throttled)
5459 * if we're unable to extend our runtime we resched so that the active
5460 * hierarchy can be throttled
5462 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5463 resched_curr(rq_of(cfs_rq));
5466 static __always_inline
5467 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5469 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5472 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5475 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5477 return cfs_bandwidth_used() && cfs_rq->throttled;
5480 /* check whether cfs_rq, or any parent, is throttled */
5481 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5483 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5487 * Ensure that neither of the group entities corresponding to src_cpu or
5488 * dest_cpu are members of a throttled hierarchy when performing group
5489 * load-balance operations.
5491 static inline int throttled_lb_pair(struct task_group *tg,
5492 int src_cpu, int dest_cpu)
5494 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5496 src_cfs_rq = tg->cfs_rq[src_cpu];
5497 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5499 return throttled_hierarchy(src_cfs_rq) ||
5500 throttled_hierarchy(dest_cfs_rq);
5503 static int tg_unthrottle_up(struct task_group *tg, void *data)
5505 struct rq *rq = data;
5506 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5508 cfs_rq->throttle_count--;
5509 if (!cfs_rq->throttle_count) {
5510 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5511 cfs_rq->throttled_clock_pelt;
5513 /* Add cfs_rq with load or one or more already running entities to the list */
5514 if (!cfs_rq_is_decayed(cfs_rq))
5515 list_add_leaf_cfs_rq(cfs_rq);
5517 if (cfs_rq->throttled_clock_self) {
5518 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5520 cfs_rq->throttled_clock_self = 0;
5522 if (SCHED_WARN_ON((s64)delta < 0))
5525 cfs_rq->throttled_clock_self_time += delta;
5532 static int tg_throttle_down(struct task_group *tg, void *data)
5534 struct rq *rq = data;
5535 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5537 /* group is entering throttled state, stop time */
5538 if (!cfs_rq->throttle_count) {
5539 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5540 list_del_leaf_cfs_rq(cfs_rq);
5542 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5543 if (cfs_rq->nr_running)
5544 cfs_rq->throttled_clock_self = rq_clock(rq);
5546 cfs_rq->throttle_count++;
5551 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5553 struct rq *rq = rq_of(cfs_rq);
5554 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5555 struct sched_entity *se;
5556 long task_delta, idle_task_delta, dequeue = 1;
5558 raw_spin_lock(&cfs_b->lock);
5559 /* This will start the period timer if necessary */
5560 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5562 * We have raced with bandwidth becoming available, and if we
5563 * actually throttled the timer might not unthrottle us for an
5564 * entire period. We additionally needed to make sure that any
5565 * subsequent check_cfs_rq_runtime calls agree not to throttle
5566 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5567 * for 1ns of runtime rather than just check cfs_b.
5571 list_add_tail_rcu(&cfs_rq->throttled_list,
5572 &cfs_b->throttled_cfs_rq);
5574 raw_spin_unlock(&cfs_b->lock);
5577 return false; /* Throttle no longer required. */
5579 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5581 /* freeze hierarchy runnable averages while throttled */
5583 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5586 task_delta = cfs_rq->h_nr_running;
5587 idle_task_delta = cfs_rq->idle_h_nr_running;
5588 for_each_sched_entity(se) {
5589 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5590 /* throttled entity or throttle-on-deactivate */
5594 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5596 if (cfs_rq_is_idle(group_cfs_rq(se)))
5597 idle_task_delta = cfs_rq->h_nr_running;
5599 qcfs_rq->h_nr_running -= task_delta;
5600 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5602 if (qcfs_rq->load.weight) {
5603 /* Avoid re-evaluating load for this entity: */
5604 se = parent_entity(se);
5609 for_each_sched_entity(se) {
5610 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5611 /* throttled entity or throttle-on-deactivate */
5615 update_load_avg(qcfs_rq, se, 0);
5616 se_update_runnable(se);
5618 if (cfs_rq_is_idle(group_cfs_rq(se)))
5619 idle_task_delta = cfs_rq->h_nr_running;
5621 qcfs_rq->h_nr_running -= task_delta;
5622 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5625 /* At this point se is NULL and we are at root level*/
5626 sub_nr_running(rq, task_delta);
5630 * Note: distribution will already see us throttled via the
5631 * throttled-list. rq->lock protects completion.
5633 cfs_rq->throttled = 1;
5634 SCHED_WARN_ON(cfs_rq->throttled_clock);
5635 if (cfs_rq->nr_running)
5636 cfs_rq->throttled_clock = rq_clock(rq);
5640 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5642 struct rq *rq = rq_of(cfs_rq);
5643 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5644 struct sched_entity *se;
5645 long task_delta, idle_task_delta;
5647 se = cfs_rq->tg->se[cpu_of(rq)];
5649 cfs_rq->throttled = 0;
5651 update_rq_clock(rq);
5653 raw_spin_lock(&cfs_b->lock);
5654 if (cfs_rq->throttled_clock) {
5655 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5656 cfs_rq->throttled_clock = 0;
5658 list_del_rcu(&cfs_rq->throttled_list);
5659 raw_spin_unlock(&cfs_b->lock);
5661 /* update hierarchical throttle state */
5662 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5664 if (!cfs_rq->load.weight) {
5665 if (!cfs_rq->on_list)
5668 * Nothing to run but something to decay (on_list)?
5669 * Complete the branch.
5671 for_each_sched_entity(se) {
5672 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5675 goto unthrottle_throttle;
5678 task_delta = cfs_rq->h_nr_running;
5679 idle_task_delta = cfs_rq->idle_h_nr_running;
5680 for_each_sched_entity(se) {
5681 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5685 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5687 if (cfs_rq_is_idle(group_cfs_rq(se)))
5688 idle_task_delta = cfs_rq->h_nr_running;
5690 qcfs_rq->h_nr_running += task_delta;
5691 qcfs_rq->idle_h_nr_running += idle_task_delta;
5693 /* end evaluation on encountering a throttled cfs_rq */
5694 if (cfs_rq_throttled(qcfs_rq))
5695 goto unthrottle_throttle;
5698 for_each_sched_entity(se) {
5699 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5701 update_load_avg(qcfs_rq, se, UPDATE_TG);
5702 se_update_runnable(se);
5704 if (cfs_rq_is_idle(group_cfs_rq(se)))
5705 idle_task_delta = cfs_rq->h_nr_running;
5707 qcfs_rq->h_nr_running += task_delta;
5708 qcfs_rq->idle_h_nr_running += idle_task_delta;
5710 /* end evaluation on encountering a throttled cfs_rq */
5711 if (cfs_rq_throttled(qcfs_rq))
5712 goto unthrottle_throttle;
5715 /* At this point se is NULL and we are at root level*/
5716 add_nr_running(rq, task_delta);
5718 unthrottle_throttle:
5719 assert_list_leaf_cfs_rq(rq);
5721 /* Determine whether we need to wake up potentially idle CPU: */
5722 if (rq->curr == rq->idle && rq->cfs.nr_running)
5727 static void __cfsb_csd_unthrottle(void *arg)
5729 struct cfs_rq *cursor, *tmp;
5730 struct rq *rq = arg;
5736 * Iterating over the list can trigger several call to
5737 * update_rq_clock() in unthrottle_cfs_rq().
5738 * Do it once and skip the potential next ones.
5740 update_rq_clock(rq);
5741 rq_clock_start_loop_update(rq);
5744 * Since we hold rq lock we're safe from concurrent manipulation of
5745 * the CSD list. However, this RCU critical section annotates the
5746 * fact that we pair with sched_free_group_rcu(), so that we cannot
5747 * race with group being freed in the window between removing it
5748 * from the list and advancing to the next entry in the list.
5752 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5753 throttled_csd_list) {
5754 list_del_init(&cursor->throttled_csd_list);
5756 if (cfs_rq_throttled(cursor))
5757 unthrottle_cfs_rq(cursor);
5762 rq_clock_stop_loop_update(rq);
5766 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5768 struct rq *rq = rq_of(cfs_rq);
5771 if (rq == this_rq()) {
5772 unthrottle_cfs_rq(cfs_rq);
5776 /* Already enqueued */
5777 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5780 first = list_empty(&rq->cfsb_csd_list);
5781 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5783 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5786 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5788 unthrottle_cfs_rq(cfs_rq);
5792 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5794 lockdep_assert_rq_held(rq_of(cfs_rq));
5796 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5797 cfs_rq->runtime_remaining <= 0))
5800 __unthrottle_cfs_rq_async(cfs_rq);
5803 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5805 int this_cpu = smp_processor_id();
5806 u64 runtime, remaining = 1;
5807 bool throttled = false;
5808 struct cfs_rq *cfs_rq, *tmp;
5811 LIST_HEAD(local_unthrottle);
5814 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5823 rq_lock_irqsave(rq, &rf);
5824 if (!cfs_rq_throttled(cfs_rq))
5827 /* Already queued for async unthrottle */
5828 if (!list_empty(&cfs_rq->throttled_csd_list))
5831 /* By the above checks, this should never be true */
5832 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5834 raw_spin_lock(&cfs_b->lock);
5835 runtime = -cfs_rq->runtime_remaining + 1;
5836 if (runtime > cfs_b->runtime)
5837 runtime = cfs_b->runtime;
5838 cfs_b->runtime -= runtime;
5839 remaining = cfs_b->runtime;
5840 raw_spin_unlock(&cfs_b->lock);
5842 cfs_rq->runtime_remaining += runtime;
5844 /* we check whether we're throttled above */
5845 if (cfs_rq->runtime_remaining > 0) {
5846 if (cpu_of(rq) != this_cpu) {
5847 unthrottle_cfs_rq_async(cfs_rq);
5850 * We currently only expect to be unthrottling
5851 * a single cfs_rq locally.
5853 SCHED_WARN_ON(!list_empty(&local_unthrottle));
5854 list_add_tail(&cfs_rq->throttled_csd_list,
5862 rq_unlock_irqrestore(rq, &rf);
5865 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
5866 throttled_csd_list) {
5867 struct rq *rq = rq_of(cfs_rq);
5869 rq_lock_irqsave(rq, &rf);
5871 list_del_init(&cfs_rq->throttled_csd_list);
5873 if (cfs_rq_throttled(cfs_rq))
5874 unthrottle_cfs_rq(cfs_rq);
5876 rq_unlock_irqrestore(rq, &rf);
5878 SCHED_WARN_ON(!list_empty(&local_unthrottle));
5886 * Responsible for refilling a task_group's bandwidth and unthrottling its
5887 * cfs_rqs as appropriate. If there has been no activity within the last
5888 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5889 * used to track this state.
5891 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5895 /* no need to continue the timer with no bandwidth constraint */
5896 if (cfs_b->quota == RUNTIME_INF)
5897 goto out_deactivate;
5899 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5900 cfs_b->nr_periods += overrun;
5902 /* Refill extra burst quota even if cfs_b->idle */
5903 __refill_cfs_bandwidth_runtime(cfs_b);
5906 * idle depends on !throttled (for the case of a large deficit), and if
5907 * we're going inactive then everything else can be deferred
5909 if (cfs_b->idle && !throttled)
5910 goto out_deactivate;
5913 /* mark as potentially idle for the upcoming period */
5918 /* account preceding periods in which throttling occurred */
5919 cfs_b->nr_throttled += overrun;
5922 * This check is repeated as we release cfs_b->lock while we unthrottle.
5924 while (throttled && cfs_b->runtime > 0) {
5925 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5926 /* we can't nest cfs_b->lock while distributing bandwidth */
5927 throttled = distribute_cfs_runtime(cfs_b);
5928 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5932 * While we are ensured activity in the period following an
5933 * unthrottle, this also covers the case in which the new bandwidth is
5934 * insufficient to cover the existing bandwidth deficit. (Forcing the
5935 * timer to remain active while there are any throttled entities.)
5945 /* a cfs_rq won't donate quota below this amount */
5946 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5947 /* minimum remaining period time to redistribute slack quota */
5948 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5949 /* how long we wait to gather additional slack before distributing */
5950 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5953 * Are we near the end of the current quota period?
5955 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5956 * hrtimer base being cleared by hrtimer_start. In the case of
5957 * migrate_hrtimers, base is never cleared, so we are fine.
5959 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5961 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5964 /* if the call-back is running a quota refresh is already occurring */
5965 if (hrtimer_callback_running(refresh_timer))
5968 /* is a quota refresh about to occur? */
5969 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5970 if (remaining < (s64)min_expire)
5976 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5978 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5980 /* if there's a quota refresh soon don't bother with slack */
5981 if (runtime_refresh_within(cfs_b, min_left))
5984 /* don't push forwards an existing deferred unthrottle */
5985 if (cfs_b->slack_started)
5987 cfs_b->slack_started = true;
5989 hrtimer_start(&cfs_b->slack_timer,
5990 ns_to_ktime(cfs_bandwidth_slack_period),
5994 /* we know any runtime found here is valid as update_curr() precedes return */
5995 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5997 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5998 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6000 if (slack_runtime <= 0)
6003 raw_spin_lock(&cfs_b->lock);
6004 if (cfs_b->quota != RUNTIME_INF) {
6005 cfs_b->runtime += slack_runtime;
6007 /* we are under rq->lock, defer unthrottling using a timer */
6008 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6009 !list_empty(&cfs_b->throttled_cfs_rq))
6010 start_cfs_slack_bandwidth(cfs_b);
6012 raw_spin_unlock(&cfs_b->lock);
6014 /* even if it's not valid for return we don't want to try again */
6015 cfs_rq->runtime_remaining -= slack_runtime;
6018 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6020 if (!cfs_bandwidth_used())
6023 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6026 __return_cfs_rq_runtime(cfs_rq);
6030 * This is done with a timer (instead of inline with bandwidth return) since
6031 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6033 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6035 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6036 unsigned long flags;
6038 /* confirm we're still not at a refresh boundary */
6039 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6040 cfs_b->slack_started = false;
6042 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6043 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6047 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6048 runtime = cfs_b->runtime;
6050 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6055 distribute_cfs_runtime(cfs_b);
6059 * When a group wakes up we want to make sure that its quota is not already
6060 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6061 * runtime as update_curr() throttling can not trigger until it's on-rq.
6063 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6065 if (!cfs_bandwidth_used())
6068 /* an active group must be handled by the update_curr()->put() path */
6069 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6072 /* ensure the group is not already throttled */
6073 if (cfs_rq_throttled(cfs_rq))
6076 /* update runtime allocation */
6077 account_cfs_rq_runtime(cfs_rq, 0);
6078 if (cfs_rq->runtime_remaining <= 0)
6079 throttle_cfs_rq(cfs_rq);
6082 static void sync_throttle(struct task_group *tg, int cpu)
6084 struct cfs_rq *pcfs_rq, *cfs_rq;
6086 if (!cfs_bandwidth_used())
6092 cfs_rq = tg->cfs_rq[cpu];
6093 pcfs_rq = tg->parent->cfs_rq[cpu];
6095 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6096 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6099 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6100 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6102 if (!cfs_bandwidth_used())
6105 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6109 * it's possible for a throttled entity to be forced into a running
6110 * state (e.g. set_curr_task), in this case we're finished.
6112 if (cfs_rq_throttled(cfs_rq))
6115 return throttle_cfs_rq(cfs_rq);
6118 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6120 struct cfs_bandwidth *cfs_b =
6121 container_of(timer, struct cfs_bandwidth, slack_timer);
6123 do_sched_cfs_slack_timer(cfs_b);
6125 return HRTIMER_NORESTART;
6128 extern const u64 max_cfs_quota_period;
6130 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6132 struct cfs_bandwidth *cfs_b =
6133 container_of(timer, struct cfs_bandwidth, period_timer);
6134 unsigned long flags;
6139 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6141 overrun = hrtimer_forward_now(timer, cfs_b->period);
6145 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6148 u64 new, old = ktime_to_ns(cfs_b->period);
6151 * Grow period by a factor of 2 to avoid losing precision.
6152 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6156 if (new < max_cfs_quota_period) {
6157 cfs_b->period = ns_to_ktime(new);
6161 pr_warn_ratelimited(
6162 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6164 div_u64(new, NSEC_PER_USEC),
6165 div_u64(cfs_b->quota, NSEC_PER_USEC));
6167 pr_warn_ratelimited(
6168 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6170 div_u64(old, NSEC_PER_USEC),
6171 div_u64(cfs_b->quota, NSEC_PER_USEC));
6174 /* reset count so we don't come right back in here */
6179 cfs_b->period_active = 0;
6180 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6182 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6185 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6187 raw_spin_lock_init(&cfs_b->lock);
6189 cfs_b->quota = RUNTIME_INF;
6190 cfs_b->period = ns_to_ktime(default_cfs_period());
6192 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6194 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6195 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6196 cfs_b->period_timer.function = sched_cfs_period_timer;
6198 /* Add a random offset so that timers interleave */
6199 hrtimer_set_expires(&cfs_b->period_timer,
6200 get_random_u32_below(cfs_b->period));
6201 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6202 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6203 cfs_b->slack_started = false;
6206 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6208 cfs_rq->runtime_enabled = 0;
6209 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6210 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6213 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6215 lockdep_assert_held(&cfs_b->lock);
6217 if (cfs_b->period_active)
6220 cfs_b->period_active = 1;
6221 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6222 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6225 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6227 int __maybe_unused i;
6229 /* init_cfs_bandwidth() was not called */
6230 if (!cfs_b->throttled_cfs_rq.next)
6233 hrtimer_cancel(&cfs_b->period_timer);
6234 hrtimer_cancel(&cfs_b->slack_timer);
6237 * It is possible that we still have some cfs_rq's pending on a CSD
6238 * list, though this race is very rare. In order for this to occur, we
6239 * must have raced with the last task leaving the group while there
6240 * exist throttled cfs_rq(s), and the period_timer must have queued the
6241 * CSD item but the remote cpu has not yet processed it. To handle this,
6242 * we can simply flush all pending CSD work inline here. We're
6243 * guaranteed at this point that no additional cfs_rq of this group can
6247 for_each_possible_cpu(i) {
6248 struct rq *rq = cpu_rq(i);
6249 unsigned long flags;
6251 if (list_empty(&rq->cfsb_csd_list))
6254 local_irq_save(flags);
6255 __cfsb_csd_unthrottle(rq);
6256 local_irq_restore(flags);
6262 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6264 * The race is harmless, since modifying bandwidth settings of unhooked group
6265 * bits doesn't do much.
6268 /* cpu online callback */
6269 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6271 struct task_group *tg;
6273 lockdep_assert_rq_held(rq);
6276 list_for_each_entry_rcu(tg, &task_groups, list) {
6277 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6278 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6280 raw_spin_lock(&cfs_b->lock);
6281 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6282 raw_spin_unlock(&cfs_b->lock);
6287 /* cpu offline callback */
6288 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6290 struct task_group *tg;
6292 lockdep_assert_rq_held(rq);
6295 * The rq clock has already been updated in the
6296 * set_rq_offline(), so we should skip updating
6297 * the rq clock again in unthrottle_cfs_rq().
6299 rq_clock_start_loop_update(rq);
6302 list_for_each_entry_rcu(tg, &task_groups, list) {
6303 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6305 if (!cfs_rq->runtime_enabled)
6309 * clock_task is not advancing so we just need to make sure
6310 * there's some valid quota amount
6312 cfs_rq->runtime_remaining = 1;
6314 * Offline rq is schedulable till CPU is completely disabled
6315 * in take_cpu_down(), so we prevent new cfs throttling here.
6317 cfs_rq->runtime_enabled = 0;
6319 if (cfs_rq_throttled(cfs_rq))
6320 unthrottle_cfs_rq(cfs_rq);
6324 rq_clock_stop_loop_update(rq);
6327 bool cfs_task_bw_constrained(struct task_struct *p)
6329 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6331 if (!cfs_bandwidth_used())
6334 if (cfs_rq->runtime_enabled ||
6335 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6341 #ifdef CONFIG_NO_HZ_FULL
6342 /* called from pick_next_task_fair() */
6343 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6345 int cpu = cpu_of(rq);
6347 if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6350 if (!tick_nohz_full_cpu(cpu))
6353 if (rq->nr_running != 1)
6357 * We know there is only one task runnable and we've just picked it. The
6358 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6359 * be otherwise able to stop the tick. Just need to check if we are using
6360 * bandwidth control.
6362 if (cfs_task_bw_constrained(p))
6363 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6367 #else /* CONFIG_CFS_BANDWIDTH */
6369 static inline bool cfs_bandwidth_used(void)
6374 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6375 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6376 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6377 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6378 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6380 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6385 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6390 static inline int throttled_lb_pair(struct task_group *tg,
6391 int src_cpu, int dest_cpu)
6396 #ifdef CONFIG_FAIR_GROUP_SCHED
6397 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6398 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6401 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6405 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6406 static inline void update_runtime_enabled(struct rq *rq) {}
6407 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6408 #ifdef CONFIG_CGROUP_SCHED
6409 bool cfs_task_bw_constrained(struct task_struct *p)
6414 #endif /* CONFIG_CFS_BANDWIDTH */
6416 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6417 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6420 /**************************************************
6421 * CFS operations on tasks:
6424 #ifdef CONFIG_SCHED_HRTICK
6425 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6427 struct sched_entity *se = &p->se;
6429 SCHED_WARN_ON(task_rq(p) != rq);
6431 if (rq->cfs.h_nr_running > 1) {
6432 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6433 u64 slice = se->slice;
6434 s64 delta = slice - ran;
6437 if (task_current(rq, p))
6441 hrtick_start(rq, delta);
6446 * called from enqueue/dequeue and updates the hrtick when the
6447 * current task is from our class and nr_running is low enough
6450 static void hrtick_update(struct rq *rq)
6452 struct task_struct *curr = rq->curr;
6454 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6457 hrtick_start_fair(rq, curr);
6459 #else /* !CONFIG_SCHED_HRTICK */
6461 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6465 static inline void hrtick_update(struct rq *rq)
6471 static inline bool cpu_overutilized(int cpu)
6473 unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6474 unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6476 /* Return true only if the utilization doesn't fit CPU's capacity */
6477 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6480 static inline void update_overutilized_status(struct rq *rq)
6482 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6483 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6484 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6488 static inline void update_overutilized_status(struct rq *rq) { }
6491 /* Runqueue only has SCHED_IDLE tasks enqueued */
6492 static int sched_idle_rq(struct rq *rq)
6494 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6499 static int sched_idle_cpu(int cpu)
6501 return sched_idle_rq(cpu_rq(cpu));
6506 * The enqueue_task method is called before nr_running is
6507 * increased. Here we update the fair scheduling stats and
6508 * then put the task into the rbtree:
6511 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6513 struct cfs_rq *cfs_rq;
6514 struct sched_entity *se = &p->se;
6515 int idle_h_nr_running = task_has_idle_policy(p);
6516 int task_new = !(flags & ENQUEUE_WAKEUP);
6519 * The code below (indirectly) updates schedutil which looks at
6520 * the cfs_rq utilization to select a frequency.
6521 * Let's add the task's estimated utilization to the cfs_rq's
6522 * estimated utilization, before we update schedutil.
6524 util_est_enqueue(&rq->cfs, p);
6527 * If in_iowait is set, the code below may not trigger any cpufreq
6528 * utilization updates, so do it here explicitly with the IOWAIT flag
6532 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6534 for_each_sched_entity(se) {
6537 cfs_rq = cfs_rq_of(se);
6538 enqueue_entity(cfs_rq, se, flags);
6540 cfs_rq->h_nr_running++;
6541 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6543 if (cfs_rq_is_idle(cfs_rq))
6544 idle_h_nr_running = 1;
6546 /* end evaluation on encountering a throttled cfs_rq */
6547 if (cfs_rq_throttled(cfs_rq))
6548 goto enqueue_throttle;
6550 flags = ENQUEUE_WAKEUP;
6553 for_each_sched_entity(se) {
6554 cfs_rq = cfs_rq_of(se);
6556 update_load_avg(cfs_rq, se, UPDATE_TG);
6557 se_update_runnable(se);
6558 update_cfs_group(se);
6560 cfs_rq->h_nr_running++;
6561 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6563 if (cfs_rq_is_idle(cfs_rq))
6564 idle_h_nr_running = 1;
6566 /* end evaluation on encountering a throttled cfs_rq */
6567 if (cfs_rq_throttled(cfs_rq))
6568 goto enqueue_throttle;
6571 /* At this point se is NULL and we are at root level*/
6572 add_nr_running(rq, 1);
6575 * Since new tasks are assigned an initial util_avg equal to
6576 * half of the spare capacity of their CPU, tiny tasks have the
6577 * ability to cross the overutilized threshold, which will
6578 * result in the load balancer ruining all the task placement
6579 * done by EAS. As a way to mitigate that effect, do not account
6580 * for the first enqueue operation of new tasks during the
6581 * overutilized flag detection.
6583 * A better way of solving this problem would be to wait for
6584 * the PELT signals of tasks to converge before taking them
6585 * into account, but that is not straightforward to implement,
6586 * and the following generally works well enough in practice.
6589 update_overutilized_status(rq);
6592 assert_list_leaf_cfs_rq(rq);
6597 static void set_next_buddy(struct sched_entity *se);
6600 * The dequeue_task method is called before nr_running is
6601 * decreased. We remove the task from the rbtree and
6602 * update the fair scheduling stats:
6604 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6606 struct cfs_rq *cfs_rq;
6607 struct sched_entity *se = &p->se;
6608 int task_sleep = flags & DEQUEUE_SLEEP;
6609 int idle_h_nr_running = task_has_idle_policy(p);
6610 bool was_sched_idle = sched_idle_rq(rq);
6612 util_est_dequeue(&rq->cfs, p);
6614 for_each_sched_entity(se) {
6615 cfs_rq = cfs_rq_of(se);
6616 dequeue_entity(cfs_rq, se, flags);
6618 cfs_rq->h_nr_running--;
6619 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6621 if (cfs_rq_is_idle(cfs_rq))
6622 idle_h_nr_running = 1;
6624 /* end evaluation on encountering a throttled cfs_rq */
6625 if (cfs_rq_throttled(cfs_rq))
6626 goto dequeue_throttle;
6628 /* Don't dequeue parent if it has other entities besides us */
6629 if (cfs_rq->load.weight) {
6630 /* Avoid re-evaluating load for this entity: */
6631 se = parent_entity(se);
6633 * Bias pick_next to pick a task from this cfs_rq, as
6634 * p is sleeping when it is within its sched_slice.
6636 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6640 flags |= DEQUEUE_SLEEP;
6643 for_each_sched_entity(se) {
6644 cfs_rq = cfs_rq_of(se);
6646 update_load_avg(cfs_rq, se, UPDATE_TG);
6647 se_update_runnable(se);
6648 update_cfs_group(se);
6650 cfs_rq->h_nr_running--;
6651 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6653 if (cfs_rq_is_idle(cfs_rq))
6654 idle_h_nr_running = 1;
6656 /* end evaluation on encountering a throttled cfs_rq */
6657 if (cfs_rq_throttled(cfs_rq))
6658 goto dequeue_throttle;
6662 /* At this point se is NULL and we are at root level*/
6663 sub_nr_running(rq, 1);
6665 /* balance early to pull high priority tasks */
6666 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6667 rq->next_balance = jiffies;
6670 util_est_update(&rq->cfs, p, task_sleep);
6676 /* Working cpumask for: load_balance, load_balance_newidle. */
6677 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6678 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6679 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6681 #ifdef CONFIG_NO_HZ_COMMON
6684 cpumask_var_t idle_cpus_mask;
6686 int has_blocked; /* Idle CPUS has blocked load */
6687 int needs_update; /* Newly idle CPUs need their next_balance collated */
6688 unsigned long next_balance; /* in jiffy units */
6689 unsigned long next_blocked; /* Next update of blocked load in jiffies */
6690 } nohz ____cacheline_aligned;
6692 #endif /* CONFIG_NO_HZ_COMMON */
6694 static unsigned long cpu_load(struct rq *rq)
6696 return cfs_rq_load_avg(&rq->cfs);
6700 * cpu_load_without - compute CPU load without any contributions from *p
6701 * @cpu: the CPU which load is requested
6702 * @p: the task which load should be discounted
6704 * The load of a CPU is defined by the load of tasks currently enqueued on that
6705 * CPU as well as tasks which are currently sleeping after an execution on that
6708 * This method returns the load of the specified CPU by discounting the load of
6709 * the specified task, whenever the task is currently contributing to the CPU
6712 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6714 struct cfs_rq *cfs_rq;
6717 /* Task has no contribution or is new */
6718 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6719 return cpu_load(rq);
6722 load = READ_ONCE(cfs_rq->avg.load_avg);
6724 /* Discount task's util from CPU's util */
6725 lsub_positive(&load, task_h_load(p));
6730 static unsigned long cpu_runnable(struct rq *rq)
6732 return cfs_rq_runnable_avg(&rq->cfs);
6735 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6737 struct cfs_rq *cfs_rq;
6738 unsigned int runnable;
6740 /* Task has no contribution or is new */
6741 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6742 return cpu_runnable(rq);
6745 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6747 /* Discount task's runnable from CPU's runnable */
6748 lsub_positive(&runnable, p->se.avg.runnable_avg);
6753 static unsigned long capacity_of(int cpu)
6755 return cpu_rq(cpu)->cpu_capacity;
6758 static void record_wakee(struct task_struct *p)
6761 * Only decay a single time; tasks that have less then 1 wakeup per
6762 * jiffy will not have built up many flips.
6764 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6765 current->wakee_flips >>= 1;
6766 current->wakee_flip_decay_ts = jiffies;
6769 if (current->last_wakee != p) {
6770 current->last_wakee = p;
6771 current->wakee_flips++;
6776 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6778 * A waker of many should wake a different task than the one last awakened
6779 * at a frequency roughly N times higher than one of its wakees.
6781 * In order to determine whether we should let the load spread vs consolidating
6782 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6783 * partner, and a factor of lls_size higher frequency in the other.
6785 * With both conditions met, we can be relatively sure that the relationship is
6786 * non-monogamous, with partner count exceeding socket size.
6788 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6789 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6792 static int wake_wide(struct task_struct *p)
6794 unsigned int master = current->wakee_flips;
6795 unsigned int slave = p->wakee_flips;
6796 int factor = __this_cpu_read(sd_llc_size);
6799 swap(master, slave);
6800 if (slave < factor || master < slave * factor)
6806 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6807 * soonest. For the purpose of speed we only consider the waking and previous
6810 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6811 * cache-affine and is (or will be) idle.
6813 * wake_affine_weight() - considers the weight to reflect the average
6814 * scheduling latency of the CPUs. This seems to work
6815 * for the overloaded case.
6818 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6821 * If this_cpu is idle, it implies the wakeup is from interrupt
6822 * context. Only allow the move if cache is shared. Otherwise an
6823 * interrupt intensive workload could force all tasks onto one
6824 * node depending on the IO topology or IRQ affinity settings.
6826 * If the prev_cpu is idle and cache affine then avoid a migration.
6827 * There is no guarantee that the cache hot data from an interrupt
6828 * is more important than cache hot data on the prev_cpu and from
6829 * a cpufreq perspective, it's better to have higher utilisation
6832 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6833 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6835 if (sync && cpu_rq(this_cpu)->nr_running == 1)
6838 if (available_idle_cpu(prev_cpu))
6841 return nr_cpumask_bits;
6845 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6846 int this_cpu, int prev_cpu, int sync)
6848 s64 this_eff_load, prev_eff_load;
6849 unsigned long task_load;
6851 this_eff_load = cpu_load(cpu_rq(this_cpu));
6854 unsigned long current_load = task_h_load(current);
6856 if (current_load > this_eff_load)
6859 this_eff_load -= current_load;
6862 task_load = task_h_load(p);
6864 this_eff_load += task_load;
6865 if (sched_feat(WA_BIAS))
6866 this_eff_load *= 100;
6867 this_eff_load *= capacity_of(prev_cpu);
6869 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
6870 prev_eff_load -= task_load;
6871 if (sched_feat(WA_BIAS))
6872 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
6873 prev_eff_load *= capacity_of(this_cpu);
6876 * If sync, adjust the weight of prev_eff_load such that if
6877 * prev_eff == this_eff that select_idle_sibling() will consider
6878 * stacking the wakee on top of the waker if no other CPU is
6884 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6887 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6888 int this_cpu, int prev_cpu, int sync)
6890 int target = nr_cpumask_bits;
6892 if (sched_feat(WA_IDLE))
6893 target = wake_affine_idle(this_cpu, prev_cpu, sync);
6895 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6896 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6898 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
6899 if (target != this_cpu)
6902 schedstat_inc(sd->ttwu_move_affine);
6903 schedstat_inc(p->stats.nr_wakeups_affine);
6907 static struct sched_group *
6908 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6911 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6914 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6916 unsigned long load, min_load = ULONG_MAX;
6917 unsigned int min_exit_latency = UINT_MAX;
6918 u64 latest_idle_timestamp = 0;
6919 int least_loaded_cpu = this_cpu;
6920 int shallowest_idle_cpu = -1;
6923 /* Check if we have any choice: */
6924 if (group->group_weight == 1)
6925 return cpumask_first(sched_group_span(group));
6927 /* Traverse only the allowed CPUs */
6928 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6929 struct rq *rq = cpu_rq(i);
6931 if (!sched_core_cookie_match(rq, p))
6934 if (sched_idle_cpu(i))
6937 if (available_idle_cpu(i)) {
6938 struct cpuidle_state *idle = idle_get_state(rq);
6939 if (idle && idle->exit_latency < min_exit_latency) {
6941 * We give priority to a CPU whose idle state
6942 * has the smallest exit latency irrespective
6943 * of any idle timestamp.
6945 min_exit_latency = idle->exit_latency;
6946 latest_idle_timestamp = rq->idle_stamp;
6947 shallowest_idle_cpu = i;
6948 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6949 rq->idle_stamp > latest_idle_timestamp) {
6951 * If equal or no active idle state, then
6952 * the most recently idled CPU might have
6955 latest_idle_timestamp = rq->idle_stamp;
6956 shallowest_idle_cpu = i;
6958 } else if (shallowest_idle_cpu == -1) {
6959 load = cpu_load(cpu_rq(i));
6960 if (load < min_load) {
6962 least_loaded_cpu = i;
6967 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6970 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6971 int cpu, int prev_cpu, int sd_flag)
6975 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6979 * We need task's util for cpu_util_without, sync it up to
6980 * prev_cpu's last_update_time.
6982 if (!(sd_flag & SD_BALANCE_FORK))
6983 sync_entity_load_avg(&p->se);
6986 struct sched_group *group;
6987 struct sched_domain *tmp;
6990 if (!(sd->flags & sd_flag)) {
6995 group = find_idlest_group(sd, p, cpu);
7001 new_cpu = find_idlest_group_cpu(group, p, cpu);
7002 if (new_cpu == cpu) {
7003 /* Now try balancing at a lower domain level of 'cpu': */
7008 /* Now try balancing at a lower domain level of 'new_cpu': */
7010 weight = sd->span_weight;
7012 for_each_domain(cpu, tmp) {
7013 if (weight <= tmp->span_weight)
7015 if (tmp->flags & sd_flag)
7023 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7025 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7026 sched_cpu_cookie_match(cpu_rq(cpu), p))
7032 #ifdef CONFIG_SCHED_SMT
7033 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7034 EXPORT_SYMBOL_GPL(sched_smt_present);
7036 static inline void set_idle_cores(int cpu, int val)
7038 struct sched_domain_shared *sds;
7040 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7042 WRITE_ONCE(sds->has_idle_cores, val);
7045 static inline bool test_idle_cores(int cpu)
7047 struct sched_domain_shared *sds;
7049 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7051 return READ_ONCE(sds->has_idle_cores);
7057 * Scans the local SMT mask to see if the entire core is idle, and records this
7058 * information in sd_llc_shared->has_idle_cores.
7060 * Since SMT siblings share all cache levels, inspecting this limited remote
7061 * state should be fairly cheap.
7063 void __update_idle_core(struct rq *rq)
7065 int core = cpu_of(rq);
7069 if (test_idle_cores(core))
7072 for_each_cpu(cpu, cpu_smt_mask(core)) {
7076 if (!available_idle_cpu(cpu))
7080 set_idle_cores(core, 1);
7086 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7087 * there are no idle cores left in the system; tracked through
7088 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7090 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7095 for_each_cpu(cpu, cpu_smt_mask(core)) {
7096 if (!available_idle_cpu(cpu)) {
7098 if (*idle_cpu == -1) {
7099 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
7107 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
7114 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7119 * Scan the local SMT mask for idle CPUs.
7121 static int select_idle_smt(struct task_struct *p, int target)
7125 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7128 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7135 #else /* CONFIG_SCHED_SMT */
7137 static inline void set_idle_cores(int cpu, int val)
7141 static inline bool test_idle_cores(int cpu)
7146 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7148 return __select_idle_cpu(core, p);
7151 static inline int select_idle_smt(struct task_struct *p, int target)
7156 #endif /* CONFIG_SCHED_SMT */
7159 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7160 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7161 * average idle time for this rq (as found in rq->avg_idle).
7163 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7165 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7166 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7167 struct sched_domain_shared *sd_share;
7168 struct rq *this_rq = this_rq();
7169 int this = smp_processor_id();
7170 struct sched_domain *this_sd = NULL;
7173 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7175 if (sched_feat(SIS_PROP) && !has_idle_core) {
7176 u64 avg_cost, avg_idle, span_avg;
7177 unsigned long now = jiffies;
7179 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7184 * If we're busy, the assumption that the last idle period
7185 * predicts the future is flawed; age away the remaining
7186 * predicted idle time.
7188 if (unlikely(this_rq->wake_stamp < now)) {
7189 while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7190 this_rq->wake_stamp++;
7191 this_rq->wake_avg_idle >>= 1;
7195 avg_idle = this_rq->wake_avg_idle;
7196 avg_cost = this_sd->avg_scan_cost + 1;
7198 span_avg = sd->span_weight * avg_idle;
7199 if (span_avg > 4*avg_cost)
7200 nr = div_u64(span_avg, avg_cost);
7204 time = cpu_clock(this);
7207 if (sched_feat(SIS_UTIL)) {
7208 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7210 /* because !--nr is the condition to stop scan */
7211 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7212 /* overloaded LLC is unlikely to have idle cpu/core */
7218 for_each_cpu_wrap(cpu, cpus, target + 1) {
7219 if (has_idle_core) {
7220 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7221 if ((unsigned int)i < nr_cpumask_bits)
7227 idle_cpu = __select_idle_cpu(cpu, p);
7228 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7234 set_idle_cores(target, false);
7236 if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7237 time = cpu_clock(this) - time;
7240 * Account for the scan cost of wakeups against the average
7243 this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7245 update_avg(&this_sd->avg_scan_cost, time);
7252 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7253 * the task fits. If no CPU is big enough, but there are idle ones, try to
7254 * maximize capacity.
7257 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7259 unsigned long task_util, util_min, util_max, best_cap = 0;
7260 int fits, best_fits = 0;
7261 int cpu, best_cpu = -1;
7262 struct cpumask *cpus;
7264 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7265 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7267 task_util = task_util_est(p);
7268 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7269 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7271 for_each_cpu_wrap(cpu, cpus, target) {
7272 unsigned long cpu_cap = capacity_of(cpu);
7274 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7277 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7279 /* This CPU fits with all requirements */
7283 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7284 * Look for the CPU with best capacity.
7287 cpu_cap = arch_scale_cpu_capacity(cpu) - thermal_load_avg(cpu_rq(cpu));
7290 * First, select CPU which fits better (-1 being better than 0).
7291 * Then, select the one with best capacity at same level.
7293 if ((fits < best_fits) ||
7294 ((fits == best_fits) && (cpu_cap > best_cap))) {
7304 static inline bool asym_fits_cpu(unsigned long util,
7305 unsigned long util_min,
7306 unsigned long util_max,
7309 if (sched_asym_cpucap_active())
7311 * Return true only if the cpu fully fits the task requirements
7312 * which include the utilization and the performance hints.
7314 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7320 * Try and locate an idle core/thread in the LLC cache domain.
7322 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7324 bool has_idle_core = false;
7325 struct sched_domain *sd;
7326 unsigned long task_util, util_min, util_max;
7327 int i, recent_used_cpu;
7330 * On asymmetric system, update task utilization because we will check
7331 * that the task fits with cpu's capacity.
7333 if (sched_asym_cpucap_active()) {
7334 sync_entity_load_avg(&p->se);
7335 task_util = task_util_est(p);
7336 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7337 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7341 * per-cpu select_rq_mask usage
7343 lockdep_assert_irqs_disabled();
7345 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7346 asym_fits_cpu(task_util, util_min, util_max, target))
7350 * If the previous CPU is cache affine and idle, don't be stupid:
7352 if (prev != target && cpus_share_cache(prev, target) &&
7353 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7354 asym_fits_cpu(task_util, util_min, util_max, prev))
7358 * Allow a per-cpu kthread to stack with the wakee if the
7359 * kworker thread and the tasks previous CPUs are the same.
7360 * The assumption is that the wakee queued work for the
7361 * per-cpu kthread that is now complete and the wakeup is
7362 * essentially a sync wakeup. An obvious example of this
7363 * pattern is IO completions.
7365 if (is_per_cpu_kthread(current) &&
7367 prev == smp_processor_id() &&
7368 this_rq()->nr_running <= 1 &&
7369 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7373 /* Check a recently used CPU as a potential idle candidate: */
7374 recent_used_cpu = p->recent_used_cpu;
7375 p->recent_used_cpu = prev;
7376 if (recent_used_cpu != prev &&
7377 recent_used_cpu != target &&
7378 cpus_share_cache(recent_used_cpu, target) &&
7379 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7380 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7381 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7382 return recent_used_cpu;
7386 * For asymmetric CPU capacity systems, our domain of interest is
7387 * sd_asym_cpucapacity rather than sd_llc.
7389 if (sched_asym_cpucap_active()) {
7390 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7392 * On an asymmetric CPU capacity system where an exclusive
7393 * cpuset defines a symmetric island (i.e. one unique
7394 * capacity_orig value through the cpuset), the key will be set
7395 * but the CPUs within that cpuset will not have a domain with
7396 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7400 i = select_idle_capacity(p, sd, target);
7401 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7405 sd = rcu_dereference(per_cpu(sd_llc, target));
7409 if (sched_smt_active()) {
7410 has_idle_core = test_idle_cores(target);
7412 if (!has_idle_core && cpus_share_cache(prev, target)) {
7413 i = select_idle_smt(p, prev);
7414 if ((unsigned int)i < nr_cpumask_bits)
7419 i = select_idle_cpu(p, sd, has_idle_core, target);
7420 if ((unsigned)i < nr_cpumask_bits)
7427 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7428 * @cpu: the CPU to get the utilization for
7429 * @p: task for which the CPU utilization should be predicted or NULL
7430 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7431 * @boost: 1 to enable boosting, otherwise 0
7433 * The unit of the return value must be the same as the one of CPU capacity
7434 * so that CPU utilization can be compared with CPU capacity.
7436 * CPU utilization is the sum of running time of runnable tasks plus the
7437 * recent utilization of currently non-runnable tasks on that CPU.
7438 * It represents the amount of CPU capacity currently used by CFS tasks in
7439 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7440 * capacity at f_max.
7442 * The estimated CPU utilization is defined as the maximum between CPU
7443 * utilization and sum of the estimated utilization of the currently
7444 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7445 * previously-executed tasks, which helps better deduce how busy a CPU will
7446 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7447 * of such a task would be significantly decayed at this point of time.
7449 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7450 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7451 * utilization. Boosting is implemented in cpu_util() so that internal
7452 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7453 * latter via cpu_util_cfs_boost().
7455 * CPU utilization can be higher than the current CPU capacity
7456 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7457 * of rounding errors as well as task migrations or wakeups of new tasks.
7458 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7459 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7460 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7461 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7462 * though since this is useful for predicting the CPU capacity required
7463 * after task migrations (scheduler-driven DVFS).
7465 * Return: (Boosted) (estimated) utilization for the specified CPU.
7467 static unsigned long
7468 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7470 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7471 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7472 unsigned long runnable;
7475 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7476 util = max(util, runnable);
7480 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7481 * contribution. If @p migrates from another CPU to @cpu add its
7482 * contribution. In all the other cases @cpu is not impacted by the
7483 * migration so its util_avg is already correct.
7485 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7486 lsub_positive(&util, task_util(p));
7487 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7488 util += task_util(p);
7490 if (sched_feat(UTIL_EST)) {
7491 unsigned long util_est;
7493 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7496 * During wake-up @p isn't enqueued yet and doesn't contribute
7497 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7498 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7499 * has been enqueued.
7501 * During exec (@dst_cpu = -1) @p is enqueued and does
7502 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7503 * Remove it to "simulate" cpu_util without @p's contribution.
7505 * Despite the task_on_rq_queued(@p) check there is still a
7506 * small window for a possible race when an exec
7507 * select_task_rq_fair() races with LB's detach_task().
7511 * p->on_rq = TASK_ON_RQ_MIGRATING;
7512 * -------------------------------- A
7514 * dequeue_task_fair() + Race Time
7515 * util_est_dequeue() /
7516 * -------------------------------- B
7518 * The additional check "current == p" is required to further
7519 * reduce the race window.
7522 util_est += _task_util_est(p);
7523 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7524 lsub_positive(&util_est, _task_util_est(p));
7526 util = max(util, util_est);
7529 return min(util, arch_scale_cpu_capacity(cpu));
7532 unsigned long cpu_util_cfs(int cpu)
7534 return cpu_util(cpu, NULL, -1, 0);
7537 unsigned long cpu_util_cfs_boost(int cpu)
7539 return cpu_util(cpu, NULL, -1, 1);
7543 * cpu_util_without: compute cpu utilization without any contributions from *p
7544 * @cpu: the CPU which utilization is requested
7545 * @p: the task which utilization should be discounted
7547 * The utilization of a CPU is defined by the utilization of tasks currently
7548 * enqueued on that CPU as well as tasks which are currently sleeping after an
7549 * execution on that CPU.
7551 * This method returns the utilization of the specified CPU by discounting the
7552 * utilization of the specified task, whenever the task is currently
7553 * contributing to the CPU utilization.
7555 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7557 /* Task has no contribution or is new */
7558 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7561 return cpu_util(cpu, p, -1, 0);
7565 * energy_env - Utilization landscape for energy estimation.
7566 * @task_busy_time: Utilization contribution by the task for which we test the
7567 * placement. Given by eenv_task_busy_time().
7568 * @pd_busy_time: Utilization of the whole perf domain without the task
7569 * contribution. Given by eenv_pd_busy_time().
7570 * @cpu_cap: Maximum CPU capacity for the perf domain.
7571 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7574 unsigned long task_busy_time;
7575 unsigned long pd_busy_time;
7576 unsigned long cpu_cap;
7577 unsigned long pd_cap;
7581 * Compute the task busy time for compute_energy(). This time cannot be
7582 * injected directly into effective_cpu_util() because of the IRQ scaling.
7583 * The latter only makes sense with the most recent CPUs where the task has
7586 static inline void eenv_task_busy_time(struct energy_env *eenv,
7587 struct task_struct *p, int prev_cpu)
7589 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7590 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7592 if (unlikely(irq >= max_cap))
7593 busy_time = max_cap;
7595 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7597 eenv->task_busy_time = busy_time;
7601 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7602 * utilization for each @pd_cpus, it however doesn't take into account
7603 * clamping since the ratio (utilization / cpu_capacity) is already enough to
7604 * scale the EM reported power consumption at the (eventually clamped)
7607 * The contribution of the task @p for which we want to estimate the
7608 * energy cost is removed (by cpu_util()) and must be calculated
7609 * separately (see eenv_task_busy_time). This ensures:
7611 * - A stable PD utilization, no matter which CPU of that PD we want to place
7614 * - A fair comparison between CPUs as the task contribution (task_util())
7615 * will always be the same no matter which CPU utilization we rely on
7616 * (util_avg or util_est).
7618 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7619 * exceed @eenv->pd_cap.
7621 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7622 struct cpumask *pd_cpus,
7623 struct task_struct *p)
7625 unsigned long busy_time = 0;
7628 for_each_cpu(cpu, pd_cpus) {
7629 unsigned long util = cpu_util(cpu, p, -1, 0);
7631 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7634 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7638 * Compute the maximum utilization for compute_energy() when the task @p
7639 * is placed on the cpu @dst_cpu.
7641 * Returns the maximum utilization among @eenv->cpus. This utilization can't
7642 * exceed @eenv->cpu_cap.
7644 static inline unsigned long
7645 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7646 struct task_struct *p, int dst_cpu)
7648 unsigned long max_util = 0;
7651 for_each_cpu(cpu, pd_cpus) {
7652 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7653 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7654 unsigned long eff_util;
7657 * Performance domain frequency: utilization clamping
7658 * must be considered since it affects the selection
7659 * of the performance domain frequency.
7660 * NOTE: in case RT tasks are running, by default the
7661 * FREQUENCY_UTIL's utilization can be max OPP.
7663 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7664 max_util = max(max_util, eff_util);
7667 return min(max_util, eenv->cpu_cap);
7671 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7672 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7673 * contribution is ignored.
7675 static inline unsigned long
7676 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7677 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7679 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7680 unsigned long busy_time = eenv->pd_busy_time;
7681 unsigned long energy;
7684 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7686 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7688 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
7694 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7695 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7696 * spare capacity in each performance domain and uses it as a potential
7697 * candidate to execute the task. Then, it uses the Energy Model to figure
7698 * out which of the CPU candidates is the most energy-efficient.
7700 * The rationale for this heuristic is as follows. In a performance domain,
7701 * all the most energy efficient CPU candidates (according to the Energy
7702 * Model) are those for which we'll request a low frequency. When there are
7703 * several CPUs for which the frequency request will be the same, we don't
7704 * have enough data to break the tie between them, because the Energy Model
7705 * only includes active power costs. With this model, if we assume that
7706 * frequency requests follow utilization (e.g. using schedutil), the CPU with
7707 * the maximum spare capacity in a performance domain is guaranteed to be among
7708 * the best candidates of the performance domain.
7710 * In practice, it could be preferable from an energy standpoint to pack
7711 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7712 * but that could also hurt our chances to go cluster idle, and we have no
7713 * ways to tell with the current Energy Model if this is actually a good
7714 * idea or not. So, find_energy_efficient_cpu() basically favors
7715 * cluster-packing, and spreading inside a cluster. That should at least be
7716 * a good thing for latency, and this is consistent with the idea that most
7717 * of the energy savings of EAS come from the asymmetry of the system, and
7718 * not so much from breaking the tie between identical CPUs. That's also the
7719 * reason why EAS is enabled in the topology code only for systems where
7720 * SD_ASYM_CPUCAPACITY is set.
7722 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7723 * they don't have any useful utilization data yet and it's not possible to
7724 * forecast their impact on energy consumption. Consequently, they will be
7725 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7726 * to be energy-inefficient in some use-cases. The alternative would be to
7727 * bias new tasks towards specific types of CPUs first, or to try to infer
7728 * their util_avg from the parent task, but those heuristics could hurt
7729 * other use-cases too. So, until someone finds a better way to solve this,
7730 * let's keep things simple by re-using the existing slow path.
7732 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7734 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7735 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7736 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7737 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7738 struct root_domain *rd = this_rq()->rd;
7739 int cpu, best_energy_cpu, target = -1;
7740 int prev_fits = -1, best_fits = -1;
7741 unsigned long best_thermal_cap = 0;
7742 unsigned long prev_thermal_cap = 0;
7743 struct sched_domain *sd;
7744 struct perf_domain *pd;
7745 struct energy_env eenv;
7748 pd = rcu_dereference(rd->pd);
7749 if (!pd || READ_ONCE(rd->overutilized))
7753 * Energy-aware wake-up happens on the lowest sched_domain starting
7754 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7756 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7757 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7764 sync_entity_load_avg(&p->se);
7765 if (!task_util_est(p) && p_util_min == 0)
7768 eenv_task_busy_time(&eenv, p, prev_cpu);
7770 for (; pd; pd = pd->next) {
7771 unsigned long util_min = p_util_min, util_max = p_util_max;
7772 unsigned long cpu_cap, cpu_thermal_cap, util;
7773 long prev_spare_cap = -1, max_spare_cap = -1;
7774 unsigned long rq_util_min, rq_util_max;
7775 unsigned long cur_delta, base_energy;
7776 int max_spare_cap_cpu = -1;
7777 int fits, max_fits = -1;
7779 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7781 if (cpumask_empty(cpus))
7784 /* Account thermal pressure for the energy estimation */
7785 cpu = cpumask_first(cpus);
7786 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7787 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7789 eenv.cpu_cap = cpu_thermal_cap;
7792 for_each_cpu(cpu, cpus) {
7793 struct rq *rq = cpu_rq(cpu);
7795 eenv.pd_cap += cpu_thermal_cap;
7797 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7800 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7803 util = cpu_util(cpu, p, cpu, 0);
7804 cpu_cap = capacity_of(cpu);
7807 * Skip CPUs that cannot satisfy the capacity request.
7808 * IOW, placing the task there would make the CPU
7809 * overutilized. Take uclamp into account to see how
7810 * much capacity we can get out of the CPU; this is
7811 * aligned with sched_cpu_util().
7813 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7815 * Open code uclamp_rq_util_with() except for
7816 * the clamp() part. Ie: apply max aggregation
7817 * only. util_fits_cpu() logic requires to
7818 * operate on non clamped util but must use the
7819 * max-aggregated uclamp_{min, max}.
7821 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7822 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7824 util_min = max(rq_util_min, p_util_min);
7825 util_max = max(rq_util_max, p_util_max);
7828 fits = util_fits_cpu(util, util_min, util_max, cpu);
7832 lsub_positive(&cpu_cap, util);
7834 if (cpu == prev_cpu) {
7835 /* Always use prev_cpu as a candidate. */
7836 prev_spare_cap = cpu_cap;
7838 } else if ((fits > max_fits) ||
7839 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
7841 * Find the CPU with the maximum spare capacity
7842 * among the remaining CPUs in the performance
7845 max_spare_cap = cpu_cap;
7846 max_spare_cap_cpu = cpu;
7851 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
7854 eenv_pd_busy_time(&eenv, cpus, p);
7855 /* Compute the 'base' energy of the pd, without @p */
7856 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
7858 /* Evaluate the energy impact of using prev_cpu. */
7859 if (prev_spare_cap > -1) {
7860 prev_delta = compute_energy(&eenv, pd, cpus, p,
7862 /* CPU utilization has changed */
7863 if (prev_delta < base_energy)
7865 prev_delta -= base_energy;
7866 prev_thermal_cap = cpu_thermal_cap;
7867 best_delta = min(best_delta, prev_delta);
7870 /* Evaluate the energy impact of using max_spare_cap_cpu. */
7871 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
7872 /* Current best energy cpu fits better */
7873 if (max_fits < best_fits)
7877 * Both don't fit performance hint (i.e. uclamp_min)
7878 * but best energy cpu has better capacity.
7880 if ((max_fits < 0) &&
7881 (cpu_thermal_cap <= best_thermal_cap))
7884 cur_delta = compute_energy(&eenv, pd, cpus, p,
7886 /* CPU utilization has changed */
7887 if (cur_delta < base_energy)
7889 cur_delta -= base_energy;
7892 * Both fit for the task but best energy cpu has lower
7895 if ((max_fits > 0) && (best_fits > 0) &&
7896 (cur_delta >= best_delta))
7899 best_delta = cur_delta;
7900 best_energy_cpu = max_spare_cap_cpu;
7901 best_fits = max_fits;
7902 best_thermal_cap = cpu_thermal_cap;
7907 if ((best_fits > prev_fits) ||
7908 ((best_fits > 0) && (best_delta < prev_delta)) ||
7909 ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
7910 target = best_energy_cpu;
7921 * select_task_rq_fair: Select target runqueue for the waking task in domains
7922 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
7923 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7925 * Balances load by selecting the idlest CPU in the idlest group, or under
7926 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
7928 * Returns the target CPU number.
7931 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
7933 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
7934 struct sched_domain *tmp, *sd = NULL;
7935 int cpu = smp_processor_id();
7936 int new_cpu = prev_cpu;
7937 int want_affine = 0;
7938 /* SD_flags and WF_flags share the first nibble */
7939 int sd_flag = wake_flags & 0xF;
7942 * required for stable ->cpus_allowed
7944 lockdep_assert_held(&p->pi_lock);
7945 if (wake_flags & WF_TTWU) {
7948 if ((wake_flags & WF_CURRENT_CPU) &&
7949 cpumask_test_cpu(cpu, p->cpus_ptr))
7952 if (sched_energy_enabled()) {
7953 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
7959 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
7963 for_each_domain(cpu, tmp) {
7965 * If both 'cpu' and 'prev_cpu' are part of this domain,
7966 * cpu is a valid SD_WAKE_AFFINE target.
7968 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
7969 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
7970 if (cpu != prev_cpu)
7971 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
7973 sd = NULL; /* Prefer wake_affine over balance flags */
7978 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
7979 * usually do not have SD_BALANCE_WAKE set. That means wakeup
7980 * will usually go to the fast path.
7982 if (tmp->flags & sd_flag)
7984 else if (!want_affine)
7990 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
7991 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
7993 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8001 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8002 * cfs_rq_of(p) references at time of call are still valid and identify the
8003 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8005 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8007 struct sched_entity *se = &p->se;
8009 if (!task_on_rq_migrating(p)) {
8010 remove_entity_load_avg(se);
8013 * Here, the task's PELT values have been updated according to
8014 * the current rq's clock. But if that clock hasn't been
8015 * updated in a while, a substantial idle time will be missed,
8016 * leading to an inflation after wake-up on the new rq.
8018 * Estimate the missing time from the cfs_rq last_update_time
8019 * and update sched_avg to improve the PELT continuity after
8022 migrate_se_pelt_lag(se);
8025 /* Tell new CPU we are migrated */
8026 se->avg.last_update_time = 0;
8028 update_scan_period(p, new_cpu);
8031 static void task_dead_fair(struct task_struct *p)
8033 remove_entity_load_avg(&p->se);
8037 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8042 return newidle_balance(rq, rf) != 0;
8044 #endif /* CONFIG_SMP */
8046 static void set_next_buddy(struct sched_entity *se)
8048 for_each_sched_entity(se) {
8049 if (SCHED_WARN_ON(!se->on_rq))
8053 cfs_rq_of(se)->next = se;
8058 * Preempt the current task with a newly woken task if needed:
8060 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8062 struct task_struct *curr = rq->curr;
8063 struct sched_entity *se = &curr->se, *pse = &p->se;
8064 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8065 int next_buddy_marked = 0;
8066 int cse_is_idle, pse_is_idle;
8068 if (unlikely(se == pse))
8072 * This is possible from callers such as attach_tasks(), in which we
8073 * unconditionally wakeup_preempt() after an enqueue (which may have
8074 * lead to a throttle). This both saves work and prevents false
8075 * next-buddy nomination below.
8077 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8080 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8081 set_next_buddy(pse);
8082 next_buddy_marked = 1;
8086 * We can come here with TIF_NEED_RESCHED already set from new task
8089 * Note: this also catches the edge-case of curr being in a throttled
8090 * group (e.g. via set_curr_task), since update_curr() (in the
8091 * enqueue of curr) will have resulted in resched being set. This
8092 * prevents us from potentially nominating it as a false LAST_BUDDY
8095 if (test_tsk_need_resched(curr))
8098 /* Idle tasks are by definition preempted by non-idle tasks. */
8099 if (unlikely(task_has_idle_policy(curr)) &&
8100 likely(!task_has_idle_policy(p)))
8104 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8105 * is driven by the tick):
8107 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8110 find_matching_se(&se, &pse);
8113 cse_is_idle = se_is_idle(se);
8114 pse_is_idle = se_is_idle(pse);
8117 * Preempt an idle group in favor of a non-idle group (and don't preempt
8118 * in the inverse case).
8120 if (cse_is_idle && !pse_is_idle)
8122 if (cse_is_idle != pse_is_idle)
8125 cfs_rq = cfs_rq_of(se);
8126 update_curr(cfs_rq);
8129 * XXX pick_eevdf(cfs_rq) != se ?
8131 if (pick_eevdf(cfs_rq) == pse)
8141 static struct task_struct *pick_task_fair(struct rq *rq)
8143 struct sched_entity *se;
8144 struct cfs_rq *cfs_rq;
8148 if (!cfs_rq->nr_running)
8152 struct sched_entity *curr = cfs_rq->curr;
8154 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8157 update_curr(cfs_rq);
8161 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8165 se = pick_next_entity(cfs_rq, curr);
8166 cfs_rq = group_cfs_rq(se);
8173 struct task_struct *
8174 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8176 struct cfs_rq *cfs_rq = &rq->cfs;
8177 struct sched_entity *se;
8178 struct task_struct *p;
8182 if (!sched_fair_runnable(rq))
8185 #ifdef CONFIG_FAIR_GROUP_SCHED
8186 if (!prev || prev->sched_class != &fair_sched_class)
8190 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8191 * likely that a next task is from the same cgroup as the current.
8193 * Therefore attempt to avoid putting and setting the entire cgroup
8194 * hierarchy, only change the part that actually changes.
8198 struct sched_entity *curr = cfs_rq->curr;
8201 * Since we got here without doing put_prev_entity() we also
8202 * have to consider cfs_rq->curr. If it is still a runnable
8203 * entity, update_curr() will update its vruntime, otherwise
8204 * forget we've ever seen it.
8208 update_curr(cfs_rq);
8213 * This call to check_cfs_rq_runtime() will do the
8214 * throttle and dequeue its entity in the parent(s).
8215 * Therefore the nr_running test will indeed
8218 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8221 if (!cfs_rq->nr_running)
8228 se = pick_next_entity(cfs_rq, curr);
8229 cfs_rq = group_cfs_rq(se);
8235 * Since we haven't yet done put_prev_entity and if the selected task
8236 * is a different task than we started out with, try and touch the
8237 * least amount of cfs_rqs.
8240 struct sched_entity *pse = &prev->se;
8242 while (!(cfs_rq = is_same_group(se, pse))) {
8243 int se_depth = se->depth;
8244 int pse_depth = pse->depth;
8246 if (se_depth <= pse_depth) {
8247 put_prev_entity(cfs_rq_of(pse), pse);
8248 pse = parent_entity(pse);
8250 if (se_depth >= pse_depth) {
8251 set_next_entity(cfs_rq_of(se), se);
8252 se = parent_entity(se);
8256 put_prev_entity(cfs_rq, pse);
8257 set_next_entity(cfs_rq, se);
8264 put_prev_task(rq, prev);
8267 se = pick_next_entity(cfs_rq, NULL);
8268 set_next_entity(cfs_rq, se);
8269 cfs_rq = group_cfs_rq(se);
8274 done: __maybe_unused;
8277 * Move the next running task to the front of
8278 * the list, so our cfs_tasks list becomes MRU
8281 list_move(&p->se.group_node, &rq->cfs_tasks);
8284 if (hrtick_enabled_fair(rq))
8285 hrtick_start_fair(rq, p);
8287 update_misfit_status(p, rq);
8288 sched_fair_update_stop_tick(rq, p);
8296 new_tasks = newidle_balance(rq, rf);
8299 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8300 * possible for any higher priority task to appear. In that case we
8301 * must re-start the pick_next_entity() loop.
8310 * rq is about to be idle, check if we need to update the
8311 * lost_idle_time of clock_pelt
8313 update_idle_rq_clock_pelt(rq);
8318 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8320 return pick_next_task_fair(rq, NULL, NULL);
8324 * Account for a descheduled task:
8326 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8328 struct sched_entity *se = &prev->se;
8329 struct cfs_rq *cfs_rq;
8331 for_each_sched_entity(se) {
8332 cfs_rq = cfs_rq_of(se);
8333 put_prev_entity(cfs_rq, se);
8338 * sched_yield() is very simple
8340 static void yield_task_fair(struct rq *rq)
8342 struct task_struct *curr = rq->curr;
8343 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8344 struct sched_entity *se = &curr->se;
8347 * Are we the only task in the tree?
8349 if (unlikely(rq->nr_running == 1))
8352 clear_buddies(cfs_rq, se);
8354 update_rq_clock(rq);
8356 * Update run-time statistics of the 'current'.
8358 update_curr(cfs_rq);
8360 * Tell update_rq_clock() that we've just updated,
8361 * so we don't do microscopic update in schedule()
8362 * and double the fastpath cost.
8364 rq_clock_skip_update(rq);
8366 se->deadline += calc_delta_fair(se->slice, se);
8369 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8371 struct sched_entity *se = &p->se;
8373 /* throttled hierarchies are not runnable */
8374 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8377 /* Tell the scheduler that we'd really like pse to run next. */
8380 yield_task_fair(rq);
8386 /**************************************************
8387 * Fair scheduling class load-balancing methods.
8391 * The purpose of load-balancing is to achieve the same basic fairness the
8392 * per-CPU scheduler provides, namely provide a proportional amount of compute
8393 * time to each task. This is expressed in the following equation:
8395 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8397 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8398 * W_i,0 is defined as:
8400 * W_i,0 = \Sum_j w_i,j (2)
8402 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8403 * is derived from the nice value as per sched_prio_to_weight[].
8405 * The weight average is an exponential decay average of the instantaneous
8408 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8410 * C_i is the compute capacity of CPU i, typically it is the
8411 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8412 * can also include other factors [XXX].
8414 * To achieve this balance we define a measure of imbalance which follows
8415 * directly from (1):
8417 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8419 * We them move tasks around to minimize the imbalance. In the continuous
8420 * function space it is obvious this converges, in the discrete case we get
8421 * a few fun cases generally called infeasible weight scenarios.
8424 * - infeasible weights;
8425 * - local vs global optima in the discrete case. ]
8430 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8431 * for all i,j solution, we create a tree of CPUs that follows the hardware
8432 * topology where each level pairs two lower groups (or better). This results
8433 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8434 * tree to only the first of the previous level and we decrease the frequency
8435 * of load-balance at each level inv. proportional to the number of CPUs in
8441 * \Sum { --- * --- * 2^i } = O(n) (5)
8443 * `- size of each group
8444 * | | `- number of CPUs doing load-balance
8446 * `- sum over all levels
8448 * Coupled with a limit on how many tasks we can migrate every balance pass,
8449 * this makes (5) the runtime complexity of the balancer.
8451 * An important property here is that each CPU is still (indirectly) connected
8452 * to every other CPU in at most O(log n) steps:
8454 * The adjacency matrix of the resulting graph is given by:
8457 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8460 * And you'll find that:
8462 * A^(log_2 n)_i,j != 0 for all i,j (7)
8464 * Showing there's indeed a path between every CPU in at most O(log n) steps.
8465 * The task movement gives a factor of O(m), giving a convergence complexity
8468 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8473 * In order to avoid CPUs going idle while there's still work to do, new idle
8474 * balancing is more aggressive and has the newly idle CPU iterate up the domain
8475 * tree itself instead of relying on other CPUs to bring it work.
8477 * This adds some complexity to both (5) and (8) but it reduces the total idle
8485 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8488 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8493 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8495 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8497 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8500 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8501 * rewrite all of this once again.]
8504 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8506 enum fbq_type { regular, remote, all };
8509 * 'group_type' describes the group of CPUs at the moment of load balancing.
8511 * The enum is ordered by pulling priority, with the group with lowest priority
8512 * first so the group_type can simply be compared when selecting the busiest
8513 * group. See update_sd_pick_busiest().
8516 /* The group has spare capacity that can be used to run more tasks. */
8517 group_has_spare = 0,
8519 * The group is fully used and the tasks don't compete for more CPU
8520 * cycles. Nevertheless, some tasks might wait before running.
8524 * One task doesn't fit with CPU's capacity and must be migrated to a
8525 * more powerful CPU.
8529 * Balance SMT group that's fully busy. Can benefit from migration
8530 * a task on SMT with busy sibling to another CPU on idle core.
8534 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8535 * and the task should be migrated to it instead of running on the
8540 * The tasks' affinity constraints previously prevented the scheduler
8541 * from balancing the load across the system.
8545 * The CPU is overloaded and can't provide expected CPU cycles to all
8551 enum migration_type {
8558 #define LBF_ALL_PINNED 0x01
8559 #define LBF_NEED_BREAK 0x02
8560 #define LBF_DST_PINNED 0x04
8561 #define LBF_SOME_PINNED 0x08
8562 #define LBF_ACTIVE_LB 0x10
8565 struct sched_domain *sd;
8573 struct cpumask *dst_grpmask;
8575 enum cpu_idle_type idle;
8577 /* The set of CPUs under consideration for load-balancing */
8578 struct cpumask *cpus;
8583 unsigned int loop_break;
8584 unsigned int loop_max;
8586 enum fbq_type fbq_type;
8587 enum migration_type migration_type;
8588 struct list_head tasks;
8592 * Is this task likely cache-hot:
8594 static int task_hot(struct task_struct *p, struct lb_env *env)
8598 lockdep_assert_rq_held(env->src_rq);
8600 if (p->sched_class != &fair_sched_class)
8603 if (unlikely(task_has_idle_policy(p)))
8606 /* SMT siblings share cache */
8607 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8611 * Buddy candidates are cache hot:
8613 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8614 (&p->se == cfs_rq_of(&p->se)->next))
8617 if (sysctl_sched_migration_cost == -1)
8621 * Don't migrate task if the task's cookie does not match
8622 * with the destination CPU's core cookie.
8624 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8627 if (sysctl_sched_migration_cost == 0)
8630 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8632 return delta < (s64)sysctl_sched_migration_cost;
8635 #ifdef CONFIG_NUMA_BALANCING
8637 * Returns 1, if task migration degrades locality
8638 * Returns 0, if task migration improves locality i.e migration preferred.
8639 * Returns -1, if task migration is not affected by locality.
8641 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8643 struct numa_group *numa_group = rcu_dereference(p->numa_group);
8644 unsigned long src_weight, dst_weight;
8645 int src_nid, dst_nid, dist;
8647 if (!static_branch_likely(&sched_numa_balancing))
8650 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8653 src_nid = cpu_to_node(env->src_cpu);
8654 dst_nid = cpu_to_node(env->dst_cpu);
8656 if (src_nid == dst_nid)
8659 /* Migrating away from the preferred node is always bad. */
8660 if (src_nid == p->numa_preferred_nid) {
8661 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8667 /* Encourage migration to the preferred node. */
8668 if (dst_nid == p->numa_preferred_nid)
8671 /* Leaving a core idle is often worse than degrading locality. */
8672 if (env->idle == CPU_IDLE)
8675 dist = node_distance(src_nid, dst_nid);
8677 src_weight = group_weight(p, src_nid, dist);
8678 dst_weight = group_weight(p, dst_nid, dist);
8680 src_weight = task_weight(p, src_nid, dist);
8681 dst_weight = task_weight(p, dst_nid, dist);
8684 return dst_weight < src_weight;
8688 static inline int migrate_degrades_locality(struct task_struct *p,
8696 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8699 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8703 lockdep_assert_rq_held(env->src_rq);
8706 * We do not migrate tasks that are:
8707 * 1) throttled_lb_pair, or
8708 * 2) cannot be migrated to this CPU due to cpus_ptr, or
8709 * 3) running (obviously), or
8710 * 4) are cache-hot on their current CPU.
8712 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8715 /* Disregard pcpu kthreads; they are where they need to be. */
8716 if (kthread_is_per_cpu(p))
8719 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8722 schedstat_inc(p->stats.nr_failed_migrations_affine);
8724 env->flags |= LBF_SOME_PINNED;
8727 * Remember if this task can be migrated to any other CPU in
8728 * our sched_group. We may want to revisit it if we couldn't
8729 * meet load balance goals by pulling other tasks on src_cpu.
8731 * Avoid computing new_dst_cpu
8733 * - if we have already computed one in current iteration
8734 * - if it's an active balance
8736 if (env->idle == CPU_NEWLY_IDLE ||
8737 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8740 /* Prevent to re-select dst_cpu via env's CPUs: */
8741 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8742 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8743 env->flags |= LBF_DST_PINNED;
8744 env->new_dst_cpu = cpu;
8752 /* Record that we found at least one task that could run on dst_cpu */
8753 env->flags &= ~LBF_ALL_PINNED;
8755 if (task_on_cpu(env->src_rq, p)) {
8756 schedstat_inc(p->stats.nr_failed_migrations_running);
8761 * Aggressive migration if:
8763 * 2) destination numa is preferred
8764 * 3) task is cache cold, or
8765 * 4) too many balance attempts have failed.
8767 if (env->flags & LBF_ACTIVE_LB)
8770 tsk_cache_hot = migrate_degrades_locality(p, env);
8771 if (tsk_cache_hot == -1)
8772 tsk_cache_hot = task_hot(p, env);
8774 if (tsk_cache_hot <= 0 ||
8775 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
8776 if (tsk_cache_hot == 1) {
8777 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
8778 schedstat_inc(p->stats.nr_forced_migrations);
8783 schedstat_inc(p->stats.nr_failed_migrations_hot);
8788 * detach_task() -- detach the task for the migration specified in env
8790 static void detach_task(struct task_struct *p, struct lb_env *env)
8792 lockdep_assert_rq_held(env->src_rq);
8794 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8795 set_task_cpu(p, env->dst_cpu);
8799 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8800 * part of active balancing operations within "domain".
8802 * Returns a task if successful and NULL otherwise.
8804 static struct task_struct *detach_one_task(struct lb_env *env)
8806 struct task_struct *p;
8808 lockdep_assert_rq_held(env->src_rq);
8810 list_for_each_entry_reverse(p,
8811 &env->src_rq->cfs_tasks, se.group_node) {
8812 if (!can_migrate_task(p, env))
8815 detach_task(p, env);
8818 * Right now, this is only the second place where
8819 * lb_gained[env->idle] is updated (other is detach_tasks)
8820 * so we can safely collect stats here rather than
8821 * inside detach_tasks().
8823 schedstat_inc(env->sd->lb_gained[env->idle]);
8830 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8831 * busiest_rq, as part of a balancing operation within domain "sd".
8833 * Returns number of detached tasks if successful and 0 otherwise.
8835 static int detach_tasks(struct lb_env *env)
8837 struct list_head *tasks = &env->src_rq->cfs_tasks;
8838 unsigned long util, load;
8839 struct task_struct *p;
8842 lockdep_assert_rq_held(env->src_rq);
8845 * Source run queue has been emptied by another CPU, clear
8846 * LBF_ALL_PINNED flag as we will not test any task.
8848 if (env->src_rq->nr_running <= 1) {
8849 env->flags &= ~LBF_ALL_PINNED;
8853 if (env->imbalance <= 0)
8856 while (!list_empty(tasks)) {
8858 * We don't want to steal all, otherwise we may be treated likewise,
8859 * which could at worst lead to a livelock crash.
8861 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
8866 * We've more or less seen every task there is, call it quits
8867 * unless we haven't found any movable task yet.
8869 if (env->loop > env->loop_max &&
8870 !(env->flags & LBF_ALL_PINNED))
8873 /* take a breather every nr_migrate tasks */
8874 if (env->loop > env->loop_break) {
8875 env->loop_break += SCHED_NR_MIGRATE_BREAK;
8876 env->flags |= LBF_NEED_BREAK;
8880 p = list_last_entry(tasks, struct task_struct, se.group_node);
8882 if (!can_migrate_task(p, env))
8885 switch (env->migration_type) {
8888 * Depending of the number of CPUs and tasks and the
8889 * cgroup hierarchy, task_h_load() can return a null
8890 * value. Make sure that env->imbalance decreases
8891 * otherwise detach_tasks() will stop only after
8892 * detaching up to loop_max tasks.
8894 load = max_t(unsigned long, task_h_load(p), 1);
8896 if (sched_feat(LB_MIN) &&
8897 load < 16 && !env->sd->nr_balance_failed)
8901 * Make sure that we don't migrate too much load.
8902 * Nevertheless, let relax the constraint if
8903 * scheduler fails to find a good waiting task to
8906 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
8909 env->imbalance -= load;
8913 util = task_util_est(p);
8915 if (util > env->imbalance)
8918 env->imbalance -= util;
8925 case migrate_misfit:
8926 /* This is not a misfit task */
8927 if (task_fits_cpu(p, env->src_cpu))
8934 detach_task(p, env);
8935 list_add(&p->se.group_node, &env->tasks);
8939 #ifdef CONFIG_PREEMPTION
8941 * NEWIDLE balancing is a source of latency, so preemptible
8942 * kernels will stop after the first task is detached to minimize
8943 * the critical section.
8945 if (env->idle == CPU_NEWLY_IDLE)
8950 * We only want to steal up to the prescribed amount of
8953 if (env->imbalance <= 0)
8958 list_move(&p->se.group_node, tasks);
8962 * Right now, this is one of only two places we collect this stat
8963 * so we can safely collect detach_one_task() stats here rather
8964 * than inside detach_one_task().
8966 schedstat_add(env->sd->lb_gained[env->idle], detached);
8972 * attach_task() -- attach the task detached by detach_task() to its new rq.
8974 static void attach_task(struct rq *rq, struct task_struct *p)
8976 lockdep_assert_rq_held(rq);
8978 WARN_ON_ONCE(task_rq(p) != rq);
8979 activate_task(rq, p, ENQUEUE_NOCLOCK);
8980 wakeup_preempt(rq, p, 0);
8984 * attach_one_task() -- attaches the task returned from detach_one_task() to
8987 static void attach_one_task(struct rq *rq, struct task_struct *p)
8992 update_rq_clock(rq);
8998 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9001 static void attach_tasks(struct lb_env *env)
9003 struct list_head *tasks = &env->tasks;
9004 struct task_struct *p;
9007 rq_lock(env->dst_rq, &rf);
9008 update_rq_clock(env->dst_rq);
9010 while (!list_empty(tasks)) {
9011 p = list_first_entry(tasks, struct task_struct, se.group_node);
9012 list_del_init(&p->se.group_node);
9014 attach_task(env->dst_rq, p);
9017 rq_unlock(env->dst_rq, &rf);
9020 #ifdef CONFIG_NO_HZ_COMMON
9021 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9023 if (cfs_rq->avg.load_avg)
9026 if (cfs_rq->avg.util_avg)
9032 static inline bool others_have_blocked(struct rq *rq)
9034 if (READ_ONCE(rq->avg_rt.util_avg))
9037 if (READ_ONCE(rq->avg_dl.util_avg))
9040 if (thermal_load_avg(rq))
9043 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
9044 if (READ_ONCE(rq->avg_irq.util_avg))
9051 static inline void update_blocked_load_tick(struct rq *rq)
9053 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9056 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9059 rq->has_blocked_load = 0;
9062 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
9063 static inline bool others_have_blocked(struct rq *rq) { return false; }
9064 static inline void update_blocked_load_tick(struct rq *rq) {}
9065 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9068 static bool __update_blocked_others(struct rq *rq, bool *done)
9070 const struct sched_class *curr_class;
9071 u64 now = rq_clock_pelt(rq);
9072 unsigned long thermal_pressure;
9076 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9077 * DL and IRQ signals have been updated before updating CFS.
9079 curr_class = rq->curr->sched_class;
9081 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9083 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9084 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9085 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9086 update_irq_load_avg(rq, 0);
9088 if (others_have_blocked(rq))
9094 #ifdef CONFIG_FAIR_GROUP_SCHED
9096 static bool __update_blocked_fair(struct rq *rq, bool *done)
9098 struct cfs_rq *cfs_rq, *pos;
9099 bool decayed = false;
9100 int cpu = cpu_of(rq);
9103 * Iterates the task_group tree in a bottom up fashion, see
9104 * list_add_leaf_cfs_rq() for details.
9106 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9107 struct sched_entity *se;
9109 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9110 update_tg_load_avg(cfs_rq);
9112 if (cfs_rq->nr_running == 0)
9113 update_idle_cfs_rq_clock_pelt(cfs_rq);
9115 if (cfs_rq == &rq->cfs)
9119 /* Propagate pending load changes to the parent, if any: */
9120 se = cfs_rq->tg->se[cpu];
9121 if (se && !skip_blocked_update(se))
9122 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9125 * There can be a lot of idle CPU cgroups. Don't let fully
9126 * decayed cfs_rqs linger on the list.
9128 if (cfs_rq_is_decayed(cfs_rq))
9129 list_del_leaf_cfs_rq(cfs_rq);
9131 /* Don't need periodic decay once load/util_avg are null */
9132 if (cfs_rq_has_blocked(cfs_rq))
9140 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9141 * This needs to be done in a top-down fashion because the load of a child
9142 * group is a fraction of its parents load.
9144 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9146 struct rq *rq = rq_of(cfs_rq);
9147 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9148 unsigned long now = jiffies;
9151 if (cfs_rq->last_h_load_update == now)
9154 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9155 for_each_sched_entity(se) {
9156 cfs_rq = cfs_rq_of(se);
9157 WRITE_ONCE(cfs_rq->h_load_next, se);
9158 if (cfs_rq->last_h_load_update == now)
9163 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9164 cfs_rq->last_h_load_update = now;
9167 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9168 load = cfs_rq->h_load;
9169 load = div64_ul(load * se->avg.load_avg,
9170 cfs_rq_load_avg(cfs_rq) + 1);
9171 cfs_rq = group_cfs_rq(se);
9172 cfs_rq->h_load = load;
9173 cfs_rq->last_h_load_update = now;
9177 static unsigned long task_h_load(struct task_struct *p)
9179 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9181 update_cfs_rq_h_load(cfs_rq);
9182 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9183 cfs_rq_load_avg(cfs_rq) + 1);
9186 static bool __update_blocked_fair(struct rq *rq, bool *done)
9188 struct cfs_rq *cfs_rq = &rq->cfs;
9191 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9192 if (cfs_rq_has_blocked(cfs_rq))
9198 static unsigned long task_h_load(struct task_struct *p)
9200 return p->se.avg.load_avg;
9204 static void update_blocked_averages(int cpu)
9206 bool decayed = false, done = true;
9207 struct rq *rq = cpu_rq(cpu);
9210 rq_lock_irqsave(rq, &rf);
9211 update_blocked_load_tick(rq);
9212 update_rq_clock(rq);
9214 decayed |= __update_blocked_others(rq, &done);
9215 decayed |= __update_blocked_fair(rq, &done);
9217 update_blocked_load_status(rq, !done);
9219 cpufreq_update_util(rq, 0);
9220 rq_unlock_irqrestore(rq, &rf);
9223 /********** Helpers for find_busiest_group ************************/
9226 * sg_lb_stats - stats of a sched_group required for load_balancing
9228 struct sg_lb_stats {
9229 unsigned long avg_load; /*Avg load across the CPUs of the group */
9230 unsigned long group_load; /* Total load over the CPUs of the group */
9231 unsigned long group_capacity;
9232 unsigned long group_util; /* Total utilization over the CPUs of the group */
9233 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9234 unsigned int sum_nr_running; /* Nr of tasks running in the group */
9235 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9236 unsigned int idle_cpus;
9237 unsigned int group_weight;
9238 enum group_type group_type;
9239 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9240 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9241 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9242 #ifdef CONFIG_NUMA_BALANCING
9243 unsigned int nr_numa_running;
9244 unsigned int nr_preferred_running;
9249 * sd_lb_stats - Structure to store the statistics of a sched_domain
9250 * during load balancing.
9252 struct sd_lb_stats {
9253 struct sched_group *busiest; /* Busiest group in this sd */
9254 struct sched_group *local; /* Local group in this sd */
9255 unsigned long total_load; /* Total load of all groups in sd */
9256 unsigned long total_capacity; /* Total capacity of all groups in sd */
9257 unsigned long avg_load; /* Average load across all groups in sd */
9258 unsigned int prefer_sibling; /* tasks should go to sibling first */
9260 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9261 struct sg_lb_stats local_stat; /* Statistics of the local group */
9264 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9267 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9268 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9269 * We must however set busiest_stat::group_type and
9270 * busiest_stat::idle_cpus to the worst busiest group because
9271 * update_sd_pick_busiest() reads these before assignment.
9273 *sds = (struct sd_lb_stats){
9277 .total_capacity = 0UL,
9279 .idle_cpus = UINT_MAX,
9280 .group_type = group_has_spare,
9285 static unsigned long scale_rt_capacity(int cpu)
9287 struct rq *rq = cpu_rq(cpu);
9288 unsigned long max = arch_scale_cpu_capacity(cpu);
9289 unsigned long used, free;
9292 irq = cpu_util_irq(rq);
9294 if (unlikely(irq >= max))
9298 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9299 * (running and not running) with weights 0 and 1024 respectively.
9300 * avg_thermal.load_avg tracks thermal pressure and the weighted
9301 * average uses the actual delta max capacity(load).
9303 used = READ_ONCE(rq->avg_rt.util_avg);
9304 used += READ_ONCE(rq->avg_dl.util_avg);
9305 used += thermal_load_avg(rq);
9307 if (unlikely(used >= max))
9312 return scale_irq_capacity(free, irq, max);
9315 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9317 unsigned long capacity = scale_rt_capacity(cpu);
9318 struct sched_group *sdg = sd->groups;
9323 cpu_rq(cpu)->cpu_capacity = capacity;
9324 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9326 sdg->sgc->capacity = capacity;
9327 sdg->sgc->min_capacity = capacity;
9328 sdg->sgc->max_capacity = capacity;
9331 void update_group_capacity(struct sched_domain *sd, int cpu)
9333 struct sched_domain *child = sd->child;
9334 struct sched_group *group, *sdg = sd->groups;
9335 unsigned long capacity, min_capacity, max_capacity;
9336 unsigned long interval;
9338 interval = msecs_to_jiffies(sd->balance_interval);
9339 interval = clamp(interval, 1UL, max_load_balance_interval);
9340 sdg->sgc->next_update = jiffies + interval;
9343 update_cpu_capacity(sd, cpu);
9348 min_capacity = ULONG_MAX;
9351 if (child->flags & SD_OVERLAP) {
9353 * SD_OVERLAP domains cannot assume that child groups
9354 * span the current group.
9357 for_each_cpu(cpu, sched_group_span(sdg)) {
9358 unsigned long cpu_cap = capacity_of(cpu);
9360 capacity += cpu_cap;
9361 min_capacity = min(cpu_cap, min_capacity);
9362 max_capacity = max(cpu_cap, max_capacity);
9366 * !SD_OVERLAP domains can assume that child groups
9367 * span the current group.
9370 group = child->groups;
9372 struct sched_group_capacity *sgc = group->sgc;
9374 capacity += sgc->capacity;
9375 min_capacity = min(sgc->min_capacity, min_capacity);
9376 max_capacity = max(sgc->max_capacity, max_capacity);
9377 group = group->next;
9378 } while (group != child->groups);
9381 sdg->sgc->capacity = capacity;
9382 sdg->sgc->min_capacity = min_capacity;
9383 sdg->sgc->max_capacity = max_capacity;
9387 * Check whether the capacity of the rq has been noticeably reduced by side
9388 * activity. The imbalance_pct is used for the threshold.
9389 * Return true is the capacity is reduced
9392 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9394 return ((rq->cpu_capacity * sd->imbalance_pct) <
9395 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
9399 * Check whether a rq has a misfit task and if it looks like we can actually
9400 * help that task: we can migrate the task to a CPU of higher capacity, or
9401 * the task's current CPU is heavily pressured.
9403 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9405 return rq->misfit_task_load &&
9406 (arch_scale_cpu_capacity(rq->cpu) < rq->rd->max_cpu_capacity ||
9407 check_cpu_capacity(rq, sd));
9411 * Group imbalance indicates (and tries to solve) the problem where balancing
9412 * groups is inadequate due to ->cpus_ptr constraints.
9414 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9415 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9418 * { 0 1 2 3 } { 4 5 6 7 }
9421 * If we were to balance group-wise we'd place two tasks in the first group and
9422 * two tasks in the second group. Clearly this is undesired as it will overload
9423 * cpu 3 and leave one of the CPUs in the second group unused.
9425 * The current solution to this issue is detecting the skew in the first group
9426 * by noticing the lower domain failed to reach balance and had difficulty
9427 * moving tasks due to affinity constraints.
9429 * When this is so detected; this group becomes a candidate for busiest; see
9430 * update_sd_pick_busiest(). And calculate_imbalance() and
9431 * find_busiest_group() avoid some of the usual balance conditions to allow it
9432 * to create an effective group imbalance.
9434 * This is a somewhat tricky proposition since the next run might not find the
9435 * group imbalance and decide the groups need to be balanced again. A most
9436 * subtle and fragile situation.
9439 static inline int sg_imbalanced(struct sched_group *group)
9441 return group->sgc->imbalance;
9445 * group_has_capacity returns true if the group has spare capacity that could
9446 * be used by some tasks.
9447 * We consider that a group has spare capacity if the number of task is
9448 * smaller than the number of CPUs or if the utilization is lower than the
9449 * available capacity for CFS tasks.
9450 * For the latter, we use a threshold to stabilize the state, to take into
9451 * account the variance of the tasks' load and to return true if the available
9452 * capacity in meaningful for the load balancer.
9453 * As an example, an available capacity of 1% can appear but it doesn't make
9454 * any benefit for the load balance.
9457 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9459 if (sgs->sum_nr_running < sgs->group_weight)
9462 if ((sgs->group_capacity * imbalance_pct) <
9463 (sgs->group_runnable * 100))
9466 if ((sgs->group_capacity * 100) >
9467 (sgs->group_util * imbalance_pct))
9474 * group_is_overloaded returns true if the group has more tasks than it can
9476 * group_is_overloaded is not equals to !group_has_capacity because a group
9477 * with the exact right number of tasks, has no more spare capacity but is not
9478 * overloaded so both group_has_capacity and group_is_overloaded return
9482 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9484 if (sgs->sum_nr_running <= sgs->group_weight)
9487 if ((sgs->group_capacity * 100) <
9488 (sgs->group_util * imbalance_pct))
9491 if ((sgs->group_capacity * imbalance_pct) <
9492 (sgs->group_runnable * 100))
9499 group_type group_classify(unsigned int imbalance_pct,
9500 struct sched_group *group,
9501 struct sg_lb_stats *sgs)
9503 if (group_is_overloaded(imbalance_pct, sgs))
9504 return group_overloaded;
9506 if (sg_imbalanced(group))
9507 return group_imbalanced;
9509 if (sgs->group_asym_packing)
9510 return group_asym_packing;
9512 if (sgs->group_smt_balance)
9513 return group_smt_balance;
9515 if (sgs->group_misfit_task_load)
9516 return group_misfit_task;
9518 if (!group_has_capacity(imbalance_pct, sgs))
9519 return group_fully_busy;
9521 return group_has_spare;
9525 * sched_use_asym_prio - Check whether asym_packing priority must be used
9526 * @sd: The scheduling domain of the load balancing
9529 * Always use CPU priority when balancing load between SMT siblings. When
9530 * balancing load between cores, it is not sufficient that @cpu is idle. Only
9531 * use CPU priority if the whole core is idle.
9533 * Returns: True if the priority of @cpu must be followed. False otherwise.
9535 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9537 if (!sched_smt_active())
9540 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9544 * sched_asym - Check if the destination CPU can do asym_packing load balance
9545 * @env: The load balancing environment
9546 * @sds: Load-balancing data with statistics of the local group
9547 * @sgs: Load-balancing statistics of the candidate busiest group
9548 * @group: The candidate busiest group
9550 * @env::dst_cpu can do asym_packing if it has higher priority than the
9551 * preferred CPU of @group.
9553 * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9554 * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9555 * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9556 * imbalances in the number of CPUS are dealt with in find_busiest_group().
9558 * If we are balancing load within an SMT core, or at PKG domain level, always
9561 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9565 sched_asym(struct lb_env *env, struct sd_lb_stats *sds, struct sg_lb_stats *sgs,
9566 struct sched_group *group)
9568 /* Ensure that the whole local core is idle, if applicable. */
9569 if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9573 * CPU priorities does not make sense for SMT cores with more than one
9576 if (group->flags & SD_SHARE_CPUCAPACITY) {
9577 if (sgs->group_weight - sgs->idle_cpus != 1)
9581 return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9584 /* One group has more than one SMT CPU while the other group does not */
9585 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9586 struct sched_group *sg2)
9591 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9592 (sg2->flags & SD_SHARE_CPUCAPACITY);
9595 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9596 struct sched_group *group)
9598 if (env->idle == CPU_NOT_IDLE)
9602 * For SMT source group, it is better to move a task
9603 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9604 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9607 if (group->flags & SD_SHARE_CPUCAPACITY &&
9608 sgs->sum_h_nr_running > 1)
9614 static inline long sibling_imbalance(struct lb_env *env,
9615 struct sd_lb_stats *sds,
9616 struct sg_lb_stats *busiest,
9617 struct sg_lb_stats *local)
9619 int ncores_busiest, ncores_local;
9622 if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9625 ncores_busiest = sds->busiest->cores;
9626 ncores_local = sds->local->cores;
9628 if (ncores_busiest == ncores_local) {
9629 imbalance = busiest->sum_nr_running;
9630 lsub_positive(&imbalance, local->sum_nr_running);
9634 /* Balance such that nr_running/ncores ratio are same on both groups */
9635 imbalance = ncores_local * busiest->sum_nr_running;
9636 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9637 /* Normalize imbalance and do rounding on normalization */
9638 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9639 imbalance /= ncores_local + ncores_busiest;
9641 /* Take advantage of resource in an empty sched group */
9642 if (imbalance <= 1 && local->sum_nr_running == 0 &&
9643 busiest->sum_nr_running > 1)
9650 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9653 * When there is more than 1 task, the group_overloaded case already
9654 * takes care of cpu with reduced capacity
9656 if (rq->cfs.h_nr_running != 1)
9659 return check_cpu_capacity(rq, sd);
9663 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9664 * @env: The load balancing environment.
9665 * @sds: Load-balancing data with statistics of the local group.
9666 * @group: sched_group whose statistics are to be updated.
9667 * @sgs: variable to hold the statistics for this group.
9668 * @sg_status: Holds flag indicating the status of the sched_group
9670 static inline void update_sg_lb_stats(struct lb_env *env,
9671 struct sd_lb_stats *sds,
9672 struct sched_group *group,
9673 struct sg_lb_stats *sgs,
9676 int i, nr_running, local_group;
9678 memset(sgs, 0, sizeof(*sgs));
9680 local_group = group == sds->local;
9682 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9683 struct rq *rq = cpu_rq(i);
9684 unsigned long load = cpu_load(rq);
9686 sgs->group_load += load;
9687 sgs->group_util += cpu_util_cfs(i);
9688 sgs->group_runnable += cpu_runnable(rq);
9689 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9691 nr_running = rq->nr_running;
9692 sgs->sum_nr_running += nr_running;
9695 *sg_status |= SG_OVERLOAD;
9697 if (cpu_overutilized(i))
9698 *sg_status |= SG_OVERUTILIZED;
9700 #ifdef CONFIG_NUMA_BALANCING
9701 sgs->nr_numa_running += rq->nr_numa_running;
9702 sgs->nr_preferred_running += rq->nr_preferred_running;
9705 * No need to call idle_cpu() if nr_running is not 0
9707 if (!nr_running && idle_cpu(i)) {
9709 /* Idle cpu can't have misfit task */
9716 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9717 /* Check for a misfit task on the cpu */
9718 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9719 sgs->group_misfit_task_load = rq->misfit_task_load;
9720 *sg_status |= SG_OVERLOAD;
9722 } else if ((env->idle != CPU_NOT_IDLE) &&
9723 sched_reduced_capacity(rq, env->sd)) {
9724 /* Check for a task running on a CPU with reduced capacity */
9725 if (sgs->group_misfit_task_load < load)
9726 sgs->group_misfit_task_load = load;
9730 sgs->group_capacity = group->sgc->capacity;
9732 sgs->group_weight = group->group_weight;
9734 /* Check if dst CPU is idle and preferred to this group */
9735 if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9736 env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9737 sched_asym(env, sds, sgs, group)) {
9738 sgs->group_asym_packing = 1;
9741 /* Check for loaded SMT group to be balanced to dst CPU */
9742 if (!local_group && smt_balance(env, sgs, group))
9743 sgs->group_smt_balance = 1;
9745 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
9747 /* Computing avg_load makes sense only when group is overloaded */
9748 if (sgs->group_type == group_overloaded)
9749 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9750 sgs->group_capacity;
9754 * update_sd_pick_busiest - return 1 on busiest group
9755 * @env: The load balancing environment.
9756 * @sds: sched_domain statistics
9757 * @sg: sched_group candidate to be checked for being the busiest
9758 * @sgs: sched_group statistics
9760 * Determine if @sg is a busier group than the previously selected
9763 * Return: %true if @sg is a busier group than the previously selected
9764 * busiest group. %false otherwise.
9766 static bool update_sd_pick_busiest(struct lb_env *env,
9767 struct sd_lb_stats *sds,
9768 struct sched_group *sg,
9769 struct sg_lb_stats *sgs)
9771 struct sg_lb_stats *busiest = &sds->busiest_stat;
9773 /* Make sure that there is at least one task to pull */
9774 if (!sgs->sum_h_nr_running)
9778 * Don't try to pull misfit tasks we can't help.
9779 * We can use max_capacity here as reduction in capacity on some
9780 * CPUs in the group should either be possible to resolve
9781 * internally or be covered by avg_load imbalance (eventually).
9783 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9784 (sgs->group_type == group_misfit_task) &&
9785 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
9786 sds->local_stat.group_type != group_has_spare))
9789 if (sgs->group_type > busiest->group_type)
9792 if (sgs->group_type < busiest->group_type)
9796 * The candidate and the current busiest group are the same type of
9797 * group. Let check which one is the busiest according to the type.
9800 switch (sgs->group_type) {
9801 case group_overloaded:
9802 /* Select the overloaded group with highest avg_load. */
9803 if (sgs->avg_load <= busiest->avg_load)
9807 case group_imbalanced:
9809 * Select the 1st imbalanced group as we don't have any way to
9810 * choose one more than another.
9814 case group_asym_packing:
9815 /* Prefer to move from lowest priority CPU's work */
9816 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
9820 case group_misfit_task:
9822 * If we have more than one misfit sg go with the biggest
9825 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
9829 case group_smt_balance:
9831 * Check if we have spare CPUs on either SMT group to
9832 * choose has spare or fully busy handling.
9834 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
9839 case group_fully_busy:
9841 * Select the fully busy group with highest avg_load. In
9842 * theory, there is no need to pull task from such kind of
9843 * group because tasks have all compute capacity that they need
9844 * but we can still improve the overall throughput by reducing
9845 * contention when accessing shared HW resources.
9847 * XXX for now avg_load is not computed and always 0 so we
9848 * select the 1st one, except if @sg is composed of SMT
9852 if (sgs->avg_load < busiest->avg_load)
9855 if (sgs->avg_load == busiest->avg_load) {
9857 * SMT sched groups need more help than non-SMT groups.
9858 * If @sg happens to also be SMT, either choice is good.
9860 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
9866 case group_has_spare:
9868 * Do not pick sg with SMT CPUs over sg with pure CPUs,
9869 * as we do not want to pull task off SMT core with one task
9870 * and make the core idle.
9872 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
9873 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
9881 * Select not overloaded group with lowest number of idle cpus
9882 * and highest number of running tasks. We could also compare
9883 * the spare capacity which is more stable but it can end up
9884 * that the group has less spare capacity but finally more idle
9885 * CPUs which means less opportunity to pull tasks.
9887 if (sgs->idle_cpus > busiest->idle_cpus)
9889 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
9890 (sgs->sum_nr_running <= busiest->sum_nr_running))
9897 * Candidate sg has no more than one task per CPU and has higher
9898 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
9899 * throughput. Maximize throughput, power/energy consequences are not
9902 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9903 (sgs->group_type <= group_fully_busy) &&
9904 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
9910 #ifdef CONFIG_NUMA_BALANCING
9911 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9913 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
9915 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
9920 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9922 if (rq->nr_running > rq->nr_numa_running)
9924 if (rq->nr_running > rq->nr_preferred_running)
9929 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9934 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9938 #endif /* CONFIG_NUMA_BALANCING */
9944 * task_running_on_cpu - return 1 if @p is running on @cpu.
9947 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
9949 /* Task has no contribution or is new */
9950 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9953 if (task_on_rq_queued(p))
9960 * idle_cpu_without - would a given CPU be idle without p ?
9961 * @cpu: the processor on which idleness is tested.
9962 * @p: task which should be ignored.
9964 * Return: 1 if the CPU would be idle. 0 otherwise.
9966 static int idle_cpu_without(int cpu, struct task_struct *p)
9968 struct rq *rq = cpu_rq(cpu);
9970 if (rq->curr != rq->idle && rq->curr != p)
9974 * rq->nr_running can't be used but an updated version without the
9975 * impact of p on cpu must be used instead. The updated nr_running
9976 * be computed and tested before calling idle_cpu_without().
9980 if (rq->ttwu_pending)
9988 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
9989 * @sd: The sched_domain level to look for idlest group.
9990 * @group: sched_group whose statistics are to be updated.
9991 * @sgs: variable to hold the statistics for this group.
9992 * @p: The task for which we look for the idlest group/CPU.
9994 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
9995 struct sched_group *group,
9996 struct sg_lb_stats *sgs,
9997 struct task_struct *p)
10001 memset(sgs, 0, sizeof(*sgs));
10003 /* Assume that task can't fit any CPU of the group */
10004 if (sd->flags & SD_ASYM_CPUCAPACITY)
10005 sgs->group_misfit_task_load = 1;
10007 for_each_cpu(i, sched_group_span(group)) {
10008 struct rq *rq = cpu_rq(i);
10009 unsigned int local;
10011 sgs->group_load += cpu_load_without(rq, p);
10012 sgs->group_util += cpu_util_without(i, p);
10013 sgs->group_runnable += cpu_runnable_without(rq, p);
10014 local = task_running_on_cpu(i, p);
10015 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10017 nr_running = rq->nr_running - local;
10018 sgs->sum_nr_running += nr_running;
10021 * No need to call idle_cpu_without() if nr_running is not 0
10023 if (!nr_running && idle_cpu_without(i, p))
10026 /* Check if task fits in the CPU */
10027 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10028 sgs->group_misfit_task_load &&
10029 task_fits_cpu(p, i))
10030 sgs->group_misfit_task_load = 0;
10034 sgs->group_capacity = group->sgc->capacity;
10036 sgs->group_weight = group->group_weight;
10038 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10041 * Computing avg_load makes sense only when group is fully busy or
10044 if (sgs->group_type == group_fully_busy ||
10045 sgs->group_type == group_overloaded)
10046 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10047 sgs->group_capacity;
10050 static bool update_pick_idlest(struct sched_group *idlest,
10051 struct sg_lb_stats *idlest_sgs,
10052 struct sched_group *group,
10053 struct sg_lb_stats *sgs)
10055 if (sgs->group_type < idlest_sgs->group_type)
10058 if (sgs->group_type > idlest_sgs->group_type)
10062 * The candidate and the current idlest group are the same type of
10063 * group. Let check which one is the idlest according to the type.
10066 switch (sgs->group_type) {
10067 case group_overloaded:
10068 case group_fully_busy:
10069 /* Select the group with lowest avg_load. */
10070 if (idlest_sgs->avg_load <= sgs->avg_load)
10074 case group_imbalanced:
10075 case group_asym_packing:
10076 case group_smt_balance:
10077 /* Those types are not used in the slow wakeup path */
10080 case group_misfit_task:
10081 /* Select group with the highest max capacity */
10082 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10086 case group_has_spare:
10087 /* Select group with most idle CPUs */
10088 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10091 /* Select group with lowest group_util */
10092 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10093 idlest_sgs->group_util <= sgs->group_util)
10103 * find_idlest_group() finds and returns the least busy CPU group within the
10106 * Assumes p is allowed on at least one CPU in sd.
10108 static struct sched_group *
10109 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10111 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10112 struct sg_lb_stats local_sgs, tmp_sgs;
10113 struct sg_lb_stats *sgs;
10114 unsigned long imbalance;
10115 struct sg_lb_stats idlest_sgs = {
10116 .avg_load = UINT_MAX,
10117 .group_type = group_overloaded,
10123 /* Skip over this group if it has no CPUs allowed */
10124 if (!cpumask_intersects(sched_group_span(group),
10128 /* Skip over this group if no cookie matched */
10129 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10132 local_group = cpumask_test_cpu(this_cpu,
10133 sched_group_span(group));
10142 update_sg_wakeup_stats(sd, group, sgs, p);
10144 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10149 } while (group = group->next, group != sd->groups);
10152 /* There is no idlest group to push tasks to */
10156 /* The local group has been skipped because of CPU affinity */
10161 * If the local group is idler than the selected idlest group
10162 * don't try and push the task.
10164 if (local_sgs.group_type < idlest_sgs.group_type)
10168 * If the local group is busier than the selected idlest group
10169 * try and push the task.
10171 if (local_sgs.group_type > idlest_sgs.group_type)
10174 switch (local_sgs.group_type) {
10175 case group_overloaded:
10176 case group_fully_busy:
10178 /* Calculate allowed imbalance based on load */
10179 imbalance = scale_load_down(NICE_0_LOAD) *
10180 (sd->imbalance_pct-100) / 100;
10183 * When comparing groups across NUMA domains, it's possible for
10184 * the local domain to be very lightly loaded relative to the
10185 * remote domains but "imbalance" skews the comparison making
10186 * remote CPUs look much more favourable. When considering
10187 * cross-domain, add imbalance to the load on the remote node
10188 * and consider staying local.
10191 if ((sd->flags & SD_NUMA) &&
10192 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10196 * If the local group is less loaded than the selected
10197 * idlest group don't try and push any tasks.
10199 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10202 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10206 case group_imbalanced:
10207 case group_asym_packing:
10208 case group_smt_balance:
10209 /* Those type are not used in the slow wakeup path */
10212 case group_misfit_task:
10213 /* Select group with the highest max capacity */
10214 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10218 case group_has_spare:
10220 if (sd->flags & SD_NUMA) {
10221 int imb_numa_nr = sd->imb_numa_nr;
10222 #ifdef CONFIG_NUMA_BALANCING
10225 * If there is spare capacity at NUMA, try to select
10226 * the preferred node
10228 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10231 idlest_cpu = cpumask_first(sched_group_span(idlest));
10232 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10234 #endif /* CONFIG_NUMA_BALANCING */
10236 * Otherwise, keep the task close to the wakeup source
10237 * and improve locality if the number of running tasks
10238 * would remain below threshold where an imbalance is
10239 * allowed while accounting for the possibility the
10240 * task is pinned to a subset of CPUs. If there is a
10241 * real need of migration, periodic load balance will
10244 if (p->nr_cpus_allowed != NR_CPUS) {
10245 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10247 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10248 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10251 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10252 if (!adjust_numa_imbalance(imbalance,
10253 local_sgs.sum_nr_running + 1,
10258 #endif /* CONFIG_NUMA */
10261 * Select group with highest number of idle CPUs. We could also
10262 * compare the utilization which is more stable but it can end
10263 * up that the group has less spare capacity but finally more
10264 * idle CPUs which means more opportunity to run task.
10266 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10274 static void update_idle_cpu_scan(struct lb_env *env,
10275 unsigned long sum_util)
10277 struct sched_domain_shared *sd_share;
10278 int llc_weight, pct;
10281 * Update the number of CPUs to scan in LLC domain, which could
10282 * be used as a hint in select_idle_cpu(). The update of sd_share
10283 * could be expensive because it is within a shared cache line.
10284 * So the write of this hint only occurs during periodic load
10285 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10286 * can fire way more frequently than the former.
10288 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10291 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10292 if (env->sd->span_weight != llc_weight)
10295 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10300 * The number of CPUs to search drops as sum_util increases, when
10301 * sum_util hits 85% or above, the scan stops.
10302 * The reason to choose 85% as the threshold is because this is the
10303 * imbalance_pct(117) when a LLC sched group is overloaded.
10305 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10306 * and y'= y / SCHED_CAPACITY_SCALE
10308 * x is the ratio of sum_util compared to the CPU capacity:
10309 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10310 * y' is the ratio of CPUs to be scanned in the LLC domain,
10311 * and the number of CPUs to scan is calculated by:
10313 * nr_scan = llc_weight * y' [2]
10315 * When x hits the threshold of overloaded, AKA, when
10316 * x = 100 / pct, y drops to 0. According to [1],
10317 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10319 * Scale x by SCHED_CAPACITY_SCALE:
10320 * x' = sum_util / llc_weight; [3]
10322 * and finally [1] becomes:
10323 * y = SCHED_CAPACITY_SCALE -
10324 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10329 do_div(x, llc_weight);
10332 pct = env->sd->imbalance_pct;
10333 tmp = x * x * pct * pct;
10334 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10335 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10336 y = SCHED_CAPACITY_SCALE - tmp;
10340 do_div(y, SCHED_CAPACITY_SCALE);
10341 if ((int)y != sd_share->nr_idle_scan)
10342 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10346 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10347 * @env: The load balancing environment.
10348 * @sds: variable to hold the statistics for this sched_domain.
10351 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10353 struct sched_group *sg = env->sd->groups;
10354 struct sg_lb_stats *local = &sds->local_stat;
10355 struct sg_lb_stats tmp_sgs;
10356 unsigned long sum_util = 0;
10360 struct sg_lb_stats *sgs = &tmp_sgs;
10363 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10368 if (env->idle != CPU_NEWLY_IDLE ||
10369 time_after_eq(jiffies, sg->sgc->next_update))
10370 update_group_capacity(env->sd, env->dst_cpu);
10373 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10379 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10381 sds->busiest_stat = *sgs;
10385 /* Now, start updating sd_lb_stats */
10386 sds->total_load += sgs->group_load;
10387 sds->total_capacity += sgs->group_capacity;
10389 sum_util += sgs->group_util;
10391 } while (sg != env->sd->groups);
10394 * Indicate that the child domain of the busiest group prefers tasks
10395 * go to a child's sibling domains first. NB the flags of a sched group
10396 * are those of the child domain.
10399 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10402 if (env->sd->flags & SD_NUMA)
10403 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10405 if (!env->sd->parent) {
10406 struct root_domain *rd = env->dst_rq->rd;
10408 /* update overload indicator if we are at root domain */
10409 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10411 /* Update over-utilization (tipping point, U >= 0) indicator */
10412 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10413 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10414 } else if (sg_status & SG_OVERUTILIZED) {
10415 struct root_domain *rd = env->dst_rq->rd;
10417 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10418 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10421 update_idle_cpu_scan(env, sum_util);
10425 * calculate_imbalance - Calculate the amount of imbalance present within the
10426 * groups of a given sched_domain during load balance.
10427 * @env: load balance environment
10428 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10430 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10432 struct sg_lb_stats *local, *busiest;
10434 local = &sds->local_stat;
10435 busiest = &sds->busiest_stat;
10437 if (busiest->group_type == group_misfit_task) {
10438 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10439 /* Set imbalance to allow misfit tasks to be balanced. */
10440 env->migration_type = migrate_misfit;
10441 env->imbalance = 1;
10444 * Set load imbalance to allow moving task from cpu
10445 * with reduced capacity.
10447 env->migration_type = migrate_load;
10448 env->imbalance = busiest->group_misfit_task_load;
10453 if (busiest->group_type == group_asym_packing) {
10455 * In case of asym capacity, we will try to migrate all load to
10456 * the preferred CPU.
10458 env->migration_type = migrate_task;
10459 env->imbalance = busiest->sum_h_nr_running;
10463 if (busiest->group_type == group_smt_balance) {
10464 /* Reduce number of tasks sharing CPU capacity */
10465 env->migration_type = migrate_task;
10466 env->imbalance = 1;
10470 if (busiest->group_type == group_imbalanced) {
10472 * In the group_imb case we cannot rely on group-wide averages
10473 * to ensure CPU-load equilibrium, try to move any task to fix
10474 * the imbalance. The next load balance will take care of
10475 * balancing back the system.
10477 env->migration_type = migrate_task;
10478 env->imbalance = 1;
10483 * Try to use spare capacity of local group without overloading it or
10484 * emptying busiest.
10486 if (local->group_type == group_has_spare) {
10487 if ((busiest->group_type > group_fully_busy) &&
10488 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10490 * If busiest is overloaded, try to fill spare
10491 * capacity. This might end up creating spare capacity
10492 * in busiest or busiest still being overloaded but
10493 * there is no simple way to directly compute the
10494 * amount of load to migrate in order to balance the
10497 env->migration_type = migrate_util;
10498 env->imbalance = max(local->group_capacity, local->group_util) -
10502 * In some cases, the group's utilization is max or even
10503 * higher than capacity because of migrations but the
10504 * local CPU is (newly) idle. There is at least one
10505 * waiting task in this overloaded busiest group. Let's
10508 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10509 env->migration_type = migrate_task;
10510 env->imbalance = 1;
10516 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10518 * When prefer sibling, evenly spread running tasks on
10521 env->migration_type = migrate_task;
10522 env->imbalance = sibling_imbalance(env, sds, busiest, local);
10526 * If there is no overload, we just want to even the number of
10529 env->migration_type = migrate_task;
10530 env->imbalance = max_t(long, 0,
10531 (local->idle_cpus - busiest->idle_cpus));
10535 /* Consider allowing a small imbalance between NUMA groups */
10536 if (env->sd->flags & SD_NUMA) {
10537 env->imbalance = adjust_numa_imbalance(env->imbalance,
10538 local->sum_nr_running + 1,
10539 env->sd->imb_numa_nr);
10543 /* Number of tasks to move to restore balance */
10544 env->imbalance >>= 1;
10550 * Local is fully busy but has to take more load to relieve the
10553 if (local->group_type < group_overloaded) {
10555 * Local will become overloaded so the avg_load metrics are
10559 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10560 local->group_capacity;
10563 * If the local group is more loaded than the selected
10564 * busiest group don't try to pull any tasks.
10566 if (local->avg_load >= busiest->avg_load) {
10567 env->imbalance = 0;
10571 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10572 sds->total_capacity;
10575 * If the local group is more loaded than the average system
10576 * load, don't try to pull any tasks.
10578 if (local->avg_load >= sds->avg_load) {
10579 env->imbalance = 0;
10586 * Both group are or will become overloaded and we're trying to get all
10587 * the CPUs to the average_load, so we don't want to push ourselves
10588 * above the average load, nor do we wish to reduce the max loaded CPU
10589 * below the average load. At the same time, we also don't want to
10590 * reduce the group load below the group capacity. Thus we look for
10591 * the minimum possible imbalance.
10593 env->migration_type = migrate_load;
10594 env->imbalance = min(
10595 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10596 (sds->avg_load - local->avg_load) * local->group_capacity
10597 ) / SCHED_CAPACITY_SCALE;
10600 /******* find_busiest_group() helpers end here *********************/
10603 * Decision matrix according to the local and busiest group type:
10605 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10606 * has_spare nr_idle balanced N/A N/A balanced balanced
10607 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
10608 * misfit_task force N/A N/A N/A N/A N/A
10609 * asym_packing force force N/A N/A force force
10610 * imbalanced force force N/A N/A force force
10611 * overloaded force force N/A N/A force avg_load
10613 * N/A : Not Applicable because already filtered while updating
10615 * balanced : The system is balanced for these 2 groups.
10616 * force : Calculate the imbalance as load migration is probably needed.
10617 * avg_load : Only if imbalance is significant enough.
10618 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
10619 * different in groups.
10623 * find_busiest_group - Returns the busiest group within the sched_domain
10624 * if there is an imbalance.
10625 * @env: The load balancing environment.
10627 * Also calculates the amount of runnable load which should be moved
10628 * to restore balance.
10630 * Return: - The busiest group if imbalance exists.
10632 static struct sched_group *find_busiest_group(struct lb_env *env)
10634 struct sg_lb_stats *local, *busiest;
10635 struct sd_lb_stats sds;
10637 init_sd_lb_stats(&sds);
10640 * Compute the various statistics relevant for load balancing at
10643 update_sd_lb_stats(env, &sds);
10645 /* There is no busy sibling group to pull tasks from */
10649 busiest = &sds.busiest_stat;
10651 /* Misfit tasks should be dealt with regardless of the avg load */
10652 if (busiest->group_type == group_misfit_task)
10653 goto force_balance;
10655 if (sched_energy_enabled()) {
10656 struct root_domain *rd = env->dst_rq->rd;
10658 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10662 /* ASYM feature bypasses nice load balance check */
10663 if (busiest->group_type == group_asym_packing)
10664 goto force_balance;
10667 * If the busiest group is imbalanced the below checks don't
10668 * work because they assume all things are equal, which typically
10669 * isn't true due to cpus_ptr constraints and the like.
10671 if (busiest->group_type == group_imbalanced)
10672 goto force_balance;
10674 local = &sds.local_stat;
10676 * If the local group is busier than the selected busiest group
10677 * don't try and pull any tasks.
10679 if (local->group_type > busiest->group_type)
10683 * When groups are overloaded, use the avg_load to ensure fairness
10686 if (local->group_type == group_overloaded) {
10688 * If the local group is more loaded than the selected
10689 * busiest group don't try to pull any tasks.
10691 if (local->avg_load >= busiest->avg_load)
10694 /* XXX broken for overlapping NUMA groups */
10695 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10696 sds.total_capacity;
10699 * Don't pull any tasks if this group is already above the
10700 * domain average load.
10702 if (local->avg_load >= sds.avg_load)
10706 * If the busiest group is more loaded, use imbalance_pct to be
10709 if (100 * busiest->avg_load <=
10710 env->sd->imbalance_pct * local->avg_load)
10715 * Try to move all excess tasks to a sibling domain of the busiest
10716 * group's child domain.
10718 if (sds.prefer_sibling && local->group_type == group_has_spare &&
10719 sibling_imbalance(env, &sds, busiest, local) > 1)
10720 goto force_balance;
10722 if (busiest->group_type != group_overloaded) {
10723 if (env->idle == CPU_NOT_IDLE) {
10725 * If the busiest group is not overloaded (and as a
10726 * result the local one too) but this CPU is already
10727 * busy, let another idle CPU try to pull task.
10732 if (busiest->group_type == group_smt_balance &&
10733 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10734 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10735 goto force_balance;
10738 if (busiest->group_weight > 1 &&
10739 local->idle_cpus <= (busiest->idle_cpus + 1)) {
10741 * If the busiest group is not overloaded
10742 * and there is no imbalance between this and busiest
10743 * group wrt idle CPUs, it is balanced. The imbalance
10744 * becomes significant if the diff is greater than 1
10745 * otherwise we might end up to just move the imbalance
10746 * on another group. Of course this applies only if
10747 * there is more than 1 CPU per group.
10752 if (busiest->sum_h_nr_running == 1) {
10754 * busiest doesn't have any tasks waiting to run
10761 /* Looks like there is an imbalance. Compute it */
10762 calculate_imbalance(env, &sds);
10763 return env->imbalance ? sds.busiest : NULL;
10766 env->imbalance = 0;
10771 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
10773 static struct rq *find_busiest_queue(struct lb_env *env,
10774 struct sched_group *group)
10776 struct rq *busiest = NULL, *rq;
10777 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
10778 unsigned int busiest_nr = 0;
10781 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10782 unsigned long capacity, load, util;
10783 unsigned int nr_running;
10787 rt = fbq_classify_rq(rq);
10790 * We classify groups/runqueues into three groups:
10791 * - regular: there are !numa tasks
10792 * - remote: there are numa tasks that run on the 'wrong' node
10793 * - all: there is no distinction
10795 * In order to avoid migrating ideally placed numa tasks,
10796 * ignore those when there's better options.
10798 * If we ignore the actual busiest queue to migrate another
10799 * task, the next balance pass can still reduce the busiest
10800 * queue by moving tasks around inside the node.
10802 * If we cannot move enough load due to this classification
10803 * the next pass will adjust the group classification and
10804 * allow migration of more tasks.
10806 * Both cases only affect the total convergence complexity.
10808 if (rt > env->fbq_type)
10811 nr_running = rq->cfs.h_nr_running;
10815 capacity = capacity_of(i);
10818 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
10819 * eventually lead to active_balancing high->low capacity.
10820 * Higher per-CPU capacity is considered better than balancing
10823 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
10824 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
10829 * Make sure we only pull tasks from a CPU of lower priority
10830 * when balancing between SMT siblings.
10832 * If balancing between cores, let lower priority CPUs help
10833 * SMT cores with more than one busy sibling.
10835 if ((env->sd->flags & SD_ASYM_PACKING) &&
10836 sched_use_asym_prio(env->sd, i) &&
10837 sched_asym_prefer(i, env->dst_cpu) &&
10841 switch (env->migration_type) {
10844 * When comparing with load imbalance, use cpu_load()
10845 * which is not scaled with the CPU capacity.
10847 load = cpu_load(rq);
10849 if (nr_running == 1 && load > env->imbalance &&
10850 !check_cpu_capacity(rq, env->sd))
10854 * For the load comparisons with the other CPUs,
10855 * consider the cpu_load() scaled with the CPU
10856 * capacity, so that the load can be moved away
10857 * from the CPU that is potentially running at a
10860 * Thus we're looking for max(load_i / capacity_i),
10861 * crosswise multiplication to rid ourselves of the
10862 * division works out to:
10863 * load_i * capacity_j > load_j * capacity_i;
10864 * where j is our previous maximum.
10866 if (load * busiest_capacity > busiest_load * capacity) {
10867 busiest_load = load;
10868 busiest_capacity = capacity;
10874 util = cpu_util_cfs_boost(i);
10877 * Don't try to pull utilization from a CPU with one
10878 * running task. Whatever its utilization, we will fail
10881 if (nr_running <= 1)
10884 if (busiest_util < util) {
10885 busiest_util = util;
10891 if (busiest_nr < nr_running) {
10892 busiest_nr = nr_running;
10897 case migrate_misfit:
10899 * For ASYM_CPUCAPACITY domains with misfit tasks we
10900 * simply seek the "biggest" misfit task.
10902 if (rq->misfit_task_load > busiest_load) {
10903 busiest_load = rq->misfit_task_load;
10916 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
10917 * so long as it is large enough.
10919 #define MAX_PINNED_INTERVAL 512
10922 asym_active_balance(struct lb_env *env)
10925 * ASYM_PACKING needs to force migrate tasks from busy but lower
10926 * priority CPUs in order to pack all tasks in the highest priority
10927 * CPUs. When done between cores, do it only if the whole core if the
10928 * whole core is idle.
10930 * If @env::src_cpu is an SMT core with busy siblings, let
10931 * the lower priority @env::dst_cpu help it. Do not follow
10934 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
10935 sched_use_asym_prio(env->sd, env->dst_cpu) &&
10936 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
10937 !sched_use_asym_prio(env->sd, env->src_cpu));
10941 imbalanced_active_balance(struct lb_env *env)
10943 struct sched_domain *sd = env->sd;
10946 * The imbalanced case includes the case of pinned tasks preventing a fair
10947 * distribution of the load on the system but also the even distribution of the
10948 * threads on a system with spare capacity
10950 if ((env->migration_type == migrate_task) &&
10951 (sd->nr_balance_failed > sd->cache_nice_tries+2))
10957 static int need_active_balance(struct lb_env *env)
10959 struct sched_domain *sd = env->sd;
10961 if (asym_active_balance(env))
10964 if (imbalanced_active_balance(env))
10968 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
10969 * It's worth migrating the task if the src_cpu's capacity is reduced
10970 * because of other sched_class or IRQs if more capacity stays
10971 * available on dst_cpu.
10973 if ((env->idle != CPU_NOT_IDLE) &&
10974 (env->src_rq->cfs.h_nr_running == 1)) {
10975 if ((check_cpu_capacity(env->src_rq, sd)) &&
10976 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
10980 if (env->migration_type == migrate_misfit)
10986 static int active_load_balance_cpu_stop(void *data);
10988 static int should_we_balance(struct lb_env *env)
10990 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
10991 struct sched_group *sg = env->sd->groups;
10992 int cpu, idle_smt = -1;
10995 * Ensure the balancing environment is consistent; can happen
10996 * when the softirq triggers 'during' hotplug.
10998 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11002 * In the newly idle case, we will allow all the CPUs
11003 * to do the newly idle load balance.
11005 * However, we bail out if we already have tasks or a wakeup pending,
11006 * to optimize wakeup latency.
11008 if (env->idle == CPU_NEWLY_IDLE) {
11009 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11014 cpumask_copy(swb_cpus, group_balance_mask(sg));
11015 /* Try to find first idle CPU */
11016 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11017 if (!idle_cpu(cpu))
11021 * Don't balance to idle SMT in busy core right away when
11022 * balancing cores, but remember the first idle SMT CPU for
11023 * later consideration. Find CPU on an idle core first.
11025 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11026 if (idle_smt == -1)
11029 * If the core is not idle, and first SMT sibling which is
11030 * idle has been found, then its not needed to check other
11031 * SMT siblings for idleness:
11033 #ifdef CONFIG_SCHED_SMT
11034 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11039 /* Are we the first idle CPU? */
11040 return cpu == env->dst_cpu;
11043 if (idle_smt == env->dst_cpu)
11046 /* Are we the first CPU of this group ? */
11047 return group_balance_cpu(sg) == env->dst_cpu;
11051 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11052 * tasks if there is an imbalance.
11054 static int load_balance(int this_cpu, struct rq *this_rq,
11055 struct sched_domain *sd, enum cpu_idle_type idle,
11056 int *continue_balancing)
11058 int ld_moved, cur_ld_moved, active_balance = 0;
11059 struct sched_domain *sd_parent = sd->parent;
11060 struct sched_group *group;
11061 struct rq *busiest;
11062 struct rq_flags rf;
11063 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11064 struct lb_env env = {
11066 .dst_cpu = this_cpu,
11068 .dst_grpmask = group_balance_mask(sd->groups),
11070 .loop_break = SCHED_NR_MIGRATE_BREAK,
11073 .tasks = LIST_HEAD_INIT(env.tasks),
11076 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11078 schedstat_inc(sd->lb_count[idle]);
11081 if (!should_we_balance(&env)) {
11082 *continue_balancing = 0;
11086 group = find_busiest_group(&env);
11088 schedstat_inc(sd->lb_nobusyg[idle]);
11092 busiest = find_busiest_queue(&env, group);
11094 schedstat_inc(sd->lb_nobusyq[idle]);
11098 WARN_ON_ONCE(busiest == env.dst_rq);
11100 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11102 env.src_cpu = busiest->cpu;
11103 env.src_rq = busiest;
11106 /* Clear this flag as soon as we find a pullable task */
11107 env.flags |= LBF_ALL_PINNED;
11108 if (busiest->nr_running > 1) {
11110 * Attempt to move tasks. If find_busiest_group has found
11111 * an imbalance but busiest->nr_running <= 1, the group is
11112 * still unbalanced. ld_moved simply stays zero, so it is
11113 * correctly treated as an imbalance.
11115 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11118 rq_lock_irqsave(busiest, &rf);
11119 update_rq_clock(busiest);
11122 * cur_ld_moved - load moved in current iteration
11123 * ld_moved - cumulative load moved across iterations
11125 cur_ld_moved = detach_tasks(&env);
11128 * We've detached some tasks from busiest_rq. Every
11129 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11130 * unlock busiest->lock, and we are able to be sure
11131 * that nobody can manipulate the tasks in parallel.
11132 * See task_rq_lock() family for the details.
11135 rq_unlock(busiest, &rf);
11137 if (cur_ld_moved) {
11138 attach_tasks(&env);
11139 ld_moved += cur_ld_moved;
11142 local_irq_restore(rf.flags);
11144 if (env.flags & LBF_NEED_BREAK) {
11145 env.flags &= ~LBF_NEED_BREAK;
11146 /* Stop if we tried all running tasks */
11147 if (env.loop < busiest->nr_running)
11152 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11153 * us and move them to an alternate dst_cpu in our sched_group
11154 * where they can run. The upper limit on how many times we
11155 * iterate on same src_cpu is dependent on number of CPUs in our
11158 * This changes load balance semantics a bit on who can move
11159 * load to a given_cpu. In addition to the given_cpu itself
11160 * (or a ilb_cpu acting on its behalf where given_cpu is
11161 * nohz-idle), we now have balance_cpu in a position to move
11162 * load to given_cpu. In rare situations, this may cause
11163 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11164 * _independently_ and at _same_ time to move some load to
11165 * given_cpu) causing excess load to be moved to given_cpu.
11166 * This however should not happen so much in practice and
11167 * moreover subsequent load balance cycles should correct the
11168 * excess load moved.
11170 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11172 /* Prevent to re-select dst_cpu via env's CPUs */
11173 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11175 env.dst_rq = cpu_rq(env.new_dst_cpu);
11176 env.dst_cpu = env.new_dst_cpu;
11177 env.flags &= ~LBF_DST_PINNED;
11179 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11182 * Go back to "more_balance" rather than "redo" since we
11183 * need to continue with same src_cpu.
11189 * We failed to reach balance because of affinity.
11192 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11194 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11195 *group_imbalance = 1;
11198 /* All tasks on this runqueue were pinned by CPU affinity */
11199 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11200 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11202 * Attempting to continue load balancing at the current
11203 * sched_domain level only makes sense if there are
11204 * active CPUs remaining as possible busiest CPUs to
11205 * pull load from which are not contained within the
11206 * destination group that is receiving any migrated
11209 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11211 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11214 goto out_all_pinned;
11219 schedstat_inc(sd->lb_failed[idle]);
11221 * Increment the failure counter only on periodic balance.
11222 * We do not want newidle balance, which can be very
11223 * frequent, pollute the failure counter causing
11224 * excessive cache_hot migrations and active balances.
11226 if (idle != CPU_NEWLY_IDLE)
11227 sd->nr_balance_failed++;
11229 if (need_active_balance(&env)) {
11230 unsigned long flags;
11232 raw_spin_rq_lock_irqsave(busiest, flags);
11235 * Don't kick the active_load_balance_cpu_stop,
11236 * if the curr task on busiest CPU can't be
11237 * moved to this_cpu:
11239 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11240 raw_spin_rq_unlock_irqrestore(busiest, flags);
11241 goto out_one_pinned;
11244 /* Record that we found at least one task that could run on this_cpu */
11245 env.flags &= ~LBF_ALL_PINNED;
11248 * ->active_balance synchronizes accesses to
11249 * ->active_balance_work. Once set, it's cleared
11250 * only after active load balance is finished.
11252 if (!busiest->active_balance) {
11253 busiest->active_balance = 1;
11254 busiest->push_cpu = this_cpu;
11255 active_balance = 1;
11259 raw_spin_rq_unlock_irqrestore(busiest, flags);
11260 if (active_balance) {
11261 stop_one_cpu_nowait(cpu_of(busiest),
11262 active_load_balance_cpu_stop, busiest,
11263 &busiest->active_balance_work);
11268 sd->nr_balance_failed = 0;
11271 if (likely(!active_balance) || need_active_balance(&env)) {
11272 /* We were unbalanced, so reset the balancing interval */
11273 sd->balance_interval = sd->min_interval;
11280 * We reach balance although we may have faced some affinity
11281 * constraints. Clear the imbalance flag only if other tasks got
11282 * a chance to move and fix the imbalance.
11284 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11285 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11287 if (*group_imbalance)
11288 *group_imbalance = 0;
11293 * We reach balance because all tasks are pinned at this level so
11294 * we can't migrate them. Let the imbalance flag set so parent level
11295 * can try to migrate them.
11297 schedstat_inc(sd->lb_balanced[idle]);
11299 sd->nr_balance_failed = 0;
11305 * newidle_balance() disregards balance intervals, so we could
11306 * repeatedly reach this code, which would lead to balance_interval
11307 * skyrocketing in a short amount of time. Skip the balance_interval
11308 * increase logic to avoid that.
11310 if (env.idle == CPU_NEWLY_IDLE)
11313 /* tune up the balancing interval */
11314 if ((env.flags & LBF_ALL_PINNED &&
11315 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11316 sd->balance_interval < sd->max_interval)
11317 sd->balance_interval *= 2;
11322 static inline unsigned long
11323 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11325 unsigned long interval = sd->balance_interval;
11328 interval *= sd->busy_factor;
11330 /* scale ms to jiffies */
11331 interval = msecs_to_jiffies(interval);
11334 * Reduce likelihood of busy balancing at higher domains racing with
11335 * balancing at lower domains by preventing their balancing periods
11336 * from being multiples of each other.
11341 interval = clamp(interval, 1UL, max_load_balance_interval);
11347 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11349 unsigned long interval, next;
11351 /* used by idle balance, so cpu_busy = 0 */
11352 interval = get_sd_balance_interval(sd, 0);
11353 next = sd->last_balance + interval;
11355 if (time_after(*next_balance, next))
11356 *next_balance = next;
11360 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11361 * running tasks off the busiest CPU onto idle CPUs. It requires at
11362 * least 1 task to be running on each physical CPU where possible, and
11363 * avoids physical / logical imbalances.
11365 static int active_load_balance_cpu_stop(void *data)
11367 struct rq *busiest_rq = data;
11368 int busiest_cpu = cpu_of(busiest_rq);
11369 int target_cpu = busiest_rq->push_cpu;
11370 struct rq *target_rq = cpu_rq(target_cpu);
11371 struct sched_domain *sd;
11372 struct task_struct *p = NULL;
11373 struct rq_flags rf;
11375 rq_lock_irq(busiest_rq, &rf);
11377 * Between queueing the stop-work and running it is a hole in which
11378 * CPUs can become inactive. We should not move tasks from or to
11381 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11384 /* Make sure the requested CPU hasn't gone down in the meantime: */
11385 if (unlikely(busiest_cpu != smp_processor_id() ||
11386 !busiest_rq->active_balance))
11389 /* Is there any task to move? */
11390 if (busiest_rq->nr_running <= 1)
11394 * This condition is "impossible", if it occurs
11395 * we need to fix it. Originally reported by
11396 * Bjorn Helgaas on a 128-CPU setup.
11398 WARN_ON_ONCE(busiest_rq == target_rq);
11400 /* Search for an sd spanning us and the target CPU. */
11402 for_each_domain(target_cpu, sd) {
11403 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11408 struct lb_env env = {
11410 .dst_cpu = target_cpu,
11411 .dst_rq = target_rq,
11412 .src_cpu = busiest_rq->cpu,
11413 .src_rq = busiest_rq,
11415 .flags = LBF_ACTIVE_LB,
11418 schedstat_inc(sd->alb_count);
11419 update_rq_clock(busiest_rq);
11421 p = detach_one_task(&env);
11423 schedstat_inc(sd->alb_pushed);
11424 /* Active balancing done, reset the failure counter. */
11425 sd->nr_balance_failed = 0;
11427 schedstat_inc(sd->alb_failed);
11432 busiest_rq->active_balance = 0;
11433 rq_unlock(busiest_rq, &rf);
11436 attach_one_task(target_rq, p);
11438 local_irq_enable();
11443 static DEFINE_SPINLOCK(balancing);
11446 * Scale the max load_balance interval with the number of CPUs in the system.
11447 * This trades load-balance latency on larger machines for less cross talk.
11449 void update_max_interval(void)
11451 max_load_balance_interval = HZ*num_online_cpus()/10;
11454 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11456 if (cost > sd->max_newidle_lb_cost) {
11458 * Track max cost of a domain to make sure to not delay the
11459 * next wakeup on the CPU.
11461 sd->max_newidle_lb_cost = cost;
11462 sd->last_decay_max_lb_cost = jiffies;
11463 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11465 * Decay the newidle max times by ~1% per second to ensure that
11466 * it is not outdated and the current max cost is actually
11469 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11470 sd->last_decay_max_lb_cost = jiffies;
11479 * It checks each scheduling domain to see if it is due to be balanced,
11480 * and initiates a balancing operation if so.
11482 * Balancing parameters are set up in init_sched_domains.
11484 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11486 int continue_balancing = 1;
11488 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11489 unsigned long interval;
11490 struct sched_domain *sd;
11491 /* Earliest time when we have to do rebalance again */
11492 unsigned long next_balance = jiffies + 60*HZ;
11493 int update_next_balance = 0;
11494 int need_serialize, need_decay = 0;
11498 for_each_domain(cpu, sd) {
11500 * Decay the newidle max times here because this is a regular
11501 * visit to all the domains.
11503 need_decay = update_newidle_cost(sd, 0);
11504 max_cost += sd->max_newidle_lb_cost;
11507 * Stop the load balance at this level. There is another
11508 * CPU in our sched group which is doing load balancing more
11511 if (!continue_balancing) {
11517 interval = get_sd_balance_interval(sd, busy);
11519 need_serialize = sd->flags & SD_SERIALIZE;
11520 if (need_serialize) {
11521 if (!spin_trylock(&balancing))
11525 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11526 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11528 * The LBF_DST_PINNED logic could have changed
11529 * env->dst_cpu, so we can't know our idle
11530 * state even if we migrated tasks. Update it.
11532 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11533 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11535 sd->last_balance = jiffies;
11536 interval = get_sd_balance_interval(sd, busy);
11538 if (need_serialize)
11539 spin_unlock(&balancing);
11541 if (time_after(next_balance, sd->last_balance + interval)) {
11542 next_balance = sd->last_balance + interval;
11543 update_next_balance = 1;
11548 * Ensure the rq-wide value also decays but keep it at a
11549 * reasonable floor to avoid funnies with rq->avg_idle.
11551 rq->max_idle_balance_cost =
11552 max((u64)sysctl_sched_migration_cost, max_cost);
11557 * next_balance will be updated only when there is a need.
11558 * When the cpu is attached to null domain for ex, it will not be
11561 if (likely(update_next_balance))
11562 rq->next_balance = next_balance;
11566 static inline int on_null_domain(struct rq *rq)
11568 return unlikely(!rcu_dereference_sched(rq->sd));
11571 #ifdef CONFIG_NO_HZ_COMMON
11573 * NOHZ idle load balancing (ILB) details:
11575 * - When one of the busy CPUs notices that there may be an idle rebalancing
11576 * needed, they will kick the idle load balancer, which then does idle
11577 * load balancing for all the idle CPUs.
11579 * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED is not set
11582 static inline int find_new_ilb(void)
11584 const struct cpumask *hk_mask;
11587 hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11589 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
11591 if (ilb_cpu == smp_processor_id())
11594 if (idle_cpu(ilb_cpu))
11602 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
11603 * SMP function call (IPI).
11605 * We pick the first idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11607 static void kick_ilb(unsigned int flags)
11612 * Increase nohz.next_balance only when if full ilb is triggered but
11613 * not if we only update stats.
11615 if (flags & NOHZ_BALANCE_KICK)
11616 nohz.next_balance = jiffies+1;
11618 ilb_cpu = find_new_ilb();
11623 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11624 * the first flag owns it; cleared by nohz_csd_func().
11626 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11627 if (flags & NOHZ_KICK_MASK)
11631 * This way we generate an IPI on the target CPU which
11632 * is idle, and the softirq performing NOHZ idle load balancing
11633 * will be run before returning from the IPI.
11635 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11639 * Current decision point for kicking the idle load balancer in the presence
11640 * of idle CPUs in the system.
11642 static void nohz_balancer_kick(struct rq *rq)
11644 unsigned long now = jiffies;
11645 struct sched_domain_shared *sds;
11646 struct sched_domain *sd;
11647 int nr_busy, i, cpu = rq->cpu;
11648 unsigned int flags = 0;
11650 if (unlikely(rq->idle_balance))
11654 * We may be recently in ticked or tickless idle mode. At the first
11655 * busy tick after returning from idle, we will update the busy stats.
11657 nohz_balance_exit_idle(rq);
11660 * None are in tickless mode and hence no need for NOHZ idle load
11663 if (likely(!atomic_read(&nohz.nr_cpus)))
11666 if (READ_ONCE(nohz.has_blocked) &&
11667 time_after(now, READ_ONCE(nohz.next_blocked)))
11668 flags = NOHZ_STATS_KICK;
11670 if (time_before(now, nohz.next_balance))
11673 if (rq->nr_running >= 2) {
11674 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11680 sd = rcu_dereference(rq->sd);
11683 * If there's a runnable CFS task and the current CPU has reduced
11684 * capacity, kick the ILB to see if there's a better CPU to run on:
11686 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11687 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11692 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11695 * When ASYM_PACKING; see if there's a more preferred CPU
11696 * currently idle; in which case, kick the ILB to move tasks
11699 * When balancing betwen cores, all the SMT siblings of the
11700 * preferred CPU must be idle.
11702 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11703 if (sched_use_asym_prio(sd, i) &&
11704 sched_asym_prefer(i, cpu)) {
11705 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11711 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11714 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11715 * to run the misfit task on.
11717 if (check_misfit_status(rq, sd)) {
11718 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11723 * For asymmetric systems, we do not want to nicely balance
11724 * cache use, instead we want to embrace asymmetry and only
11725 * ensure tasks have enough CPU capacity.
11727 * Skip the LLC logic because it's not relevant in that case.
11732 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11735 * If there is an imbalance between LLC domains (IOW we could
11736 * increase the overall cache utilization), we need a less-loaded LLC
11737 * domain to pull some load from. Likewise, we may need to spread
11738 * load within the current LLC domain (e.g. packed SMT cores but
11739 * other CPUs are idle). We can't really know from here how busy
11740 * the others are - so just get a NOHZ balance going if it looks
11741 * like this LLC domain has tasks we could move.
11743 nr_busy = atomic_read(&sds->nr_busy_cpus);
11745 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11752 if (READ_ONCE(nohz.needs_update))
11753 flags |= NOHZ_NEXT_KICK;
11759 static void set_cpu_sd_state_busy(int cpu)
11761 struct sched_domain *sd;
11764 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11766 if (!sd || !sd->nohz_idle)
11770 atomic_inc(&sd->shared->nr_busy_cpus);
11775 void nohz_balance_exit_idle(struct rq *rq)
11777 SCHED_WARN_ON(rq != this_rq());
11779 if (likely(!rq->nohz_tick_stopped))
11782 rq->nohz_tick_stopped = 0;
11783 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
11784 atomic_dec(&nohz.nr_cpus);
11786 set_cpu_sd_state_busy(rq->cpu);
11789 static void set_cpu_sd_state_idle(int cpu)
11791 struct sched_domain *sd;
11794 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11796 if (!sd || sd->nohz_idle)
11800 atomic_dec(&sd->shared->nr_busy_cpus);
11806 * This routine will record that the CPU is going idle with tick stopped.
11807 * This info will be used in performing idle load balancing in the future.
11809 void nohz_balance_enter_idle(int cpu)
11811 struct rq *rq = cpu_rq(cpu);
11813 SCHED_WARN_ON(cpu != smp_processor_id());
11815 /* If this CPU is going down, then nothing needs to be done: */
11816 if (!cpu_active(cpu))
11819 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
11820 if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
11824 * Can be set safely without rq->lock held
11825 * If a clear happens, it will have evaluated last additions because
11826 * rq->lock is held during the check and the clear
11828 rq->has_blocked_load = 1;
11831 * The tick is still stopped but load could have been added in the
11832 * meantime. We set the nohz.has_blocked flag to trig a check of the
11833 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
11834 * of nohz.has_blocked can only happen after checking the new load
11836 if (rq->nohz_tick_stopped)
11839 /* If we're a completely isolated CPU, we don't play: */
11840 if (on_null_domain(rq))
11843 rq->nohz_tick_stopped = 1;
11845 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
11846 atomic_inc(&nohz.nr_cpus);
11849 * Ensures that if nohz_idle_balance() fails to observe our
11850 * @idle_cpus_mask store, it must observe the @has_blocked
11851 * and @needs_update stores.
11853 smp_mb__after_atomic();
11855 set_cpu_sd_state_idle(cpu);
11857 WRITE_ONCE(nohz.needs_update, 1);
11860 * Each time a cpu enter idle, we assume that it has blocked load and
11861 * enable the periodic update of the load of idle cpus
11863 WRITE_ONCE(nohz.has_blocked, 1);
11866 static bool update_nohz_stats(struct rq *rq)
11868 unsigned int cpu = rq->cpu;
11870 if (!rq->has_blocked_load)
11873 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
11876 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
11879 update_blocked_averages(cpu);
11881 return rq->has_blocked_load;
11885 * Internal function that runs load balance for all idle cpus. The load balance
11886 * can be a simple update of blocked load or a complete load balance with
11887 * tasks movement depending of flags.
11889 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
11891 /* Earliest time when we have to do rebalance again */
11892 unsigned long now = jiffies;
11893 unsigned long next_balance = now + 60*HZ;
11894 bool has_blocked_load = false;
11895 int update_next_balance = 0;
11896 int this_cpu = this_rq->cpu;
11900 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
11903 * We assume there will be no idle load after this update and clear
11904 * the has_blocked flag. If a cpu enters idle in the mean time, it will
11905 * set the has_blocked flag and trigger another update of idle load.
11906 * Because a cpu that becomes idle, is added to idle_cpus_mask before
11907 * setting the flag, we are sure to not clear the state and not
11908 * check the load of an idle cpu.
11910 * Same applies to idle_cpus_mask vs needs_update.
11912 if (flags & NOHZ_STATS_KICK)
11913 WRITE_ONCE(nohz.has_blocked, 0);
11914 if (flags & NOHZ_NEXT_KICK)
11915 WRITE_ONCE(nohz.needs_update, 0);
11918 * Ensures that if we miss the CPU, we must see the has_blocked
11919 * store from nohz_balance_enter_idle().
11924 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
11925 * chance for other idle cpu to pull load.
11927 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
11928 if (!idle_cpu(balance_cpu))
11932 * If this CPU gets work to do, stop the load balancing
11933 * work being done for other CPUs. Next load
11934 * balancing owner will pick it up.
11936 if (need_resched()) {
11937 if (flags & NOHZ_STATS_KICK)
11938 has_blocked_load = true;
11939 if (flags & NOHZ_NEXT_KICK)
11940 WRITE_ONCE(nohz.needs_update, 1);
11944 rq = cpu_rq(balance_cpu);
11946 if (flags & NOHZ_STATS_KICK)
11947 has_blocked_load |= update_nohz_stats(rq);
11950 * If time for next balance is due,
11953 if (time_after_eq(jiffies, rq->next_balance)) {
11954 struct rq_flags rf;
11956 rq_lock_irqsave(rq, &rf);
11957 update_rq_clock(rq);
11958 rq_unlock_irqrestore(rq, &rf);
11960 if (flags & NOHZ_BALANCE_KICK)
11961 rebalance_domains(rq, CPU_IDLE);
11964 if (time_after(next_balance, rq->next_balance)) {
11965 next_balance = rq->next_balance;
11966 update_next_balance = 1;
11971 * next_balance will be updated only when there is a need.
11972 * When the CPU is attached to null domain for ex, it will not be
11975 if (likely(update_next_balance))
11976 nohz.next_balance = next_balance;
11978 if (flags & NOHZ_STATS_KICK)
11979 WRITE_ONCE(nohz.next_blocked,
11980 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
11983 /* There is still blocked load, enable periodic update */
11984 if (has_blocked_load)
11985 WRITE_ONCE(nohz.has_blocked, 1);
11989 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
11990 * rebalancing for all the cpus for whom scheduler ticks are stopped.
11992 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
11994 unsigned int flags = this_rq->nohz_idle_balance;
11999 this_rq->nohz_idle_balance = 0;
12001 if (idle != CPU_IDLE)
12004 _nohz_idle_balance(this_rq, flags);
12010 * Check if we need to run the ILB for updating blocked load before entering
12013 void nohz_run_idle_balance(int cpu)
12015 unsigned int flags;
12017 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12020 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12021 * (ie NOHZ_STATS_KICK set) and will do the same.
12023 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12024 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12027 static void nohz_newidle_balance(struct rq *this_rq)
12029 int this_cpu = this_rq->cpu;
12032 * This CPU doesn't want to be disturbed by scheduler
12035 if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
12038 /* Will wake up very soon. No time for doing anything else*/
12039 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12042 /* Don't need to update blocked load of idle CPUs*/
12043 if (!READ_ONCE(nohz.has_blocked) ||
12044 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12048 * Set the need to trigger ILB in order to update blocked load
12049 * before entering idle state.
12051 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12054 #else /* !CONFIG_NO_HZ_COMMON */
12055 static inline void nohz_balancer_kick(struct rq *rq) { }
12057 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12062 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12063 #endif /* CONFIG_NO_HZ_COMMON */
12066 * newidle_balance is called by schedule() if this_cpu is about to become
12067 * idle. Attempts to pull tasks from other CPUs.
12070 * < 0 - we released the lock and there are !fair tasks present
12071 * 0 - failed, no new tasks
12072 * > 0 - success, new (fair) tasks present
12074 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12076 unsigned long next_balance = jiffies + HZ;
12077 int this_cpu = this_rq->cpu;
12078 u64 t0, t1, curr_cost = 0;
12079 struct sched_domain *sd;
12080 int pulled_task = 0;
12082 update_misfit_status(NULL, this_rq);
12085 * There is a task waiting to run. No need to search for one.
12086 * Return 0; the task will be enqueued when switching to idle.
12088 if (this_rq->ttwu_pending)
12092 * We must set idle_stamp _before_ calling idle_balance(), such that we
12093 * measure the duration of idle_balance() as idle time.
12095 this_rq->idle_stamp = rq_clock(this_rq);
12098 * Do not pull tasks towards !active CPUs...
12100 if (!cpu_active(this_cpu))
12104 * This is OK, because current is on_cpu, which avoids it being picked
12105 * for load-balance and preemption/IRQs are still disabled avoiding
12106 * further scheduler activity on it and we're being very careful to
12107 * re-start the picking loop.
12109 rq_unpin_lock(this_rq, rf);
12112 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12114 if (!READ_ONCE(this_rq->rd->overload) ||
12115 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12118 update_next_balance(sd, &next_balance);
12125 raw_spin_rq_unlock(this_rq);
12127 t0 = sched_clock_cpu(this_cpu);
12128 update_blocked_averages(this_cpu);
12131 for_each_domain(this_cpu, sd) {
12132 int continue_balancing = 1;
12135 update_next_balance(sd, &next_balance);
12137 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12140 if (sd->flags & SD_BALANCE_NEWIDLE) {
12142 pulled_task = load_balance(this_cpu, this_rq,
12143 sd, CPU_NEWLY_IDLE,
12144 &continue_balancing);
12146 t1 = sched_clock_cpu(this_cpu);
12147 domain_cost = t1 - t0;
12148 update_newidle_cost(sd, domain_cost);
12150 curr_cost += domain_cost;
12155 * Stop searching for tasks to pull if there are
12156 * now runnable tasks on this rq.
12158 if (pulled_task || this_rq->nr_running > 0 ||
12159 this_rq->ttwu_pending)
12164 raw_spin_rq_lock(this_rq);
12166 if (curr_cost > this_rq->max_idle_balance_cost)
12167 this_rq->max_idle_balance_cost = curr_cost;
12170 * While browsing the domains, we released the rq lock, a task could
12171 * have been enqueued in the meantime. Since we're not going idle,
12172 * pretend we pulled a task.
12174 if (this_rq->cfs.h_nr_running && !pulled_task)
12177 /* Is there a task of a high priority class? */
12178 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12182 /* Move the next balance forward */
12183 if (time_after(this_rq->next_balance, next_balance))
12184 this_rq->next_balance = next_balance;
12187 this_rq->idle_stamp = 0;
12189 nohz_newidle_balance(this_rq);
12191 rq_repin_lock(this_rq, rf);
12193 return pulled_task;
12197 * run_rebalance_domains is triggered when needed from the scheduler tick.
12198 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12200 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12202 struct rq *this_rq = this_rq();
12203 enum cpu_idle_type idle = this_rq->idle_balance ?
12204 CPU_IDLE : CPU_NOT_IDLE;
12207 * If this CPU has a pending nohz_balance_kick, then do the
12208 * balancing on behalf of the other idle CPUs whose ticks are
12209 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12210 * give the idle CPUs a chance to load balance. Else we may
12211 * load balance only within the local sched_domain hierarchy
12212 * and abort nohz_idle_balance altogether if we pull some load.
12214 if (nohz_idle_balance(this_rq, idle))
12217 /* normal load balance */
12218 update_blocked_averages(this_rq->cpu);
12219 rebalance_domains(this_rq, idle);
12223 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12225 void trigger_load_balance(struct rq *rq)
12228 * Don't need to rebalance while attached to NULL domain or
12229 * runqueue CPU is not active
12231 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12234 if (time_after_eq(jiffies, rq->next_balance))
12235 raise_softirq(SCHED_SOFTIRQ);
12237 nohz_balancer_kick(rq);
12240 static void rq_online_fair(struct rq *rq)
12244 update_runtime_enabled(rq);
12247 static void rq_offline_fair(struct rq *rq)
12251 /* Ensure any throttled groups are reachable by pick_next_task */
12252 unthrottle_offline_cfs_rqs(rq);
12255 #endif /* CONFIG_SMP */
12257 #ifdef CONFIG_SCHED_CORE
12259 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12261 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12262 u64 slice = se->slice;
12264 return (rtime * min_nr_tasks > slice);
12267 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
12268 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12270 if (!sched_core_enabled(rq))
12274 * If runqueue has only one task which used up its slice and
12275 * if the sibling is forced idle, then trigger schedule to
12276 * give forced idle task a chance.
12278 * sched_slice() considers only this active rq and it gets the
12279 * whole slice. But during force idle, we have siblings acting
12280 * like a single runqueue and hence we need to consider runnable
12281 * tasks on this CPU and the forced idle CPU. Ideally, we should
12282 * go through the forced idle rq, but that would be a perf hit.
12283 * We can assume that the forced idle CPU has at least
12284 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12285 * if we need to give up the CPU.
12287 if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12288 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12293 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12295 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12298 for_each_sched_entity(se) {
12299 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12302 if (cfs_rq->forceidle_seq == fi_seq)
12304 cfs_rq->forceidle_seq = fi_seq;
12307 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12311 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12313 struct sched_entity *se = &p->se;
12315 if (p->sched_class != &fair_sched_class)
12318 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12321 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12324 struct rq *rq = task_rq(a);
12325 const struct sched_entity *sea = &a->se;
12326 const struct sched_entity *seb = &b->se;
12327 struct cfs_rq *cfs_rqa;
12328 struct cfs_rq *cfs_rqb;
12331 SCHED_WARN_ON(task_rq(b)->core != rq->core);
12333 #ifdef CONFIG_FAIR_GROUP_SCHED
12335 * Find an se in the hierarchy for tasks a and b, such that the se's
12336 * are immediate siblings.
12338 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12339 int sea_depth = sea->depth;
12340 int seb_depth = seb->depth;
12342 if (sea_depth >= seb_depth)
12343 sea = parent_entity(sea);
12344 if (sea_depth <= seb_depth)
12345 seb = parent_entity(seb);
12348 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12349 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12351 cfs_rqa = sea->cfs_rq;
12352 cfs_rqb = seb->cfs_rq;
12354 cfs_rqa = &task_rq(a)->cfs;
12355 cfs_rqb = &task_rq(b)->cfs;
12359 * Find delta after normalizing se's vruntime with its cfs_rq's
12360 * min_vruntime_fi, which would have been updated in prior calls
12361 * to se_fi_update().
12363 delta = (s64)(sea->vruntime - seb->vruntime) +
12364 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12369 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12371 struct cfs_rq *cfs_rq;
12373 #ifdef CONFIG_FAIR_GROUP_SCHED
12374 cfs_rq = task_group(p)->cfs_rq[cpu];
12376 cfs_rq = &cpu_rq(cpu)->cfs;
12378 return throttled_hierarchy(cfs_rq);
12381 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12385 * scheduler tick hitting a task of our scheduling class.
12387 * NOTE: This function can be called remotely by the tick offload that
12388 * goes along full dynticks. Therefore no local assumption can be made
12389 * and everything must be accessed through the @rq and @curr passed in
12392 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12394 struct cfs_rq *cfs_rq;
12395 struct sched_entity *se = &curr->se;
12397 for_each_sched_entity(se) {
12398 cfs_rq = cfs_rq_of(se);
12399 entity_tick(cfs_rq, se, queued);
12402 if (static_branch_unlikely(&sched_numa_balancing))
12403 task_tick_numa(rq, curr);
12405 update_misfit_status(curr, rq);
12406 update_overutilized_status(task_rq(curr));
12408 task_tick_core(rq, curr);
12412 * called on fork with the child task as argument from the parent's context
12413 * - child not yet on the tasklist
12414 * - preemption disabled
12416 static void task_fork_fair(struct task_struct *p)
12418 struct sched_entity *se = &p->se, *curr;
12419 struct cfs_rq *cfs_rq;
12420 struct rq *rq = this_rq();
12421 struct rq_flags rf;
12424 update_rq_clock(rq);
12426 cfs_rq = task_cfs_rq(current);
12427 curr = cfs_rq->curr;
12429 update_curr(cfs_rq);
12430 place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12431 rq_unlock(rq, &rf);
12435 * Priority of the task has changed. Check to see if we preempt
12436 * the current task.
12439 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12441 if (!task_on_rq_queued(p))
12444 if (rq->cfs.nr_running == 1)
12448 * Reschedule if we are currently running on this runqueue and
12449 * our priority decreased, or if we are not currently running on
12450 * this runqueue and our priority is higher than the current's
12452 if (task_current(rq, p)) {
12453 if (p->prio > oldprio)
12456 wakeup_preempt(rq, p, 0);
12459 #ifdef CONFIG_FAIR_GROUP_SCHED
12461 * Propagate the changes of the sched_entity across the tg tree to make it
12462 * visible to the root
12464 static void propagate_entity_cfs_rq(struct sched_entity *se)
12466 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12468 if (cfs_rq_throttled(cfs_rq))
12471 if (!throttled_hierarchy(cfs_rq))
12472 list_add_leaf_cfs_rq(cfs_rq);
12474 /* Start to propagate at parent */
12477 for_each_sched_entity(se) {
12478 cfs_rq = cfs_rq_of(se);
12480 update_load_avg(cfs_rq, se, UPDATE_TG);
12482 if (cfs_rq_throttled(cfs_rq))
12485 if (!throttled_hierarchy(cfs_rq))
12486 list_add_leaf_cfs_rq(cfs_rq);
12490 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12493 static void detach_entity_cfs_rq(struct sched_entity *se)
12495 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12499 * In case the task sched_avg hasn't been attached:
12500 * - A forked task which hasn't been woken up by wake_up_new_task().
12501 * - A task which has been woken up by try_to_wake_up() but is
12502 * waiting for actually being woken up by sched_ttwu_pending().
12504 if (!se->avg.last_update_time)
12508 /* Catch up with the cfs_rq and remove our load when we leave */
12509 update_load_avg(cfs_rq, se, 0);
12510 detach_entity_load_avg(cfs_rq, se);
12511 update_tg_load_avg(cfs_rq);
12512 propagate_entity_cfs_rq(se);
12515 static void attach_entity_cfs_rq(struct sched_entity *se)
12517 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12519 /* Synchronize entity with its cfs_rq */
12520 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12521 attach_entity_load_avg(cfs_rq, se);
12522 update_tg_load_avg(cfs_rq);
12523 propagate_entity_cfs_rq(se);
12526 static void detach_task_cfs_rq(struct task_struct *p)
12528 struct sched_entity *se = &p->se;
12530 detach_entity_cfs_rq(se);
12533 static void attach_task_cfs_rq(struct task_struct *p)
12535 struct sched_entity *se = &p->se;
12537 attach_entity_cfs_rq(se);
12540 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12542 detach_task_cfs_rq(p);
12545 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12547 attach_task_cfs_rq(p);
12549 if (task_on_rq_queued(p)) {
12551 * We were most likely switched from sched_rt, so
12552 * kick off the schedule if running, otherwise just see
12553 * if we can still preempt the current task.
12555 if (task_current(rq, p))
12558 wakeup_preempt(rq, p, 0);
12562 /* Account for a task changing its policy or group.
12564 * This routine is mostly called to set cfs_rq->curr field when a task
12565 * migrates between groups/classes.
12567 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12569 struct sched_entity *se = &p->se;
12572 if (task_on_rq_queued(p)) {
12574 * Move the next running task to the front of the list, so our
12575 * cfs_tasks list becomes MRU one.
12577 list_move(&se->group_node, &rq->cfs_tasks);
12581 for_each_sched_entity(se) {
12582 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12584 set_next_entity(cfs_rq, se);
12585 /* ensure bandwidth has been allocated on our new cfs_rq */
12586 account_cfs_rq_runtime(cfs_rq, 0);
12590 void init_cfs_rq(struct cfs_rq *cfs_rq)
12592 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12593 u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12595 raw_spin_lock_init(&cfs_rq->removed.lock);
12599 #ifdef CONFIG_FAIR_GROUP_SCHED
12600 static void task_change_group_fair(struct task_struct *p)
12603 * We couldn't detach or attach a forked task which
12604 * hasn't been woken up by wake_up_new_task().
12606 if (READ_ONCE(p->__state) == TASK_NEW)
12609 detach_task_cfs_rq(p);
12612 /* Tell se's cfs_rq has been changed -- migrated */
12613 p->se.avg.last_update_time = 0;
12615 set_task_rq(p, task_cpu(p));
12616 attach_task_cfs_rq(p);
12619 void free_fair_sched_group(struct task_group *tg)
12623 for_each_possible_cpu(i) {
12625 kfree(tg->cfs_rq[i]);
12634 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12636 struct sched_entity *se;
12637 struct cfs_rq *cfs_rq;
12640 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12643 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12647 tg->shares = NICE_0_LOAD;
12649 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12651 for_each_possible_cpu(i) {
12652 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12653 GFP_KERNEL, cpu_to_node(i));
12657 se = kzalloc_node(sizeof(struct sched_entity_stats),
12658 GFP_KERNEL, cpu_to_node(i));
12662 init_cfs_rq(cfs_rq);
12663 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12664 init_entity_runnable_average(se);
12675 void online_fair_sched_group(struct task_group *tg)
12677 struct sched_entity *se;
12678 struct rq_flags rf;
12682 for_each_possible_cpu(i) {
12685 rq_lock_irq(rq, &rf);
12686 update_rq_clock(rq);
12687 attach_entity_cfs_rq(se);
12688 sync_throttle(tg, i);
12689 rq_unlock_irq(rq, &rf);
12693 void unregister_fair_sched_group(struct task_group *tg)
12695 unsigned long flags;
12699 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12701 for_each_possible_cpu(cpu) {
12703 remove_entity_load_avg(tg->se[cpu]);
12706 * Only empty task groups can be destroyed; so we can speculatively
12707 * check on_list without danger of it being re-added.
12709 if (!tg->cfs_rq[cpu]->on_list)
12714 raw_spin_rq_lock_irqsave(rq, flags);
12715 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12716 raw_spin_rq_unlock_irqrestore(rq, flags);
12720 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12721 struct sched_entity *se, int cpu,
12722 struct sched_entity *parent)
12724 struct rq *rq = cpu_rq(cpu);
12728 init_cfs_rq_runtime(cfs_rq);
12730 tg->cfs_rq[cpu] = cfs_rq;
12733 /* se could be NULL for root_task_group */
12738 se->cfs_rq = &rq->cfs;
12741 se->cfs_rq = parent->my_q;
12742 se->depth = parent->depth + 1;
12746 /* guarantee group entities always have weight */
12747 update_load_set(&se->load, NICE_0_LOAD);
12748 se->parent = parent;
12751 static DEFINE_MUTEX(shares_mutex);
12753 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
12757 lockdep_assert_held(&shares_mutex);
12760 * We can't change the weight of the root cgroup.
12765 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
12767 if (tg->shares == shares)
12770 tg->shares = shares;
12771 for_each_possible_cpu(i) {
12772 struct rq *rq = cpu_rq(i);
12773 struct sched_entity *se = tg->se[i];
12774 struct rq_flags rf;
12776 /* Propagate contribution to hierarchy */
12777 rq_lock_irqsave(rq, &rf);
12778 update_rq_clock(rq);
12779 for_each_sched_entity(se) {
12780 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
12781 update_cfs_group(se);
12783 rq_unlock_irqrestore(rq, &rf);
12789 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
12793 mutex_lock(&shares_mutex);
12794 if (tg_is_idle(tg))
12797 ret = __sched_group_set_shares(tg, shares);
12798 mutex_unlock(&shares_mutex);
12803 int sched_group_set_idle(struct task_group *tg, long idle)
12807 if (tg == &root_task_group)
12810 if (idle < 0 || idle > 1)
12813 mutex_lock(&shares_mutex);
12815 if (tg->idle == idle) {
12816 mutex_unlock(&shares_mutex);
12822 for_each_possible_cpu(i) {
12823 struct rq *rq = cpu_rq(i);
12824 struct sched_entity *se = tg->se[i];
12825 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
12826 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
12827 long idle_task_delta;
12828 struct rq_flags rf;
12830 rq_lock_irqsave(rq, &rf);
12832 grp_cfs_rq->idle = idle;
12833 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
12837 parent_cfs_rq = cfs_rq_of(se);
12838 if (cfs_rq_is_idle(grp_cfs_rq))
12839 parent_cfs_rq->idle_nr_running++;
12841 parent_cfs_rq->idle_nr_running--;
12844 idle_task_delta = grp_cfs_rq->h_nr_running -
12845 grp_cfs_rq->idle_h_nr_running;
12846 if (!cfs_rq_is_idle(grp_cfs_rq))
12847 idle_task_delta *= -1;
12849 for_each_sched_entity(se) {
12850 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12855 cfs_rq->idle_h_nr_running += idle_task_delta;
12857 /* Already accounted at parent level and above. */
12858 if (cfs_rq_is_idle(cfs_rq))
12863 rq_unlock_irqrestore(rq, &rf);
12866 /* Idle groups have minimum weight. */
12867 if (tg_is_idle(tg))
12868 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
12870 __sched_group_set_shares(tg, NICE_0_LOAD);
12872 mutex_unlock(&shares_mutex);
12876 #else /* CONFIG_FAIR_GROUP_SCHED */
12878 void free_fair_sched_group(struct task_group *tg) { }
12880 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12885 void online_fair_sched_group(struct task_group *tg) { }
12887 void unregister_fair_sched_group(struct task_group *tg) { }
12889 #endif /* CONFIG_FAIR_GROUP_SCHED */
12892 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
12894 struct sched_entity *se = &task->se;
12895 unsigned int rr_interval = 0;
12898 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
12901 if (rq->cfs.load.weight)
12902 rr_interval = NS_TO_JIFFIES(se->slice);
12904 return rr_interval;
12908 * All the scheduling class methods:
12910 DEFINE_SCHED_CLASS(fair) = {
12912 .enqueue_task = enqueue_task_fair,
12913 .dequeue_task = dequeue_task_fair,
12914 .yield_task = yield_task_fair,
12915 .yield_to_task = yield_to_task_fair,
12917 .wakeup_preempt = check_preempt_wakeup_fair,
12919 .pick_next_task = __pick_next_task_fair,
12920 .put_prev_task = put_prev_task_fair,
12921 .set_next_task = set_next_task_fair,
12924 .balance = balance_fair,
12925 .pick_task = pick_task_fair,
12926 .select_task_rq = select_task_rq_fair,
12927 .migrate_task_rq = migrate_task_rq_fair,
12929 .rq_online = rq_online_fair,
12930 .rq_offline = rq_offline_fair,
12932 .task_dead = task_dead_fair,
12933 .set_cpus_allowed = set_cpus_allowed_common,
12936 .task_tick = task_tick_fair,
12937 .task_fork = task_fork_fair,
12939 .prio_changed = prio_changed_fair,
12940 .switched_from = switched_from_fair,
12941 .switched_to = switched_to_fair,
12943 .get_rr_interval = get_rr_interval_fair,
12945 .update_curr = update_curr_fair,
12947 #ifdef CONFIG_FAIR_GROUP_SCHED
12948 .task_change_group = task_change_group_fair,
12951 #ifdef CONFIG_SCHED_CORE
12952 .task_is_throttled = task_is_throttled_fair,
12955 #ifdef CONFIG_UCLAMP_TASK
12956 .uclamp_enabled = 1,
12960 #ifdef CONFIG_SCHED_DEBUG
12961 void print_cfs_stats(struct seq_file *m, int cpu)
12963 struct cfs_rq *cfs_rq, *pos;
12966 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
12967 print_cfs_rq(m, cpu, cfs_rq);
12971 #ifdef CONFIG_NUMA_BALANCING
12972 void show_numa_stats(struct task_struct *p, struct seq_file *m)
12975 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
12976 struct numa_group *ng;
12979 ng = rcu_dereference(p->numa_group);
12980 for_each_online_node(node) {
12981 if (p->numa_faults) {
12982 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
12983 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
12986 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
12987 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
12989 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
12993 #endif /* CONFIG_NUMA_BALANCING */
12994 #endif /* CONFIG_SCHED_DEBUG */
12996 __init void init_sched_fair_class(void)
13001 for_each_possible_cpu(i) {
13002 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13003 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13004 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13005 GFP_KERNEL, cpu_to_node(i));
13007 #ifdef CONFIG_CFS_BANDWIDTH
13008 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13009 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13013 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
13015 #ifdef CONFIG_NO_HZ_COMMON
13016 nohz.next_balance = jiffies;
13017 nohz.next_blocked = jiffies;
13018 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);