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>
56 #include "autogroup.h"
59 * The initial- and re-scaling of tunables is configurable
63 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
64 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
65 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
67 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
69 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
72 * Minimal preemption granularity for CPU-bound tasks:
74 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
76 unsigned int sysctl_sched_base_slice = 750000ULL;
77 static unsigned int normalized_sysctl_sched_base_slice = 750000ULL;
79 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
81 int sched_thermal_decay_shift;
82 static int __init setup_sched_thermal_decay_shift(char *str)
86 if (kstrtoint(str, 0, &_shift))
87 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
89 sched_thermal_decay_shift = clamp(_shift, 0, 10);
92 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
96 * For asym packing, by default the lower numbered CPU has higher priority.
98 int __weak arch_asym_cpu_priority(int cpu)
104 * The margin used when comparing utilization with CPU capacity.
108 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
111 * The margin used when comparing CPU capacities.
112 * is 'cap1' noticeably greater than 'cap2'
116 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
119 #ifdef CONFIG_CFS_BANDWIDTH
121 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
122 * each time a cfs_rq requests quota.
124 * Note: in the case that the slice exceeds the runtime remaining (either due
125 * to consumption or the quota being specified to be smaller than the slice)
126 * we will always only issue the remaining available time.
128 * (default: 5 msec, units: microseconds)
130 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
133 #ifdef CONFIG_NUMA_BALANCING
134 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
135 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
139 static struct ctl_table sched_fair_sysctls[] = {
140 #ifdef CONFIG_CFS_BANDWIDTH
142 .procname = "sched_cfs_bandwidth_slice_us",
143 .data = &sysctl_sched_cfs_bandwidth_slice,
144 .maxlen = sizeof(unsigned int),
146 .proc_handler = proc_dointvec_minmax,
147 .extra1 = SYSCTL_ONE,
150 #ifdef CONFIG_NUMA_BALANCING
152 .procname = "numa_balancing_promote_rate_limit_MBps",
153 .data = &sysctl_numa_balancing_promote_rate_limit,
154 .maxlen = sizeof(unsigned int),
156 .proc_handler = proc_dointvec_minmax,
157 .extra1 = SYSCTL_ZERO,
159 #endif /* CONFIG_NUMA_BALANCING */
163 static int __init sched_fair_sysctl_init(void)
165 register_sysctl_init("kernel", sched_fair_sysctls);
168 late_initcall(sched_fair_sysctl_init);
171 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
177 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
183 static inline void update_load_set(struct load_weight *lw, unsigned long w)
190 * Increase the granularity value when there are more CPUs,
191 * because with more CPUs the 'effective latency' as visible
192 * to users decreases. But the relationship is not linear,
193 * so pick a second-best guess by going with the log2 of the
196 * This idea comes from the SD scheduler of Con Kolivas:
198 static unsigned int get_update_sysctl_factor(void)
200 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
203 switch (sysctl_sched_tunable_scaling) {
204 case SCHED_TUNABLESCALING_NONE:
207 case SCHED_TUNABLESCALING_LINEAR:
210 case SCHED_TUNABLESCALING_LOG:
212 factor = 1 + ilog2(cpus);
219 static void update_sysctl(void)
221 unsigned int factor = get_update_sysctl_factor();
223 #define SET_SYSCTL(name) \
224 (sysctl_##name = (factor) * normalized_sysctl_##name)
225 SET_SYSCTL(sched_base_slice);
229 void __init sched_init_granularity(void)
234 #define WMULT_CONST (~0U)
235 #define WMULT_SHIFT 32
237 static void __update_inv_weight(struct load_weight *lw)
241 if (likely(lw->inv_weight))
244 w = scale_load_down(lw->weight);
246 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
248 else if (unlikely(!w))
249 lw->inv_weight = WMULT_CONST;
251 lw->inv_weight = WMULT_CONST / w;
255 * delta_exec * weight / lw.weight
257 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
259 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
260 * we're guaranteed shift stays positive because inv_weight is guaranteed to
261 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
263 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
264 * weight/lw.weight <= 1, and therefore our shift will also be positive.
266 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
268 u64 fact = scale_load_down(weight);
269 u32 fact_hi = (u32)(fact >> 32);
270 int shift = WMULT_SHIFT;
273 __update_inv_weight(lw);
275 if (unlikely(fact_hi)) {
281 fact = mul_u32_u32(fact, lw->inv_weight);
283 fact_hi = (u32)(fact >> 32);
290 return mul_u64_u32_shr(delta_exec, fact, shift);
296 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
298 if (unlikely(se->load.weight != NICE_0_LOAD))
299 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
304 const struct sched_class fair_sched_class;
306 /**************************************************************
307 * CFS operations on generic schedulable entities:
310 #ifdef CONFIG_FAIR_GROUP_SCHED
312 /* Walk up scheduling entities hierarchy */
313 #define for_each_sched_entity(se) \
314 for (; se; se = se->parent)
316 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
318 struct rq *rq = rq_of(cfs_rq);
319 int cpu = cpu_of(rq);
322 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
327 * Ensure we either appear before our parent (if already
328 * enqueued) or force our parent to appear after us when it is
329 * enqueued. The fact that we always enqueue bottom-up
330 * reduces this to two cases and a special case for the root
331 * cfs_rq. Furthermore, it also means that we will always reset
332 * tmp_alone_branch either when the branch is connected
333 * to a tree or when we reach the top of the tree
335 if (cfs_rq->tg->parent &&
336 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
338 * If parent is already on the list, we add the child
339 * just before. Thanks to circular linked property of
340 * the list, this means to put the child at the tail
341 * of the list that starts by parent.
343 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
344 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
346 * The branch is now connected to its tree so we can
347 * reset tmp_alone_branch to the beginning of the
350 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
354 if (!cfs_rq->tg->parent) {
356 * cfs rq without parent should be put
357 * at the tail of the list.
359 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
360 &rq->leaf_cfs_rq_list);
362 * We have reach the top of a tree so we can reset
363 * tmp_alone_branch to the beginning of the list.
365 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
370 * The parent has not already been added so we want to
371 * make sure that it will be put after us.
372 * tmp_alone_branch points to the begin of the branch
373 * where we will add parent.
375 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
377 * update tmp_alone_branch to points to the new begin
380 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
384 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
386 if (cfs_rq->on_list) {
387 struct rq *rq = rq_of(cfs_rq);
390 * With cfs_rq being unthrottled/throttled during an enqueue,
391 * it can happen the tmp_alone_branch points the a leaf that
392 * we finally want to del. In this case, tmp_alone_branch moves
393 * to the prev element but it will point to rq->leaf_cfs_rq_list
394 * at the end of the enqueue.
396 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
397 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
399 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
404 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
406 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
409 /* Iterate thr' all leaf cfs_rq's on a runqueue */
410 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
411 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
414 /* Do the two (enqueued) entities belong to the same group ? */
415 static inline struct cfs_rq *
416 is_same_group(struct sched_entity *se, struct sched_entity *pse)
418 if (se->cfs_rq == pse->cfs_rq)
424 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
430 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
432 int se_depth, pse_depth;
435 * preemption test can be made between sibling entities who are in the
436 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
437 * both tasks until we find their ancestors who are siblings of common
441 /* First walk up until both entities are at same depth */
442 se_depth = (*se)->depth;
443 pse_depth = (*pse)->depth;
445 while (se_depth > pse_depth) {
447 *se = parent_entity(*se);
450 while (pse_depth > se_depth) {
452 *pse = parent_entity(*pse);
455 while (!is_same_group(*se, *pse)) {
456 *se = parent_entity(*se);
457 *pse = parent_entity(*pse);
461 static int tg_is_idle(struct task_group *tg)
466 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
468 return cfs_rq->idle > 0;
471 static int se_is_idle(struct sched_entity *se)
473 if (entity_is_task(se))
474 return task_has_idle_policy(task_of(se));
475 return cfs_rq_is_idle(group_cfs_rq(se));
478 #else /* !CONFIG_FAIR_GROUP_SCHED */
480 #define for_each_sched_entity(se) \
481 for (; se; se = NULL)
483 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
488 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
492 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
496 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
497 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
499 static inline struct sched_entity *parent_entity(struct sched_entity *se)
505 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
509 static inline int tg_is_idle(struct task_group *tg)
514 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
519 static int se_is_idle(struct sched_entity *se)
524 #endif /* CONFIG_FAIR_GROUP_SCHED */
526 static __always_inline
527 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
529 /**************************************************************
530 * Scheduling class tree data structure manipulation methods:
533 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
535 s64 delta = (s64)(vruntime - max_vruntime);
537 max_vruntime = vruntime;
542 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
544 s64 delta = (s64)(vruntime - min_vruntime);
546 min_vruntime = vruntime;
551 static inline bool entity_before(const struct sched_entity *a,
552 const struct sched_entity *b)
554 return (s64)(a->vruntime - b->vruntime) < 0;
557 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
559 return (s64)(se->vruntime - cfs_rq->min_vruntime);
562 #define __node_2_se(node) \
563 rb_entry((node), struct sched_entity, run_node)
566 * Compute virtual time from the per-task service numbers:
568 * Fair schedulers conserve lag:
572 * Where lag_i is given by:
574 * lag_i = S - s_i = w_i * (V - v_i)
576 * Where S is the ideal service time and V is it's virtual time counterpart.
580 * \Sum w_i * (V - v_i) = 0
581 * \Sum w_i * V - w_i * v_i = 0
583 * From which we can solve an expression for V in v_i (which we have in
586 * \Sum v_i * w_i \Sum v_i * w_i
587 * V = -------------- = --------------
590 * Specifically, this is the weighted average of all entity virtual runtimes.
592 * [[ NOTE: this is only equal to the ideal scheduler under the condition
593 * that join/leave operations happen at lag_i = 0, otherwise the
594 * virtual time has non-continguous motion equivalent to:
598 * Also see the comment in place_entity() that deals with this. ]]
600 * However, since v_i is u64, and the multiplcation could easily overflow
601 * transform it into a relative form that uses smaller quantities:
603 * Substitute: v_i == (v_i - v0) + v0
605 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
606 * V = ---------------------------- = --------------------- + v0
609 * Which we track using:
611 * v0 := cfs_rq->min_vruntime
612 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
613 * \Sum w_i := cfs_rq->avg_load
615 * Since min_vruntime is a monotonic increasing variable that closely tracks
616 * the per-task service, these deltas: (v_i - v), will be in the order of the
617 * maximal (virtual) lag induced in the system due to quantisation.
619 * Also, we use scale_load_down() to reduce the size.
621 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
624 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
626 unsigned long weight = scale_load_down(se->load.weight);
627 s64 key = entity_key(cfs_rq, se);
629 cfs_rq->avg_vruntime += key * weight;
630 cfs_rq->avg_load += weight;
634 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
636 unsigned long weight = scale_load_down(se->load.weight);
637 s64 key = entity_key(cfs_rq, se);
639 cfs_rq->avg_vruntime -= key * weight;
640 cfs_rq->avg_load -= weight;
644 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
647 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
649 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
653 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
654 * For this to be so, the result of this function must have a left bias.
656 u64 avg_vruntime(struct cfs_rq *cfs_rq)
658 struct sched_entity *curr = cfs_rq->curr;
659 s64 avg = cfs_rq->avg_vruntime;
660 long load = cfs_rq->avg_load;
662 if (curr && curr->on_rq) {
663 unsigned long weight = scale_load_down(curr->load.weight);
665 avg += entity_key(cfs_rq, curr) * weight;
670 /* sign flips effective floor / ceil */
673 avg = div_s64(avg, load);
676 return cfs_rq->min_vruntime + avg;
680 * lag_i = S - s_i = w_i * (V - v_i)
682 * However, since V is approximated by the weighted average of all entities it
683 * is possible -- by addition/removal/reweight to the tree -- to move V around
684 * and end up with a larger lag than we started with.
686 * Limit this to either double the slice length with a minimum of TICK_NSEC
687 * since that is the timing granularity.
689 * EEVDF gives the following limit for a steady state system:
691 * -r_max < lag < max(r_max, q)
693 * XXX could add max_slice to the augmented data to track this.
695 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
699 SCHED_WARN_ON(!se->on_rq);
700 lag = avg_vruntime(cfs_rq) - se->vruntime;
702 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
703 se->vlag = clamp(lag, -limit, limit);
707 * Entity is eligible once it received less service than it ought to have,
710 * lag_i = S - s_i = w_i*(V - v_i)
712 * lag_i >= 0 -> V >= v_i
715 * V = ------------------ + v
718 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
720 * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
721 * to the loss in precision caused by the division.
723 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
725 struct sched_entity *curr = cfs_rq->curr;
726 s64 avg = cfs_rq->avg_vruntime;
727 long load = cfs_rq->avg_load;
729 if (curr && curr->on_rq) {
730 unsigned long weight = scale_load_down(curr->load.weight);
732 avg += entity_key(cfs_rq, curr) * weight;
736 return avg >= entity_key(cfs_rq, se) * load;
739 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
741 u64 min_vruntime = cfs_rq->min_vruntime;
743 * open coded max_vruntime() to allow updating avg_vruntime
745 s64 delta = (s64)(vruntime - min_vruntime);
747 avg_vruntime_update(cfs_rq, delta);
748 min_vruntime = vruntime;
753 static void update_min_vruntime(struct cfs_rq *cfs_rq)
755 struct sched_entity *se = __pick_first_entity(cfs_rq);
756 struct sched_entity *curr = cfs_rq->curr;
758 u64 vruntime = cfs_rq->min_vruntime;
762 vruntime = curr->vruntime;
769 vruntime = se->vruntime;
771 vruntime = min_vruntime(vruntime, se->vruntime);
774 /* ensure we never gain time by being placed backwards. */
775 u64_u32_store(cfs_rq->min_vruntime,
776 __update_min_vruntime(cfs_rq, vruntime));
779 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
781 return entity_before(__node_2_se(a), __node_2_se(b));
784 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
786 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
789 struct sched_entity *rse = __node_2_se(node);
790 if (deadline_gt(min_deadline, se, rse))
791 se->min_deadline = rse->min_deadline;
796 * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
798 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
800 u64 old_min_deadline = se->min_deadline;
801 struct rb_node *node = &se->run_node;
803 se->min_deadline = se->deadline;
804 __update_min_deadline(se, node->rb_right);
805 __update_min_deadline(se, node->rb_left);
807 return se->min_deadline == old_min_deadline;
810 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
811 run_node, min_deadline, min_deadline_update);
814 * Enqueue an entity into the rb-tree:
816 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
818 avg_vruntime_add(cfs_rq, se);
819 se->min_deadline = se->deadline;
820 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
821 __entity_less, &min_deadline_cb);
824 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
826 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
828 avg_vruntime_sub(cfs_rq, se);
831 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
833 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
838 return __node_2_se(left);
842 * Earliest Eligible Virtual Deadline First
844 * In order to provide latency guarantees for different request sizes
845 * EEVDF selects the best runnable task from two criteria:
847 * 1) the task must be eligible (must be owed service)
849 * 2) from those tasks that meet 1), we select the one
850 * with the earliest virtual deadline.
852 * We can do this in O(log n) time due to an augmented RB-tree. The
853 * tree keeps the entries sorted on service, but also functions as a
854 * heap based on the deadline by keeping:
856 * se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
858 * Which allows an EDF like search on (sub)trees.
860 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq)
862 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
863 struct sched_entity *curr = cfs_rq->curr;
864 struct sched_entity *best = NULL;
865 struct sched_entity *best_left = NULL;
867 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 * Now we heap search eligible trees for the best (min_)deadline
892 if (!best || deadline_gt(deadline, best, se))
896 * Every se in a left branch is eligible, keep track of the
897 * branch with the best min_deadline
900 struct sched_entity *left = __node_2_se(node->rb_left);
902 if (!best_left || deadline_gt(min_deadline, best_left, left))
906 * min_deadline is in the left branch. rb_left and all
907 * descendants are eligible, so immediately switch to the second
910 if (left->min_deadline == se->min_deadline)
914 /* min_deadline is at this node, no need to look right */
915 if (se->deadline == se->min_deadline)
918 /* else min_deadline is in the right branch. */
919 node = node->rb_right;
923 * We ran into an eligible node which is itself the best.
924 * (Or nr_running == 0 and both are NULL)
926 if (!best_left || (s64)(best_left->min_deadline - best->deadline) > 0)
930 * Now best_left and all of its children are eligible, and we are just
931 * looking for deadline == min_deadline
933 node = &best_left->run_node;
935 struct sched_entity *se = __node_2_se(node);
937 /* min_deadline is the current node */
938 if (se->deadline == se->min_deadline)
941 /* min_deadline is in the left branch */
943 __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
944 node = node->rb_left;
948 /* else min_deadline is in the right branch */
949 node = node->rb_right;
954 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
956 struct sched_entity *se = __pick_eevdf(cfs_rq);
959 struct sched_entity *left = __pick_first_entity(cfs_rq);
961 pr_err("EEVDF scheduling fail, picking leftmost\n");
969 #ifdef CONFIG_SCHED_DEBUG
970 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
972 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
977 return __node_2_se(last);
980 /**************************************************************
981 * Scheduling class statistics methods:
984 int sched_update_scaling(void)
986 unsigned int factor = get_update_sysctl_factor();
988 #define WRT_SYSCTL(name) \
989 (normalized_sysctl_##name = sysctl_##name / (factor))
990 WRT_SYSCTL(sched_base_slice);
998 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1001 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1002 * this is probably good enough.
1004 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1006 if ((s64)(se->vruntime - se->deadline) < 0)
1010 * For EEVDF the virtual time slope is determined by w_i (iow.
1011 * nice) while the request time r_i is determined by
1012 * sysctl_sched_base_slice.
1014 se->slice = sysctl_sched_base_slice;
1017 * EEVDF: vd_i = ve_i + r_i / w_i
1019 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1022 * The task has consumed its request, reschedule.
1024 if (cfs_rq->nr_running > 1) {
1025 resched_curr(rq_of(cfs_rq));
1026 clear_buddies(cfs_rq, se);
1033 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1034 static unsigned long task_h_load(struct task_struct *p);
1035 static unsigned long capacity_of(int cpu);
1037 /* Give new sched_entity start runnable values to heavy its load in infant time */
1038 void init_entity_runnable_average(struct sched_entity *se)
1040 struct sched_avg *sa = &se->avg;
1042 memset(sa, 0, sizeof(*sa));
1045 * Tasks are initialized with full load to be seen as heavy tasks until
1046 * they get a chance to stabilize to their real load level.
1047 * Group entities are initialized with zero load to reflect the fact that
1048 * nothing has been attached to the task group yet.
1050 if (entity_is_task(se))
1051 sa->load_avg = scale_load_down(se->load.weight);
1053 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1057 * With new tasks being created, their initial util_avgs are extrapolated
1058 * based on the cfs_rq's current util_avg:
1060 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1062 * However, in many cases, the above util_avg does not give a desired
1063 * value. Moreover, the sum of the util_avgs may be divergent, such
1064 * as when the series is a harmonic series.
1066 * To solve this problem, we also cap the util_avg of successive tasks to
1067 * only 1/2 of the left utilization budget:
1069 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1071 * where n denotes the nth task and cpu_scale the CPU capacity.
1073 * For example, for a CPU with 1024 of capacity, a simplest series from
1074 * the beginning would be like:
1076 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1077 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1079 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1080 * if util_avg > util_avg_cap.
1082 void post_init_entity_util_avg(struct task_struct *p)
1084 struct sched_entity *se = &p->se;
1085 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1086 struct sched_avg *sa = &se->avg;
1087 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1088 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1090 if (p->sched_class != &fair_sched_class) {
1092 * For !fair tasks do:
1094 update_cfs_rq_load_avg(now, cfs_rq);
1095 attach_entity_load_avg(cfs_rq, se);
1096 switched_from_fair(rq, p);
1098 * such that the next switched_to_fair() has the
1101 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1106 if (cfs_rq->avg.util_avg != 0) {
1107 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
1108 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1110 if (sa->util_avg > cap)
1117 sa->runnable_avg = sa->util_avg;
1120 #else /* !CONFIG_SMP */
1121 void init_entity_runnable_average(struct sched_entity *se)
1124 void post_init_entity_util_avg(struct task_struct *p)
1127 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1130 #endif /* CONFIG_SMP */
1133 * Update the current task's runtime statistics.
1135 static void update_curr(struct cfs_rq *cfs_rq)
1137 struct sched_entity *curr = cfs_rq->curr;
1138 u64 now = rq_clock_task(rq_of(cfs_rq));
1141 if (unlikely(!curr))
1144 delta_exec = now - curr->exec_start;
1145 if (unlikely((s64)delta_exec <= 0))
1148 curr->exec_start = now;
1150 if (schedstat_enabled()) {
1151 struct sched_statistics *stats;
1153 stats = __schedstats_from_se(curr);
1154 __schedstat_set(stats->exec_max,
1155 max(delta_exec, stats->exec_max));
1158 curr->sum_exec_runtime += delta_exec;
1159 schedstat_add(cfs_rq->exec_clock, delta_exec);
1161 curr->vruntime += calc_delta_fair(delta_exec, curr);
1162 update_deadline(cfs_rq, curr);
1163 update_min_vruntime(cfs_rq);
1165 if (entity_is_task(curr)) {
1166 struct task_struct *curtask = task_of(curr);
1168 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1169 cgroup_account_cputime(curtask, delta_exec);
1170 account_group_exec_runtime(curtask, delta_exec);
1173 account_cfs_rq_runtime(cfs_rq, delta_exec);
1176 static void update_curr_fair(struct rq *rq)
1178 update_curr(cfs_rq_of(&rq->curr->se));
1182 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1184 struct sched_statistics *stats;
1185 struct task_struct *p = NULL;
1187 if (!schedstat_enabled())
1190 stats = __schedstats_from_se(se);
1192 if (entity_is_task(se))
1195 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1199 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1201 struct sched_statistics *stats;
1202 struct task_struct *p = NULL;
1204 if (!schedstat_enabled())
1207 stats = __schedstats_from_se(se);
1210 * When the sched_schedstat changes from 0 to 1, some sched se
1211 * maybe already in the runqueue, the se->statistics.wait_start
1212 * will be 0.So it will let the delta wrong. We need to avoid this
1215 if (unlikely(!schedstat_val(stats->wait_start)))
1218 if (entity_is_task(se))
1221 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1225 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1227 struct sched_statistics *stats;
1228 struct task_struct *tsk = NULL;
1230 if (!schedstat_enabled())
1233 stats = __schedstats_from_se(se);
1235 if (entity_is_task(se))
1238 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1242 * Task is being enqueued - update stats:
1245 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1247 if (!schedstat_enabled())
1251 * Are we enqueueing a waiting task? (for current tasks
1252 * a dequeue/enqueue event is a NOP)
1254 if (se != cfs_rq->curr)
1255 update_stats_wait_start_fair(cfs_rq, se);
1257 if (flags & ENQUEUE_WAKEUP)
1258 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1262 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1265 if (!schedstat_enabled())
1269 * Mark the end of the wait period if dequeueing a
1272 if (se != cfs_rq->curr)
1273 update_stats_wait_end_fair(cfs_rq, se);
1275 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1276 struct task_struct *tsk = task_of(se);
1279 /* XXX racy against TTWU */
1280 state = READ_ONCE(tsk->__state);
1281 if (state & TASK_INTERRUPTIBLE)
1282 __schedstat_set(tsk->stats.sleep_start,
1283 rq_clock(rq_of(cfs_rq)));
1284 if (state & TASK_UNINTERRUPTIBLE)
1285 __schedstat_set(tsk->stats.block_start,
1286 rq_clock(rq_of(cfs_rq)));
1291 * We are picking a new current task - update its stats:
1294 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1297 * We are starting a new run period:
1299 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1302 /**************************************************
1303 * Scheduling class queueing methods:
1306 static inline bool is_core_idle(int cpu)
1308 #ifdef CONFIG_SCHED_SMT
1311 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1315 if (!idle_cpu(sibling))
1324 #define NUMA_IMBALANCE_MIN 2
1327 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1330 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1331 * threshold. Above this threshold, individual tasks may be contending
1332 * for both memory bandwidth and any shared HT resources. This is an
1333 * approximation as the number of running tasks may not be related to
1334 * the number of busy CPUs due to sched_setaffinity.
1336 if (dst_running > imb_numa_nr)
1340 * Allow a small imbalance based on a simple pair of communicating
1341 * tasks that remain local when the destination is lightly loaded.
1343 if (imbalance <= NUMA_IMBALANCE_MIN)
1348 #endif /* CONFIG_NUMA */
1350 #ifdef CONFIG_NUMA_BALANCING
1352 * Approximate time to scan a full NUMA task in ms. The task scan period is
1353 * calculated based on the tasks virtual memory size and
1354 * numa_balancing_scan_size.
1356 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1357 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1359 /* Portion of address space to scan in MB */
1360 unsigned int sysctl_numa_balancing_scan_size = 256;
1362 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1363 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1365 /* The page with hint page fault latency < threshold in ms is considered hot */
1366 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1369 refcount_t refcount;
1371 spinlock_t lock; /* nr_tasks, tasks */
1376 struct rcu_head rcu;
1377 unsigned long total_faults;
1378 unsigned long max_faults_cpu;
1380 * faults[] array is split into two regions: faults_mem and faults_cpu.
1382 * Faults_cpu is used to decide whether memory should move
1383 * towards the CPU. As a consequence, these stats are weighted
1384 * more by CPU use than by memory faults.
1386 unsigned long faults[];
1390 * For functions that can be called in multiple contexts that permit reading
1391 * ->numa_group (see struct task_struct for locking rules).
1393 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1395 return rcu_dereference_check(p->numa_group, p == current ||
1396 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1399 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1401 return rcu_dereference_protected(p->numa_group, p == current);
1404 static inline unsigned long group_faults_priv(struct numa_group *ng);
1405 static inline unsigned long group_faults_shared(struct numa_group *ng);
1407 static unsigned int task_nr_scan_windows(struct task_struct *p)
1409 unsigned long rss = 0;
1410 unsigned long nr_scan_pages;
1413 * Calculations based on RSS as non-present and empty pages are skipped
1414 * by the PTE scanner and NUMA hinting faults should be trapped based
1417 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1418 rss = get_mm_rss(p->mm);
1420 rss = nr_scan_pages;
1422 rss = round_up(rss, nr_scan_pages);
1423 return rss / nr_scan_pages;
1426 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1427 #define MAX_SCAN_WINDOW 2560
1429 static unsigned int task_scan_min(struct task_struct *p)
1431 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1432 unsigned int scan, floor;
1433 unsigned int windows = 1;
1435 if (scan_size < MAX_SCAN_WINDOW)
1436 windows = MAX_SCAN_WINDOW / scan_size;
1437 floor = 1000 / windows;
1439 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1440 return max_t(unsigned int, floor, scan);
1443 static unsigned int task_scan_start(struct task_struct *p)
1445 unsigned long smin = task_scan_min(p);
1446 unsigned long period = smin;
1447 struct numa_group *ng;
1449 /* Scale the maximum scan period with the amount of shared memory. */
1451 ng = rcu_dereference(p->numa_group);
1453 unsigned long shared = group_faults_shared(ng);
1454 unsigned long private = group_faults_priv(ng);
1456 period *= refcount_read(&ng->refcount);
1457 period *= shared + 1;
1458 period /= private + shared + 1;
1462 return max(smin, period);
1465 static unsigned int task_scan_max(struct task_struct *p)
1467 unsigned long smin = task_scan_min(p);
1469 struct numa_group *ng;
1471 /* Watch for min being lower than max due to floor calculations */
1472 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1474 /* Scale the maximum scan period with the amount of shared memory. */
1475 ng = deref_curr_numa_group(p);
1477 unsigned long shared = group_faults_shared(ng);
1478 unsigned long private = group_faults_priv(ng);
1479 unsigned long period = smax;
1481 period *= refcount_read(&ng->refcount);
1482 period *= shared + 1;
1483 period /= private + shared + 1;
1485 smax = max(smax, period);
1488 return max(smin, smax);
1491 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1493 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1494 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1497 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1499 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1500 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1503 /* Shared or private faults. */
1504 #define NR_NUMA_HINT_FAULT_TYPES 2
1506 /* Memory and CPU locality */
1507 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1509 /* Averaged statistics, and temporary buffers. */
1510 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1512 pid_t task_numa_group_id(struct task_struct *p)
1514 struct numa_group *ng;
1518 ng = rcu_dereference(p->numa_group);
1527 * The averaged statistics, shared & private, memory & CPU,
1528 * occupy the first half of the array. The second half of the
1529 * array is for current counters, which are averaged into the
1530 * first set by task_numa_placement.
1532 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1534 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1537 static inline unsigned long task_faults(struct task_struct *p, int nid)
1539 if (!p->numa_faults)
1542 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1543 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1546 static inline unsigned long group_faults(struct task_struct *p, int nid)
1548 struct numa_group *ng = deref_task_numa_group(p);
1553 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1554 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1557 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1559 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1560 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1563 static inline unsigned long group_faults_priv(struct numa_group *ng)
1565 unsigned long faults = 0;
1568 for_each_online_node(node) {
1569 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1575 static inline unsigned long group_faults_shared(struct numa_group *ng)
1577 unsigned long faults = 0;
1580 for_each_online_node(node) {
1581 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1588 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1589 * considered part of a numa group's pseudo-interleaving set. Migrations
1590 * between these nodes are slowed down, to allow things to settle down.
1592 #define ACTIVE_NODE_FRACTION 3
1594 static bool numa_is_active_node(int nid, struct numa_group *ng)
1596 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1599 /* Handle placement on systems where not all nodes are directly connected. */
1600 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1601 int lim_dist, bool task)
1603 unsigned long score = 0;
1607 * All nodes are directly connected, and the same distance
1608 * from each other. No need for fancy placement algorithms.
1610 if (sched_numa_topology_type == NUMA_DIRECT)
1613 /* sched_max_numa_distance may be changed in parallel. */
1614 max_dist = READ_ONCE(sched_max_numa_distance);
1616 * This code is called for each node, introducing N^2 complexity,
1617 * which should be ok given the number of nodes rarely exceeds 8.
1619 for_each_online_node(node) {
1620 unsigned long faults;
1621 int dist = node_distance(nid, node);
1624 * The furthest away nodes in the system are not interesting
1625 * for placement; nid was already counted.
1627 if (dist >= max_dist || node == nid)
1631 * On systems with a backplane NUMA topology, compare groups
1632 * of nodes, and move tasks towards the group with the most
1633 * memory accesses. When comparing two nodes at distance
1634 * "hoplimit", only nodes closer by than "hoplimit" are part
1635 * of each group. Skip other nodes.
1637 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1640 /* Add up the faults from nearby nodes. */
1642 faults = task_faults(p, node);
1644 faults = group_faults(p, node);
1647 * On systems with a glueless mesh NUMA topology, there are
1648 * no fixed "groups of nodes". Instead, nodes that are not
1649 * directly connected bounce traffic through intermediate
1650 * nodes; a numa_group can occupy any set of nodes.
1651 * The further away a node is, the less the faults count.
1652 * This seems to result in good task placement.
1654 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1655 faults *= (max_dist - dist);
1656 faults /= (max_dist - LOCAL_DISTANCE);
1666 * These return the fraction of accesses done by a particular task, or
1667 * task group, on a particular numa node. The group weight is given a
1668 * larger multiplier, in order to group tasks together that are almost
1669 * evenly spread out between numa nodes.
1671 static inline unsigned long task_weight(struct task_struct *p, int nid,
1674 unsigned long faults, total_faults;
1676 if (!p->numa_faults)
1679 total_faults = p->total_numa_faults;
1684 faults = task_faults(p, nid);
1685 faults += score_nearby_nodes(p, nid, dist, true);
1687 return 1000 * faults / total_faults;
1690 static inline unsigned long group_weight(struct task_struct *p, int nid,
1693 struct numa_group *ng = deref_task_numa_group(p);
1694 unsigned long faults, total_faults;
1699 total_faults = ng->total_faults;
1704 faults = group_faults(p, nid);
1705 faults += score_nearby_nodes(p, nid, dist, false);
1707 return 1000 * faults / total_faults;
1711 * If memory tiering mode is enabled, cpupid of slow memory page is
1712 * used to record scan time instead of CPU and PID. When tiering mode
1713 * is disabled at run time, the scan time (in cpupid) will be
1714 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1715 * access out of array bound.
1717 static inline bool cpupid_valid(int cpupid)
1719 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1723 * For memory tiering mode, if there are enough free pages (more than
1724 * enough watermark defined here) in fast memory node, to take full
1725 * advantage of fast memory capacity, all recently accessed slow
1726 * memory pages will be migrated to fast memory node without
1727 * considering hot threshold.
1729 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1732 unsigned long enough_wmark;
1734 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1735 pgdat->node_present_pages >> 4);
1736 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1737 struct zone *zone = pgdat->node_zones + z;
1739 if (!populated_zone(zone))
1742 if (zone_watermark_ok(zone, 0,
1743 wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1751 * For memory tiering mode, when page tables are scanned, the scan
1752 * time will be recorded in struct page in addition to make page
1753 * PROT_NONE for slow memory page. So when the page is accessed, in
1754 * hint page fault handler, the hint page fault latency is calculated
1757 * hint page fault latency = hint page fault time - scan time
1759 * The smaller the hint page fault latency, the higher the possibility
1760 * for the page to be hot.
1762 static int numa_hint_fault_latency(struct folio *folio)
1764 int last_time, time;
1766 time = jiffies_to_msecs(jiffies);
1767 last_time = folio_xchg_access_time(folio, time);
1769 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1773 * For memory tiering mode, too high promotion/demotion throughput may
1774 * hurt application latency. So we provide a mechanism to rate limit
1775 * the number of pages that are tried to be promoted.
1777 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1778 unsigned long rate_limit, int nr)
1780 unsigned long nr_cand;
1781 unsigned int now, start;
1783 now = jiffies_to_msecs(jiffies);
1784 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1785 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1786 start = pgdat->nbp_rl_start;
1787 if (now - start > MSEC_PER_SEC &&
1788 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1789 pgdat->nbp_rl_nr_cand = nr_cand;
1790 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1795 #define NUMA_MIGRATION_ADJUST_STEPS 16
1797 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1798 unsigned long rate_limit,
1799 unsigned int ref_th)
1801 unsigned int now, start, th_period, unit_th, th;
1802 unsigned long nr_cand, ref_cand, diff_cand;
1804 now = jiffies_to_msecs(jiffies);
1805 th_period = sysctl_numa_balancing_scan_period_max;
1806 start = pgdat->nbp_th_start;
1807 if (now - start > th_period &&
1808 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1809 ref_cand = rate_limit *
1810 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1811 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1812 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1813 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1814 th = pgdat->nbp_threshold ? : ref_th;
1815 if (diff_cand > ref_cand * 11 / 10)
1816 th = max(th - unit_th, unit_th);
1817 else if (diff_cand < ref_cand * 9 / 10)
1818 th = min(th + unit_th, ref_th * 2);
1819 pgdat->nbp_th_nr_cand = nr_cand;
1820 pgdat->nbp_threshold = th;
1824 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1825 int src_nid, int dst_cpu)
1827 struct numa_group *ng = deref_curr_numa_group(p);
1828 int dst_nid = cpu_to_node(dst_cpu);
1829 int last_cpupid, this_cpupid;
1832 * The pages in slow memory node should be migrated according
1833 * to hot/cold instead of private/shared.
1835 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1836 !node_is_toptier(src_nid)) {
1837 struct pglist_data *pgdat;
1838 unsigned long rate_limit;
1839 unsigned int latency, th, def_th;
1841 pgdat = NODE_DATA(dst_nid);
1842 if (pgdat_free_space_enough(pgdat)) {
1843 /* workload changed, reset hot threshold */
1844 pgdat->nbp_threshold = 0;
1848 def_th = sysctl_numa_balancing_hot_threshold;
1849 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1851 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1853 th = pgdat->nbp_threshold ? : def_th;
1854 latency = numa_hint_fault_latency(folio);
1858 return !numa_promotion_rate_limit(pgdat, rate_limit,
1859 folio_nr_pages(folio));
1862 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1863 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
1865 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1866 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1870 * Allow first faults or private faults to migrate immediately early in
1871 * the lifetime of a task. The magic number 4 is based on waiting for
1872 * two full passes of the "multi-stage node selection" test that is
1875 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1876 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1880 * Multi-stage node selection is used in conjunction with a periodic
1881 * migration fault to build a temporal task<->page relation. By using
1882 * a two-stage filter we remove short/unlikely relations.
1884 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1885 * a task's usage of a particular page (n_p) per total usage of this
1886 * page (n_t) (in a given time-span) to a probability.
1888 * Our periodic faults will sample this probability and getting the
1889 * same result twice in a row, given these samples are fully
1890 * independent, is then given by P(n)^2, provided our sample period
1891 * is sufficiently short compared to the usage pattern.
1893 * This quadric squishes small probabilities, making it less likely we
1894 * act on an unlikely task<->page relation.
1896 if (!cpupid_pid_unset(last_cpupid) &&
1897 cpupid_to_nid(last_cpupid) != dst_nid)
1900 /* Always allow migrate on private faults */
1901 if (cpupid_match_pid(p, last_cpupid))
1904 /* A shared fault, but p->numa_group has not been set up yet. */
1909 * Destination node is much more heavily used than the source
1910 * node? Allow migration.
1912 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1913 ACTIVE_NODE_FRACTION)
1917 * Distribute memory according to CPU & memory use on each node,
1918 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1920 * faults_cpu(dst) 3 faults_cpu(src)
1921 * --------------- * - > ---------------
1922 * faults_mem(dst) 4 faults_mem(src)
1924 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1925 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1929 * 'numa_type' describes the node at the moment of load balancing.
1932 /* The node has spare capacity that can be used to run more tasks. */
1935 * The node is fully used and the tasks don't compete for more CPU
1936 * cycles. Nevertheless, some tasks might wait before running.
1940 * The node is overloaded and can't provide expected CPU cycles to all
1946 /* Cached statistics for all CPUs within a node */
1949 unsigned long runnable;
1951 /* Total compute capacity of CPUs on a node */
1952 unsigned long compute_capacity;
1953 unsigned int nr_running;
1954 unsigned int weight;
1955 enum numa_type node_type;
1959 struct task_numa_env {
1960 struct task_struct *p;
1962 int src_cpu, src_nid;
1963 int dst_cpu, dst_nid;
1966 struct numa_stats src_stats, dst_stats;
1971 struct task_struct *best_task;
1976 static unsigned long cpu_load(struct rq *rq);
1977 static unsigned long cpu_runnable(struct rq *rq);
1980 numa_type numa_classify(unsigned int imbalance_pct,
1981 struct numa_stats *ns)
1983 if ((ns->nr_running > ns->weight) &&
1984 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
1985 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
1986 return node_overloaded;
1988 if ((ns->nr_running < ns->weight) ||
1989 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
1990 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
1991 return node_has_spare;
1993 return node_fully_busy;
1996 #ifdef CONFIG_SCHED_SMT
1997 /* Forward declarations of select_idle_sibling helpers */
1998 static inline bool test_idle_cores(int cpu);
1999 static inline int numa_idle_core(int idle_core, int cpu)
2001 if (!static_branch_likely(&sched_smt_present) ||
2002 idle_core >= 0 || !test_idle_cores(cpu))
2006 * Prefer cores instead of packing HT siblings
2007 * and triggering future load balancing.
2009 if (is_core_idle(cpu))
2015 static inline int numa_idle_core(int idle_core, int cpu)
2022 * Gather all necessary information to make NUMA balancing placement
2023 * decisions that are compatible with standard load balancer. This
2024 * borrows code and logic from update_sg_lb_stats but sharing a
2025 * common implementation is impractical.
2027 static void update_numa_stats(struct task_numa_env *env,
2028 struct numa_stats *ns, int nid,
2031 int cpu, idle_core = -1;
2033 memset(ns, 0, sizeof(*ns));
2037 for_each_cpu(cpu, cpumask_of_node(nid)) {
2038 struct rq *rq = cpu_rq(cpu);
2040 ns->load += cpu_load(rq);
2041 ns->runnable += cpu_runnable(rq);
2042 ns->util += cpu_util_cfs(cpu);
2043 ns->nr_running += rq->cfs.h_nr_running;
2044 ns->compute_capacity += capacity_of(cpu);
2046 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2047 if (READ_ONCE(rq->numa_migrate_on) ||
2048 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2051 if (ns->idle_cpu == -1)
2054 idle_core = numa_idle_core(idle_core, cpu);
2059 ns->weight = cpumask_weight(cpumask_of_node(nid));
2061 ns->node_type = numa_classify(env->imbalance_pct, ns);
2064 ns->idle_cpu = idle_core;
2067 static void task_numa_assign(struct task_numa_env *env,
2068 struct task_struct *p, long imp)
2070 struct rq *rq = cpu_rq(env->dst_cpu);
2072 /* Check if run-queue part of active NUMA balance. */
2073 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2075 int start = env->dst_cpu;
2077 /* Find alternative idle CPU. */
2078 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2079 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2080 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2085 rq = cpu_rq(env->dst_cpu);
2086 if (!xchg(&rq->numa_migrate_on, 1))
2090 /* Failed to find an alternative idle CPU */
2096 * Clear previous best_cpu/rq numa-migrate flag, since task now
2097 * found a better CPU to move/swap.
2099 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2100 rq = cpu_rq(env->best_cpu);
2101 WRITE_ONCE(rq->numa_migrate_on, 0);
2105 put_task_struct(env->best_task);
2110 env->best_imp = imp;
2111 env->best_cpu = env->dst_cpu;
2114 static bool load_too_imbalanced(long src_load, long dst_load,
2115 struct task_numa_env *env)
2118 long orig_src_load, orig_dst_load;
2119 long src_capacity, dst_capacity;
2122 * The load is corrected for the CPU capacity available on each node.
2125 * ------------ vs ---------
2126 * src_capacity dst_capacity
2128 src_capacity = env->src_stats.compute_capacity;
2129 dst_capacity = env->dst_stats.compute_capacity;
2131 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2133 orig_src_load = env->src_stats.load;
2134 orig_dst_load = env->dst_stats.load;
2136 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2138 /* Would this change make things worse? */
2139 return (imb > old_imb);
2143 * Maximum NUMA importance can be 1998 (2*999);
2144 * SMALLIMP @ 30 would be close to 1998/64.
2145 * Used to deter task migration.
2150 * This checks if the overall compute and NUMA accesses of the system would
2151 * be improved if the source tasks was migrated to the target dst_cpu taking
2152 * into account that it might be best if task running on the dst_cpu should
2153 * be exchanged with the source task
2155 static bool task_numa_compare(struct task_numa_env *env,
2156 long taskimp, long groupimp, bool maymove)
2158 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2159 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2160 long imp = p_ng ? groupimp : taskimp;
2161 struct task_struct *cur;
2162 long src_load, dst_load;
2163 int dist = env->dist;
2166 bool stopsearch = false;
2168 if (READ_ONCE(dst_rq->numa_migrate_on))
2172 cur = rcu_dereference(dst_rq->curr);
2173 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2177 * Because we have preemption enabled we can get migrated around and
2178 * end try selecting ourselves (current == env->p) as a swap candidate.
2180 if (cur == env->p) {
2186 if (maymove && moveimp >= env->best_imp)
2192 /* Skip this swap candidate if cannot move to the source cpu. */
2193 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2197 * Skip this swap candidate if it is not moving to its preferred
2198 * node and the best task is.
2200 if (env->best_task &&
2201 env->best_task->numa_preferred_nid == env->src_nid &&
2202 cur->numa_preferred_nid != env->src_nid) {
2207 * "imp" is the fault differential for the source task between the
2208 * source and destination node. Calculate the total differential for
2209 * the source task and potential destination task. The more negative
2210 * the value is, the more remote accesses that would be expected to
2211 * be incurred if the tasks were swapped.
2213 * If dst and source tasks are in the same NUMA group, or not
2214 * in any group then look only at task weights.
2216 cur_ng = rcu_dereference(cur->numa_group);
2217 if (cur_ng == p_ng) {
2219 * Do not swap within a group or between tasks that have
2220 * no group if there is spare capacity. Swapping does
2221 * not address the load imbalance and helps one task at
2222 * the cost of punishing another.
2224 if (env->dst_stats.node_type == node_has_spare)
2227 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2228 task_weight(cur, env->dst_nid, dist);
2230 * Add some hysteresis to prevent swapping the
2231 * tasks within a group over tiny differences.
2237 * Compare the group weights. If a task is all by itself
2238 * (not part of a group), use the task weight instead.
2241 imp += group_weight(cur, env->src_nid, dist) -
2242 group_weight(cur, env->dst_nid, dist);
2244 imp += task_weight(cur, env->src_nid, dist) -
2245 task_weight(cur, env->dst_nid, dist);
2248 /* Discourage picking a task already on its preferred node */
2249 if (cur->numa_preferred_nid == env->dst_nid)
2253 * Encourage picking a task that moves to its preferred node.
2254 * This potentially makes imp larger than it's maximum of
2255 * 1998 (see SMALLIMP and task_weight for why) but in this
2256 * case, it does not matter.
2258 if (cur->numa_preferred_nid == env->src_nid)
2261 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2268 * Prefer swapping with a task moving to its preferred node over a
2271 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2272 env->best_task->numa_preferred_nid != env->src_nid) {
2277 * If the NUMA importance is less than SMALLIMP,
2278 * task migration might only result in ping pong
2279 * of tasks and also hurt performance due to cache
2282 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2286 * In the overloaded case, try and keep the load balanced.
2288 load = task_h_load(env->p) - task_h_load(cur);
2292 dst_load = env->dst_stats.load + load;
2293 src_load = env->src_stats.load - load;
2295 if (load_too_imbalanced(src_load, dst_load, env))
2299 /* Evaluate an idle CPU for a task numa move. */
2301 int cpu = env->dst_stats.idle_cpu;
2303 /* Nothing cached so current CPU went idle since the search. */
2308 * If the CPU is no longer truly idle and the previous best CPU
2309 * is, keep using it.
2311 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2312 idle_cpu(env->best_cpu)) {
2313 cpu = env->best_cpu;
2319 task_numa_assign(env, cur, imp);
2322 * If a move to idle is allowed because there is capacity or load
2323 * balance improves then stop the search. While a better swap
2324 * candidate may exist, a search is not free.
2326 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2330 * If a swap candidate must be identified and the current best task
2331 * moves its preferred node then stop the search.
2333 if (!maymove && env->best_task &&
2334 env->best_task->numa_preferred_nid == env->src_nid) {
2343 static void task_numa_find_cpu(struct task_numa_env *env,
2344 long taskimp, long groupimp)
2346 bool maymove = false;
2350 * If dst node has spare capacity, then check if there is an
2351 * imbalance that would be overruled by the load balancer.
2353 if (env->dst_stats.node_type == node_has_spare) {
2354 unsigned int imbalance;
2355 int src_running, dst_running;
2358 * Would movement cause an imbalance? Note that if src has
2359 * more running tasks that the imbalance is ignored as the
2360 * move improves the imbalance from the perspective of the
2361 * CPU load balancer.
2363 src_running = env->src_stats.nr_running - 1;
2364 dst_running = env->dst_stats.nr_running + 1;
2365 imbalance = max(0, dst_running - src_running);
2366 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2369 /* Use idle CPU if there is no imbalance */
2372 if (env->dst_stats.idle_cpu >= 0) {
2373 env->dst_cpu = env->dst_stats.idle_cpu;
2374 task_numa_assign(env, NULL, 0);
2379 long src_load, dst_load, load;
2381 * If the improvement from just moving env->p direction is better
2382 * than swapping tasks around, check if a move is possible.
2384 load = task_h_load(env->p);
2385 dst_load = env->dst_stats.load + load;
2386 src_load = env->src_stats.load - load;
2387 maymove = !load_too_imbalanced(src_load, dst_load, env);
2390 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2391 /* Skip this CPU if the source task cannot migrate */
2392 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2396 if (task_numa_compare(env, taskimp, groupimp, maymove))
2401 static int task_numa_migrate(struct task_struct *p)
2403 struct task_numa_env env = {
2406 .src_cpu = task_cpu(p),
2407 .src_nid = task_node(p),
2409 .imbalance_pct = 112,
2415 unsigned long taskweight, groupweight;
2416 struct sched_domain *sd;
2417 long taskimp, groupimp;
2418 struct numa_group *ng;
2423 * Pick the lowest SD_NUMA domain, as that would have the smallest
2424 * imbalance and would be the first to start moving tasks about.
2426 * And we want to avoid any moving of tasks about, as that would create
2427 * random movement of tasks -- counter the numa conditions we're trying
2431 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2433 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2434 env.imb_numa_nr = sd->imb_numa_nr;
2439 * Cpusets can break the scheduler domain tree into smaller
2440 * balance domains, some of which do not cross NUMA boundaries.
2441 * Tasks that are "trapped" in such domains cannot be migrated
2442 * elsewhere, so there is no point in (re)trying.
2444 if (unlikely(!sd)) {
2445 sched_setnuma(p, task_node(p));
2449 env.dst_nid = p->numa_preferred_nid;
2450 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2451 taskweight = task_weight(p, env.src_nid, dist);
2452 groupweight = group_weight(p, env.src_nid, dist);
2453 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2454 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2455 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2456 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2458 /* Try to find a spot on the preferred nid. */
2459 task_numa_find_cpu(&env, taskimp, groupimp);
2462 * Look at other nodes in these cases:
2463 * - there is no space available on the preferred_nid
2464 * - the task is part of a numa_group that is interleaved across
2465 * multiple NUMA nodes; in order to better consolidate the group,
2466 * we need to check other locations.
2468 ng = deref_curr_numa_group(p);
2469 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2470 for_each_node_state(nid, N_CPU) {
2471 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2474 dist = node_distance(env.src_nid, env.dst_nid);
2475 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2477 taskweight = task_weight(p, env.src_nid, dist);
2478 groupweight = group_weight(p, env.src_nid, dist);
2481 /* Only consider nodes where both task and groups benefit */
2482 taskimp = task_weight(p, nid, dist) - taskweight;
2483 groupimp = group_weight(p, nid, dist) - groupweight;
2484 if (taskimp < 0 && groupimp < 0)
2489 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2490 task_numa_find_cpu(&env, taskimp, groupimp);
2495 * If the task is part of a workload that spans multiple NUMA nodes,
2496 * and is migrating into one of the workload's active nodes, remember
2497 * this node as the task's preferred numa node, so the workload can
2499 * A task that migrated to a second choice node will be better off
2500 * trying for a better one later. Do not set the preferred node here.
2503 if (env.best_cpu == -1)
2506 nid = cpu_to_node(env.best_cpu);
2508 if (nid != p->numa_preferred_nid)
2509 sched_setnuma(p, nid);
2512 /* No better CPU than the current one was found. */
2513 if (env.best_cpu == -1) {
2514 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2518 best_rq = cpu_rq(env.best_cpu);
2519 if (env.best_task == NULL) {
2520 ret = migrate_task_to(p, env.best_cpu);
2521 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2523 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2527 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2528 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2531 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2532 put_task_struct(env.best_task);
2536 /* Attempt to migrate a task to a CPU on the preferred node. */
2537 static void numa_migrate_preferred(struct task_struct *p)
2539 unsigned long interval = HZ;
2541 /* This task has no NUMA fault statistics yet */
2542 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2545 /* Periodically retry migrating the task to the preferred node */
2546 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2547 p->numa_migrate_retry = jiffies + interval;
2549 /* Success if task is already running on preferred CPU */
2550 if (task_node(p) == p->numa_preferred_nid)
2553 /* Otherwise, try migrate to a CPU on the preferred node */
2554 task_numa_migrate(p);
2558 * Find out how many nodes the workload is actively running on. Do this by
2559 * tracking the nodes from which NUMA hinting faults are triggered. This can
2560 * be different from the set of nodes where the workload's memory is currently
2563 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2565 unsigned long faults, max_faults = 0;
2566 int nid, active_nodes = 0;
2568 for_each_node_state(nid, N_CPU) {
2569 faults = group_faults_cpu(numa_group, nid);
2570 if (faults > max_faults)
2571 max_faults = faults;
2574 for_each_node_state(nid, N_CPU) {
2575 faults = group_faults_cpu(numa_group, nid);
2576 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2580 numa_group->max_faults_cpu = max_faults;
2581 numa_group->active_nodes = active_nodes;
2585 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2586 * increments. The more local the fault statistics are, the higher the scan
2587 * period will be for the next scan window. If local/(local+remote) ratio is
2588 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2589 * the scan period will decrease. Aim for 70% local accesses.
2591 #define NUMA_PERIOD_SLOTS 10
2592 #define NUMA_PERIOD_THRESHOLD 7
2595 * Increase the scan period (slow down scanning) if the majority of
2596 * our memory is already on our local node, or if the majority of
2597 * the page accesses are shared with other processes.
2598 * Otherwise, decrease the scan period.
2600 static void update_task_scan_period(struct task_struct *p,
2601 unsigned long shared, unsigned long private)
2603 unsigned int period_slot;
2604 int lr_ratio, ps_ratio;
2607 unsigned long remote = p->numa_faults_locality[0];
2608 unsigned long local = p->numa_faults_locality[1];
2611 * If there were no record hinting faults then either the task is
2612 * completely idle or all activity is in areas that are not of interest
2613 * to automatic numa balancing. Related to that, if there were failed
2614 * migration then it implies we are migrating too quickly or the local
2615 * node is overloaded. In either case, scan slower
2617 if (local + shared == 0 || p->numa_faults_locality[2]) {
2618 p->numa_scan_period = min(p->numa_scan_period_max,
2619 p->numa_scan_period << 1);
2621 p->mm->numa_next_scan = jiffies +
2622 msecs_to_jiffies(p->numa_scan_period);
2628 * Prepare to scale scan period relative to the current period.
2629 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2630 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2631 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2633 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2634 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2635 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2637 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2639 * Most memory accesses are local. There is no need to
2640 * do fast NUMA scanning, since memory is already local.
2642 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2645 diff = slot * period_slot;
2646 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2648 * Most memory accesses are shared with other tasks.
2649 * There is no point in continuing fast NUMA scanning,
2650 * since other tasks may just move the memory elsewhere.
2652 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2655 diff = slot * period_slot;
2658 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2659 * yet they are not on the local NUMA node. Speed up
2660 * NUMA scanning to get the memory moved over.
2662 int ratio = max(lr_ratio, ps_ratio);
2663 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2666 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2667 task_scan_min(p), task_scan_max(p));
2668 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2672 * Get the fraction of time the task has been running since the last
2673 * NUMA placement cycle. The scheduler keeps similar statistics, but
2674 * decays those on a 32ms period, which is orders of magnitude off
2675 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2676 * stats only if the task is so new there are no NUMA statistics yet.
2678 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2680 u64 runtime, delta, now;
2681 /* Use the start of this time slice to avoid calculations. */
2682 now = p->se.exec_start;
2683 runtime = p->se.sum_exec_runtime;
2685 if (p->last_task_numa_placement) {
2686 delta = runtime - p->last_sum_exec_runtime;
2687 *period = now - p->last_task_numa_placement;
2689 /* Avoid time going backwards, prevent potential divide error: */
2690 if (unlikely((s64)*period < 0))
2693 delta = p->se.avg.load_sum;
2694 *period = LOAD_AVG_MAX;
2697 p->last_sum_exec_runtime = runtime;
2698 p->last_task_numa_placement = now;
2704 * Determine the preferred nid for a task in a numa_group. This needs to
2705 * be done in a way that produces consistent results with group_weight,
2706 * otherwise workloads might not converge.
2708 static int preferred_group_nid(struct task_struct *p, int nid)
2713 /* Direct connections between all NUMA nodes. */
2714 if (sched_numa_topology_type == NUMA_DIRECT)
2718 * On a system with glueless mesh NUMA topology, group_weight
2719 * scores nodes according to the number of NUMA hinting faults on
2720 * both the node itself, and on nearby nodes.
2722 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2723 unsigned long score, max_score = 0;
2724 int node, max_node = nid;
2726 dist = sched_max_numa_distance;
2728 for_each_node_state(node, N_CPU) {
2729 score = group_weight(p, node, dist);
2730 if (score > max_score) {
2739 * Finding the preferred nid in a system with NUMA backplane
2740 * interconnect topology is more involved. The goal is to locate
2741 * tasks from numa_groups near each other in the system, and
2742 * untangle workloads from different sides of the system. This requires
2743 * searching down the hierarchy of node groups, recursively searching
2744 * inside the highest scoring group of nodes. The nodemask tricks
2745 * keep the complexity of the search down.
2747 nodes = node_states[N_CPU];
2748 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2749 unsigned long max_faults = 0;
2750 nodemask_t max_group = NODE_MASK_NONE;
2753 /* Are there nodes at this distance from each other? */
2754 if (!find_numa_distance(dist))
2757 for_each_node_mask(a, nodes) {
2758 unsigned long faults = 0;
2759 nodemask_t this_group;
2760 nodes_clear(this_group);
2762 /* Sum group's NUMA faults; includes a==b case. */
2763 for_each_node_mask(b, nodes) {
2764 if (node_distance(a, b) < dist) {
2765 faults += group_faults(p, b);
2766 node_set(b, this_group);
2767 node_clear(b, nodes);
2771 /* Remember the top group. */
2772 if (faults > max_faults) {
2773 max_faults = faults;
2774 max_group = this_group;
2776 * subtle: at the smallest distance there is
2777 * just one node left in each "group", the
2778 * winner is the preferred nid.
2783 /* Next round, evaluate the nodes within max_group. */
2791 static void task_numa_placement(struct task_struct *p)
2793 int seq, nid, max_nid = NUMA_NO_NODE;
2794 unsigned long max_faults = 0;
2795 unsigned long fault_types[2] = { 0, 0 };
2796 unsigned long total_faults;
2797 u64 runtime, period;
2798 spinlock_t *group_lock = NULL;
2799 struct numa_group *ng;
2802 * The p->mm->numa_scan_seq field gets updated without
2803 * exclusive access. Use READ_ONCE() here to ensure
2804 * that the field is read in a single access:
2806 seq = READ_ONCE(p->mm->numa_scan_seq);
2807 if (p->numa_scan_seq == seq)
2809 p->numa_scan_seq = seq;
2810 p->numa_scan_period_max = task_scan_max(p);
2812 total_faults = p->numa_faults_locality[0] +
2813 p->numa_faults_locality[1];
2814 runtime = numa_get_avg_runtime(p, &period);
2816 /* If the task is part of a group prevent parallel updates to group stats */
2817 ng = deref_curr_numa_group(p);
2819 group_lock = &ng->lock;
2820 spin_lock_irq(group_lock);
2823 /* Find the node with the highest number of faults */
2824 for_each_online_node(nid) {
2825 /* Keep track of the offsets in numa_faults array */
2826 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2827 unsigned long faults = 0, group_faults = 0;
2830 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2831 long diff, f_diff, f_weight;
2833 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2834 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2835 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2836 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2838 /* Decay existing window, copy faults since last scan */
2839 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2840 fault_types[priv] += p->numa_faults[membuf_idx];
2841 p->numa_faults[membuf_idx] = 0;
2844 * Normalize the faults_from, so all tasks in a group
2845 * count according to CPU use, instead of by the raw
2846 * number of faults. Tasks with little runtime have
2847 * little over-all impact on throughput, and thus their
2848 * faults are less important.
2850 f_weight = div64_u64(runtime << 16, period + 1);
2851 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2853 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2854 p->numa_faults[cpubuf_idx] = 0;
2856 p->numa_faults[mem_idx] += diff;
2857 p->numa_faults[cpu_idx] += f_diff;
2858 faults += p->numa_faults[mem_idx];
2859 p->total_numa_faults += diff;
2862 * safe because we can only change our own group
2864 * mem_idx represents the offset for a given
2865 * nid and priv in a specific region because it
2866 * is at the beginning of the numa_faults array.
2868 ng->faults[mem_idx] += diff;
2869 ng->faults[cpu_idx] += f_diff;
2870 ng->total_faults += diff;
2871 group_faults += ng->faults[mem_idx];
2876 if (faults > max_faults) {
2877 max_faults = faults;
2880 } else if (group_faults > max_faults) {
2881 max_faults = group_faults;
2886 /* Cannot migrate task to CPU-less node */
2887 max_nid = numa_nearest_node(max_nid, N_CPU);
2890 numa_group_count_active_nodes(ng);
2891 spin_unlock_irq(group_lock);
2892 max_nid = preferred_group_nid(p, max_nid);
2896 /* Set the new preferred node */
2897 if (max_nid != p->numa_preferred_nid)
2898 sched_setnuma(p, max_nid);
2901 update_task_scan_period(p, fault_types[0], fault_types[1]);
2904 static inline int get_numa_group(struct numa_group *grp)
2906 return refcount_inc_not_zero(&grp->refcount);
2909 static inline void put_numa_group(struct numa_group *grp)
2911 if (refcount_dec_and_test(&grp->refcount))
2912 kfree_rcu(grp, rcu);
2915 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2918 struct numa_group *grp, *my_grp;
2919 struct task_struct *tsk;
2921 int cpu = cpupid_to_cpu(cpupid);
2924 if (unlikely(!deref_curr_numa_group(p))) {
2925 unsigned int size = sizeof(struct numa_group) +
2926 NR_NUMA_HINT_FAULT_STATS *
2927 nr_node_ids * sizeof(unsigned long);
2929 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2933 refcount_set(&grp->refcount, 1);
2934 grp->active_nodes = 1;
2935 grp->max_faults_cpu = 0;
2936 spin_lock_init(&grp->lock);
2939 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2940 grp->faults[i] = p->numa_faults[i];
2942 grp->total_faults = p->total_numa_faults;
2945 rcu_assign_pointer(p->numa_group, grp);
2949 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2951 if (!cpupid_match_pid(tsk, cpupid))
2954 grp = rcu_dereference(tsk->numa_group);
2958 my_grp = deref_curr_numa_group(p);
2963 * Only join the other group if its bigger; if we're the bigger group,
2964 * the other task will join us.
2966 if (my_grp->nr_tasks > grp->nr_tasks)
2970 * Tie-break on the grp address.
2972 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2975 /* Always join threads in the same process. */
2976 if (tsk->mm == current->mm)
2979 /* Simple filter to avoid false positives due to PID collisions */
2980 if (flags & TNF_SHARED)
2983 /* Update priv based on whether false sharing was detected */
2986 if (join && !get_numa_group(grp))
2994 WARN_ON_ONCE(irqs_disabled());
2995 double_lock_irq(&my_grp->lock, &grp->lock);
2997 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2998 my_grp->faults[i] -= p->numa_faults[i];
2999 grp->faults[i] += p->numa_faults[i];
3001 my_grp->total_faults -= p->total_numa_faults;
3002 grp->total_faults += p->total_numa_faults;
3007 spin_unlock(&my_grp->lock);
3008 spin_unlock_irq(&grp->lock);
3010 rcu_assign_pointer(p->numa_group, grp);
3012 put_numa_group(my_grp);
3021 * Get rid of NUMA statistics associated with a task (either current or dead).
3022 * If @final is set, the task is dead and has reached refcount zero, so we can
3023 * safely free all relevant data structures. Otherwise, there might be
3024 * concurrent reads from places like load balancing and procfs, and we should
3025 * reset the data back to default state without freeing ->numa_faults.
3027 void task_numa_free(struct task_struct *p, bool final)
3029 /* safe: p either is current or is being freed by current */
3030 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3031 unsigned long *numa_faults = p->numa_faults;
3032 unsigned long flags;
3039 spin_lock_irqsave(&grp->lock, flags);
3040 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3041 grp->faults[i] -= p->numa_faults[i];
3042 grp->total_faults -= p->total_numa_faults;
3045 spin_unlock_irqrestore(&grp->lock, flags);
3046 RCU_INIT_POINTER(p->numa_group, NULL);
3047 put_numa_group(grp);
3051 p->numa_faults = NULL;
3054 p->total_numa_faults = 0;
3055 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3061 * Got a PROT_NONE fault for a page on @node.
3063 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3065 struct task_struct *p = current;
3066 bool migrated = flags & TNF_MIGRATED;
3067 int cpu_node = task_node(current);
3068 int local = !!(flags & TNF_FAULT_LOCAL);
3069 struct numa_group *ng;
3072 if (!static_branch_likely(&sched_numa_balancing))
3075 /* for example, ksmd faulting in a user's mm */
3080 * NUMA faults statistics are unnecessary for the slow memory
3081 * node for memory tiering mode.
3083 if (!node_is_toptier(mem_node) &&
3084 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3085 !cpupid_valid(last_cpupid)))
3088 /* Allocate buffer to track faults on a per-node basis */
3089 if (unlikely(!p->numa_faults)) {
3090 int size = sizeof(*p->numa_faults) *
3091 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3093 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3094 if (!p->numa_faults)
3097 p->total_numa_faults = 0;
3098 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3102 * First accesses are treated as private, otherwise consider accesses
3103 * to be private if the accessing pid has not changed
3105 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3108 priv = cpupid_match_pid(p, last_cpupid);
3109 if (!priv && !(flags & TNF_NO_GROUP))
3110 task_numa_group(p, last_cpupid, flags, &priv);
3114 * If a workload spans multiple NUMA nodes, a shared fault that
3115 * occurs wholly within the set of nodes that the workload is
3116 * actively using should be counted as local. This allows the
3117 * scan rate to slow down when a workload has settled down.
3119 ng = deref_curr_numa_group(p);
3120 if (!priv && !local && ng && ng->active_nodes > 1 &&
3121 numa_is_active_node(cpu_node, ng) &&
3122 numa_is_active_node(mem_node, ng))
3126 * Retry to migrate task to preferred node periodically, in case it
3127 * previously failed, or the scheduler moved us.
3129 if (time_after(jiffies, p->numa_migrate_retry)) {
3130 task_numa_placement(p);
3131 numa_migrate_preferred(p);
3135 p->numa_pages_migrated += pages;
3136 if (flags & TNF_MIGRATE_FAIL)
3137 p->numa_faults_locality[2] += pages;
3139 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3140 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3141 p->numa_faults_locality[local] += pages;
3144 static void reset_ptenuma_scan(struct task_struct *p)
3147 * We only did a read acquisition of the mmap sem, so
3148 * p->mm->numa_scan_seq is written to without exclusive access
3149 * and the update is not guaranteed to be atomic. That's not
3150 * much of an issue though, since this is just used for
3151 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3152 * expensive, to avoid any form of compiler optimizations:
3154 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3155 p->mm->numa_scan_offset = 0;
3158 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3162 * Allow unconditional access first two times, so that all the (pages)
3163 * of VMAs get prot_none fault introduced irrespective of accesses.
3164 * This is also done to avoid any side effect of task scanning
3165 * amplifying the unfairness of disjoint set of VMAs' access.
3167 if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3170 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3171 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3175 * Complete a scan that has already started regardless of PID access, or
3176 * some VMAs may never be scanned in multi-threaded applications:
3178 if (mm->numa_scan_offset > vma->vm_start) {
3179 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3186 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3189 * The expensive part of numa migration is done from task_work context.
3190 * Triggered from task_tick_numa().
3192 static void task_numa_work(struct callback_head *work)
3194 unsigned long migrate, next_scan, now = jiffies;
3195 struct task_struct *p = current;
3196 struct mm_struct *mm = p->mm;
3197 u64 runtime = p->se.sum_exec_runtime;
3198 struct vm_area_struct *vma;
3199 unsigned long start, end;
3200 unsigned long nr_pte_updates = 0;
3201 long pages, virtpages;
3202 struct vma_iterator vmi;
3203 bool vma_pids_skipped;
3204 bool vma_pids_forced = false;
3206 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3210 * Who cares about NUMA placement when they're dying.
3212 * NOTE: make sure not to dereference p->mm before this check,
3213 * exit_task_work() happens _after_ exit_mm() so we could be called
3214 * without p->mm even though we still had it when we enqueued this
3217 if (p->flags & PF_EXITING)
3220 if (!mm->numa_next_scan) {
3221 mm->numa_next_scan = now +
3222 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3226 * Enforce maximal scan/migration frequency..
3228 migrate = mm->numa_next_scan;
3229 if (time_before(now, migrate))
3232 if (p->numa_scan_period == 0) {
3233 p->numa_scan_period_max = task_scan_max(p);
3234 p->numa_scan_period = task_scan_start(p);
3237 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3238 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3242 * Delay this task enough that another task of this mm will likely win
3243 * the next time around.
3245 p->node_stamp += 2 * TICK_NSEC;
3247 pages = sysctl_numa_balancing_scan_size;
3248 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3249 virtpages = pages * 8; /* Scan up to this much virtual space */
3254 if (!mmap_read_trylock(mm))
3258 * VMAs are skipped if the current PID has not trapped a fault within
3259 * the VMA recently. Allow scanning to be forced if there is no
3260 * suitable VMA remaining.
3262 vma_pids_skipped = false;
3265 start = mm->numa_scan_offset;
3266 vma_iter_init(&vmi, mm, start);
3267 vma = vma_next(&vmi);
3269 reset_ptenuma_scan(p);
3271 vma_iter_set(&vmi, start);
3272 vma = vma_next(&vmi);
3276 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3277 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3278 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3283 * Shared library pages mapped by multiple processes are not
3284 * migrated as it is expected they are cache replicated. Avoid
3285 * hinting faults in read-only file-backed mappings or the vdso
3286 * as migrating the pages will be of marginal benefit.
3289 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3290 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3295 * Skip inaccessible VMAs to avoid any confusion between
3296 * PROT_NONE and NUMA hinting ptes
3298 if (!vma_is_accessible(vma)) {
3299 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3303 /* Initialise new per-VMA NUMAB state. */
3304 if (!vma->numab_state) {
3305 vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3307 if (!vma->numab_state)
3310 vma->numab_state->next_scan = now +
3311 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3313 /* Reset happens after 4 times scan delay of scan start */
3314 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
3315 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3318 * Ensure prev_scan_seq does not match numa_scan_seq,
3319 * to prevent VMAs being skipped prematurely on the
3322 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3326 * Scanning the VMA's of short lived tasks add more overhead. So
3327 * delay the scan for new VMAs.
3329 if (mm->numa_scan_seq && time_before(jiffies,
3330 vma->numab_state->next_scan)) {
3331 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3335 /* RESET access PIDs regularly for old VMAs. */
3336 if (mm->numa_scan_seq &&
3337 time_after(jiffies, vma->numab_state->pids_active_reset)) {
3338 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3339 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3340 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3341 vma->numab_state->pids_active[1] = 0;
3344 /* Do not rescan VMAs twice within the same sequence. */
3345 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3346 mm->numa_scan_offset = vma->vm_end;
3347 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3352 * Do not scan the VMA if task has not accessed it, unless no other
3353 * VMA candidate exists.
3355 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3356 vma_pids_skipped = true;
3357 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3362 start = max(start, vma->vm_start);
3363 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3364 end = min(end, vma->vm_end);
3365 nr_pte_updates = change_prot_numa(vma, start, end);
3368 * Try to scan sysctl_numa_balancing_size worth of
3369 * hpages that have at least one present PTE that
3370 * is not already pte-numa. If the VMA contains
3371 * areas that are unused or already full of prot_numa
3372 * PTEs, scan up to virtpages, to skip through those
3376 pages -= (end - start) >> PAGE_SHIFT;
3377 virtpages -= (end - start) >> PAGE_SHIFT;
3380 if (pages <= 0 || virtpages <= 0)
3384 } while (end != vma->vm_end);
3386 /* VMA scan is complete, do not scan until next sequence. */
3387 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3390 * Only force scan within one VMA at a time, to limit the
3391 * cost of scanning a potentially uninteresting VMA.
3393 if (vma_pids_forced)
3395 } for_each_vma(vmi, vma);
3398 * If no VMAs are remaining and VMAs were skipped due to the PID
3399 * not accessing the VMA previously, then force a scan to ensure
3402 if (!vma && !vma_pids_forced && vma_pids_skipped) {
3403 vma_pids_forced = true;
3409 * It is possible to reach the end of the VMA list but the last few
3410 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3411 * would find the !migratable VMA on the next scan but not reset the
3412 * scanner to the start so check it now.
3415 mm->numa_scan_offset = start;
3417 reset_ptenuma_scan(p);
3418 mmap_read_unlock(mm);
3421 * Make sure tasks use at least 32x as much time to run other code
3422 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3423 * Usually update_task_scan_period slows down scanning enough; on an
3424 * overloaded system we need to limit overhead on a per task basis.
3426 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3427 u64 diff = p->se.sum_exec_runtime - runtime;
3428 p->node_stamp += 32 * diff;
3432 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3435 struct mm_struct *mm = p->mm;
3438 mm_users = atomic_read(&mm->mm_users);
3439 if (mm_users == 1) {
3440 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3441 mm->numa_scan_seq = 0;
3445 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3446 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3447 p->numa_migrate_retry = 0;
3448 /* Protect against double add, see task_tick_numa and task_numa_work */
3449 p->numa_work.next = &p->numa_work;
3450 p->numa_faults = NULL;
3451 p->numa_pages_migrated = 0;
3452 p->total_numa_faults = 0;
3453 RCU_INIT_POINTER(p->numa_group, NULL);
3454 p->last_task_numa_placement = 0;
3455 p->last_sum_exec_runtime = 0;
3457 init_task_work(&p->numa_work, task_numa_work);
3459 /* New address space, reset the preferred nid */
3460 if (!(clone_flags & CLONE_VM)) {
3461 p->numa_preferred_nid = NUMA_NO_NODE;
3466 * New thread, keep existing numa_preferred_nid which should be copied
3467 * already by arch_dup_task_struct but stagger when scans start.
3472 delay = min_t(unsigned int, task_scan_max(current),
3473 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3474 delay += 2 * TICK_NSEC;
3475 p->node_stamp = delay;
3480 * Drive the periodic memory faults..
3482 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3484 struct callback_head *work = &curr->numa_work;
3488 * We don't care about NUMA placement if we don't have memory.
3490 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3494 * Using runtime rather than walltime has the dual advantage that
3495 * we (mostly) drive the selection from busy threads and that the
3496 * task needs to have done some actual work before we bother with
3499 now = curr->se.sum_exec_runtime;
3500 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3502 if (now > curr->node_stamp + period) {
3503 if (!curr->node_stamp)
3504 curr->numa_scan_period = task_scan_start(curr);
3505 curr->node_stamp += period;
3507 if (!time_before(jiffies, curr->mm->numa_next_scan))
3508 task_work_add(curr, work, TWA_RESUME);
3512 static void update_scan_period(struct task_struct *p, int new_cpu)
3514 int src_nid = cpu_to_node(task_cpu(p));
3515 int dst_nid = cpu_to_node(new_cpu);
3517 if (!static_branch_likely(&sched_numa_balancing))
3520 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3523 if (src_nid == dst_nid)
3527 * Allow resets if faults have been trapped before one scan
3528 * has completed. This is most likely due to a new task that
3529 * is pulled cross-node due to wakeups or load balancing.
3531 if (p->numa_scan_seq) {
3533 * Avoid scan adjustments if moving to the preferred
3534 * node or if the task was not previously running on
3535 * the preferred node.
3537 if (dst_nid == p->numa_preferred_nid ||
3538 (p->numa_preferred_nid != NUMA_NO_NODE &&
3539 src_nid != p->numa_preferred_nid))
3543 p->numa_scan_period = task_scan_start(p);
3547 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3551 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3555 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3559 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3563 #endif /* CONFIG_NUMA_BALANCING */
3566 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3568 update_load_add(&cfs_rq->load, se->load.weight);
3570 if (entity_is_task(se)) {
3571 struct rq *rq = rq_of(cfs_rq);
3573 account_numa_enqueue(rq, task_of(se));
3574 list_add(&se->group_node, &rq->cfs_tasks);
3577 cfs_rq->nr_running++;
3579 cfs_rq->idle_nr_running++;
3583 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3585 update_load_sub(&cfs_rq->load, se->load.weight);
3587 if (entity_is_task(se)) {
3588 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3589 list_del_init(&se->group_node);
3592 cfs_rq->nr_running--;
3594 cfs_rq->idle_nr_running--;
3598 * Signed add and clamp on underflow.
3600 * Explicitly do a load-store to ensure the intermediate value never hits
3601 * memory. This allows lockless observations without ever seeing the negative
3604 #define add_positive(_ptr, _val) do { \
3605 typeof(_ptr) ptr = (_ptr); \
3606 typeof(_val) val = (_val); \
3607 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3611 if (val < 0 && res > var) \
3614 WRITE_ONCE(*ptr, res); \
3618 * Unsigned subtract and clamp on underflow.
3620 * Explicitly do a load-store to ensure the intermediate value never hits
3621 * memory. This allows lockless observations without ever seeing the negative
3624 #define sub_positive(_ptr, _val) do { \
3625 typeof(_ptr) ptr = (_ptr); \
3626 typeof(*ptr) val = (_val); \
3627 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3631 WRITE_ONCE(*ptr, res); \
3635 * Remove and clamp on negative, from a local variable.
3637 * A variant of sub_positive(), which does not use explicit load-store
3638 * and is thus optimized for local variable updates.
3640 #define lsub_positive(_ptr, _val) do { \
3641 typeof(_ptr) ptr = (_ptr); \
3642 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3647 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3649 cfs_rq->avg.load_avg += se->avg.load_avg;
3650 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3654 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3656 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3657 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3658 /* See update_cfs_rq_load_avg() */
3659 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3660 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3664 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3666 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3669 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se,
3670 unsigned long weight)
3672 unsigned long old_weight = se->load.weight;
3673 u64 avruntime = avg_vruntime(cfs_rq);
3680 * COROLLARY #1: The virtual runtime of the entity needs to be
3681 * adjusted if re-weight at !0-lag point.
3683 * Proof: For contradiction assume this is not true, so we can
3684 * re-weight without changing vruntime at !0-lag point.
3686 * Weight VRuntime Avg-VRuntime
3690 * Since lag needs to be preserved through re-weight:
3692 * lag = (V - v)*w = (V'- v')*w', where v = v'
3693 * ==> V' = (V - v)*w/w' + v (1)
3695 * Let W be the total weight of the entities before reweight,
3696 * since V' is the new weighted average of entities:
3698 * V' = (WV + w'v - wv) / (W + w' - w) (2)
3700 * by using (1) & (2) we obtain:
3702 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
3703 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
3704 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
3705 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
3707 * Since we are doing at !0-lag point which means V != v, we
3710 * ==> W / (W + w' - w) = w / w'
3711 * ==> Ww' = Ww + ww' - ww
3712 * ==> W * (w' - w) = w * (w' - w)
3713 * ==> W = w (re-weight indicates w' != w)
3715 * So the cfs_rq contains only one entity, hence vruntime of
3716 * the entity @v should always equal to the cfs_rq's weighted
3717 * average vruntime @V, which means we will always re-weight
3718 * at 0-lag point, thus breach assumption. Proof completed.
3721 * COROLLARY #2: Re-weight does NOT affect weighted average
3722 * vruntime of all the entities.
3724 * Proof: According to corollary #1, Eq. (1) should be:
3726 * (V - v)*w = (V' - v')*w'
3727 * ==> v' = V' - (V - v)*w/w' (4)
3729 * According to the weighted average formula, we have:
3731 * V' = (WV - wv + w'v') / (W - w + w')
3732 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
3733 * = (WV - wv + w'V' - Vw + wv) / (W - w + w')
3734 * = (WV + w'V' - Vw) / (W - w + w')
3736 * ==> V'*(W - w + w') = WV + w'V' - Vw
3737 * ==> V' * (W - w) = (W - w) * V (5)
3739 * If the entity is the only one in the cfs_rq, then reweight
3740 * always occurs at 0-lag point, so V won't change. Or else
3741 * there are other entities, hence W != w, then Eq. (5) turns
3742 * into V' = V. So V won't change in either case, proof done.
3745 * So according to corollary #1 & #2, the effect of re-weight
3746 * on vruntime should be:
3748 * v' = V' - (V - v) * w / w' (4)
3749 * = V - (V - v) * w / w'
3753 if (avruntime != se->vruntime) {
3754 vlag = (s64)(avruntime - se->vruntime);
3755 vlag = div_s64(vlag * old_weight, weight);
3756 se->vruntime = avruntime - vlag;
3763 * When the weight changes, the virtual time slope changes and
3764 * we should adjust the relative virtual deadline accordingly.
3766 * d' = v' + (d - v)*w/w'
3767 * = V' - (V - v)*w/w' + (d - v)*w/w'
3768 * = V - (V - v)*w/w' + (d - v)*w/w'
3769 * = V + (d - V)*w/w'
3771 vslice = (s64)(se->deadline - avruntime);
3772 vslice = div_s64(vslice * old_weight, weight);
3773 se->deadline = avruntime + vslice;
3776 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3777 unsigned long weight)
3779 bool curr = cfs_rq->curr == se;
3782 /* commit outstanding execution time */
3784 update_curr(cfs_rq);
3786 __dequeue_entity(cfs_rq, se);
3787 update_load_sub(&cfs_rq->load, se->load.weight);
3789 dequeue_load_avg(cfs_rq, se);
3793 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3794 * we need to scale se->vlag when w_i changes.
3796 se->vlag = div_s64(se->vlag * se->load.weight, weight);
3798 reweight_eevdf(cfs_rq, se, weight);
3801 update_load_set(&se->load, weight);
3805 u32 divider = get_pelt_divider(&se->avg);
3807 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3811 enqueue_load_avg(cfs_rq, se);
3813 update_load_add(&cfs_rq->load, se->load.weight);
3816 * The entity's vruntime has been adjusted, so let's check
3817 * whether the rq-wide min_vruntime needs updated too. Since
3818 * the calculations above require stable min_vruntime rather
3819 * than up-to-date one, we do the update at the end of the
3822 __enqueue_entity(cfs_rq, se);
3823 update_min_vruntime(cfs_rq);
3828 void reweight_task(struct task_struct *p, int prio)
3830 struct sched_entity *se = &p->se;
3831 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3832 struct load_weight *load = &se->load;
3833 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3835 reweight_entity(cfs_rq, se, weight);
3836 load->inv_weight = sched_prio_to_wmult[prio];
3839 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3841 #ifdef CONFIG_FAIR_GROUP_SCHED
3844 * All this does is approximate the hierarchical proportion which includes that
3845 * global sum we all love to hate.
3847 * That is, the weight of a group entity, is the proportional share of the
3848 * group weight based on the group runqueue weights. That is:
3850 * tg->weight * grq->load.weight
3851 * ge->load.weight = ----------------------------- (1)
3852 * \Sum grq->load.weight
3854 * Now, because computing that sum is prohibitively expensive to compute (been
3855 * there, done that) we approximate it with this average stuff. The average
3856 * moves slower and therefore the approximation is cheaper and more stable.
3858 * So instead of the above, we substitute:
3860 * grq->load.weight -> grq->avg.load_avg (2)
3862 * which yields the following:
3864 * tg->weight * grq->avg.load_avg
3865 * ge->load.weight = ------------------------------ (3)
3868 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3870 * That is shares_avg, and it is right (given the approximation (2)).
3872 * The problem with it is that because the average is slow -- it was designed
3873 * to be exactly that of course -- this leads to transients in boundary
3874 * conditions. In specific, the case where the group was idle and we start the
3875 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3876 * yielding bad latency etc..
3878 * Now, in that special case (1) reduces to:
3880 * tg->weight * grq->load.weight
3881 * ge->load.weight = ----------------------------- = tg->weight (4)
3884 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3886 * So what we do is modify our approximation (3) to approach (4) in the (near)
3891 * tg->weight * grq->load.weight
3892 * --------------------------------------------------- (5)
3893 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3895 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3896 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3899 * tg->weight * grq->load.weight
3900 * ge->load.weight = ----------------------------- (6)
3905 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3906 * max(grq->load.weight, grq->avg.load_avg)
3908 * And that is shares_weight and is icky. In the (near) UP case it approaches
3909 * (4) while in the normal case it approaches (3). It consistently
3910 * overestimates the ge->load.weight and therefore:
3912 * \Sum ge->load.weight >= tg->weight
3916 static long calc_group_shares(struct cfs_rq *cfs_rq)
3918 long tg_weight, tg_shares, load, shares;
3919 struct task_group *tg = cfs_rq->tg;
3921 tg_shares = READ_ONCE(tg->shares);
3923 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3925 tg_weight = atomic_long_read(&tg->load_avg);
3927 /* Ensure tg_weight >= load */
3928 tg_weight -= cfs_rq->tg_load_avg_contrib;
3931 shares = (tg_shares * load);
3933 shares /= tg_weight;
3936 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3937 * of a group with small tg->shares value. It is a floor value which is
3938 * assigned as a minimum load.weight to the sched_entity representing
3939 * the group on a CPU.
3941 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3942 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3943 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3944 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3947 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3949 #endif /* CONFIG_SMP */
3952 * Recomputes the group entity based on the current state of its group
3955 static void update_cfs_group(struct sched_entity *se)
3957 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3963 if (throttled_hierarchy(gcfs_rq))
3967 shares = READ_ONCE(gcfs_rq->tg->shares);
3969 shares = calc_group_shares(gcfs_rq);
3971 if (unlikely(se->load.weight != shares))
3972 reweight_entity(cfs_rq_of(se), se, shares);
3975 #else /* CONFIG_FAIR_GROUP_SCHED */
3976 static inline void update_cfs_group(struct sched_entity *se)
3979 #endif /* CONFIG_FAIR_GROUP_SCHED */
3981 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3983 struct rq *rq = rq_of(cfs_rq);
3985 if (&rq->cfs == cfs_rq) {
3987 * There are a few boundary cases this might miss but it should
3988 * get called often enough that that should (hopefully) not be
3991 * It will not get called when we go idle, because the idle
3992 * thread is a different class (!fair), nor will the utilization
3993 * number include things like RT tasks.
3995 * As is, the util number is not freq-invariant (we'd have to
3996 * implement arch_scale_freq_capacity() for that).
3998 * See cpu_util_cfs().
4000 cpufreq_update_util(rq, flags);
4005 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4013 if (sa->runnable_sum)
4017 * _avg must be null when _sum are null because _avg = _sum / divider
4018 * Make sure that rounding and/or propagation of PELT values never
4021 SCHED_WARN_ON(sa->load_avg ||
4028 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4030 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4031 cfs_rq->last_update_time_copy);
4033 #ifdef CONFIG_FAIR_GROUP_SCHED
4035 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4036 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4037 * bottom-up, we only have to test whether the cfs_rq before us on the list
4039 * If cfs_rq is not on the list, test whether a child needs its to be added to
4040 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
4042 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4044 struct cfs_rq *prev_cfs_rq;
4045 struct list_head *prev;
4047 if (cfs_rq->on_list) {
4048 prev = cfs_rq->leaf_cfs_rq_list.prev;
4050 struct rq *rq = rq_of(cfs_rq);
4052 prev = rq->tmp_alone_branch;
4055 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4057 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4060 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4062 if (cfs_rq->load.weight)
4065 if (!load_avg_is_decayed(&cfs_rq->avg))
4068 if (child_cfs_rq_on_list(cfs_rq))
4075 * update_tg_load_avg - update the tg's load avg
4076 * @cfs_rq: the cfs_rq whose avg changed
4078 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4079 * However, because tg->load_avg is a global value there are performance
4082 * In order to avoid having to look at the other cfs_rq's, we use a
4083 * differential update where we store the last value we propagated. This in
4084 * turn allows skipping updates if the differential is 'small'.
4086 * Updating tg's load_avg is necessary before update_cfs_share().
4088 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4094 * No need to update load_avg for root_task_group as it is not used.
4096 if (cfs_rq->tg == &root_task_group)
4100 * For migration heavy workloads, access to tg->load_avg can be
4101 * unbound. Limit the update rate to at most once per ms.
4103 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4104 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4107 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4108 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4109 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4110 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4111 cfs_rq->last_update_tg_load_avg = now;
4116 * Called within set_task_rq() right before setting a task's CPU. The
4117 * caller only guarantees p->pi_lock is held; no other assumptions,
4118 * including the state of rq->lock, should be made.
4120 void set_task_rq_fair(struct sched_entity *se,
4121 struct cfs_rq *prev, struct cfs_rq *next)
4123 u64 p_last_update_time;
4124 u64 n_last_update_time;
4126 if (!sched_feat(ATTACH_AGE_LOAD))
4130 * We are supposed to update the task to "current" time, then its up to
4131 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4132 * getting what current time is, so simply throw away the out-of-date
4133 * time. This will result in the wakee task is less decayed, but giving
4134 * the wakee more load sounds not bad.
4136 if (!(se->avg.last_update_time && prev))
4139 p_last_update_time = cfs_rq_last_update_time(prev);
4140 n_last_update_time = cfs_rq_last_update_time(next);
4142 __update_load_avg_blocked_se(p_last_update_time, se);
4143 se->avg.last_update_time = n_last_update_time;
4147 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4148 * propagate its contribution. The key to this propagation is the invariant
4149 * that for each group:
4151 * ge->avg == grq->avg (1)
4153 * _IFF_ we look at the pure running and runnable sums. Because they
4154 * represent the very same entity, just at different points in the hierarchy.
4156 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4157 * and simply copies the running/runnable sum over (but still wrong, because
4158 * the group entity and group rq do not have their PELT windows aligned).
4160 * However, update_tg_cfs_load() is more complex. So we have:
4162 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4164 * And since, like util, the runnable part should be directly transferable,
4165 * the following would _appear_ to be the straight forward approach:
4167 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4169 * And per (1) we have:
4171 * ge->avg.runnable_avg == grq->avg.runnable_avg
4175 * ge->load.weight * grq->avg.load_avg
4176 * ge->avg.load_avg = ----------------------------------- (4)
4179 * Except that is wrong!
4181 * Because while for entities historical weight is not important and we
4182 * really only care about our future and therefore can consider a pure
4183 * runnable sum, runqueues can NOT do this.
4185 * We specifically want runqueues to have a load_avg that includes
4186 * historical weights. Those represent the blocked load, the load we expect
4187 * to (shortly) return to us. This only works by keeping the weights as
4188 * integral part of the sum. We therefore cannot decompose as per (3).
4190 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4191 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4192 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4193 * runnable section of these tasks overlap (or not). If they were to perfectly
4194 * align the rq as a whole would be runnable 2/3 of the time. If however we
4195 * always have at least 1 runnable task, the rq as a whole is always runnable.
4197 * So we'll have to approximate.. :/
4199 * Given the constraint:
4201 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4203 * We can construct a rule that adds runnable to a rq by assuming minimal
4206 * On removal, we'll assume each task is equally runnable; which yields:
4208 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4210 * XXX: only do this for the part of runnable > running ?
4214 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4216 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4217 u32 new_sum, divider;
4219 /* Nothing to update */
4224 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4225 * See ___update_load_avg() for details.
4227 divider = get_pelt_divider(&cfs_rq->avg);
4230 /* Set new sched_entity's utilization */
4231 se->avg.util_avg = gcfs_rq->avg.util_avg;
4232 new_sum = se->avg.util_avg * divider;
4233 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4234 se->avg.util_sum = new_sum;
4236 /* Update parent cfs_rq utilization */
4237 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4238 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4240 /* See update_cfs_rq_load_avg() */
4241 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4242 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4246 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4248 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4249 u32 new_sum, divider;
4251 /* Nothing to update */
4256 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4257 * See ___update_load_avg() for details.
4259 divider = get_pelt_divider(&cfs_rq->avg);
4261 /* Set new sched_entity's runnable */
4262 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4263 new_sum = se->avg.runnable_avg * divider;
4264 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4265 se->avg.runnable_sum = new_sum;
4267 /* Update parent cfs_rq runnable */
4268 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4269 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4270 /* See update_cfs_rq_load_avg() */
4271 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4272 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4276 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4278 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4279 unsigned long load_avg;
4287 gcfs_rq->prop_runnable_sum = 0;
4290 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4291 * See ___update_load_avg() for details.
4293 divider = get_pelt_divider(&cfs_rq->avg);
4295 if (runnable_sum >= 0) {
4297 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4298 * the CPU is saturated running == runnable.
4300 runnable_sum += se->avg.load_sum;
4301 runnable_sum = min_t(long, runnable_sum, divider);
4304 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4305 * assuming all tasks are equally runnable.
4307 if (scale_load_down(gcfs_rq->load.weight)) {
4308 load_sum = div_u64(gcfs_rq->avg.load_sum,
4309 scale_load_down(gcfs_rq->load.weight));
4312 /* But make sure to not inflate se's runnable */
4313 runnable_sum = min(se->avg.load_sum, load_sum);
4317 * runnable_sum can't be lower than running_sum
4318 * Rescale running sum to be in the same range as runnable sum
4319 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4320 * runnable_sum is in [0 : LOAD_AVG_MAX]
4322 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4323 runnable_sum = max(runnable_sum, running_sum);
4325 load_sum = se_weight(se) * runnable_sum;
4326 load_avg = div_u64(load_sum, divider);
4328 delta_avg = load_avg - se->avg.load_avg;
4332 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4334 se->avg.load_sum = runnable_sum;
4335 se->avg.load_avg = load_avg;
4336 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4337 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4338 /* See update_cfs_rq_load_avg() */
4339 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4340 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4343 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4345 cfs_rq->propagate = 1;
4346 cfs_rq->prop_runnable_sum += runnable_sum;
4349 /* Update task and its cfs_rq load average */
4350 static inline int propagate_entity_load_avg(struct sched_entity *se)
4352 struct cfs_rq *cfs_rq, *gcfs_rq;
4354 if (entity_is_task(se))
4357 gcfs_rq = group_cfs_rq(se);
4358 if (!gcfs_rq->propagate)
4361 gcfs_rq->propagate = 0;
4363 cfs_rq = cfs_rq_of(se);
4365 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4367 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4368 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4369 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4371 trace_pelt_cfs_tp(cfs_rq);
4372 trace_pelt_se_tp(se);
4378 * Check if we need to update the load and the utilization of a blocked
4381 static inline bool skip_blocked_update(struct sched_entity *se)
4383 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4386 * If sched_entity still have not zero load or utilization, we have to
4389 if (se->avg.load_avg || se->avg.util_avg)
4393 * If there is a pending propagation, we have to update the load and
4394 * the utilization of the sched_entity:
4396 if (gcfs_rq->propagate)
4400 * Otherwise, the load and the utilization of the sched_entity is
4401 * already zero and there is no pending propagation, so it will be a
4402 * waste of time to try to decay it:
4407 #else /* CONFIG_FAIR_GROUP_SCHED */
4409 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4411 static inline int propagate_entity_load_avg(struct sched_entity *se)
4416 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4418 #endif /* CONFIG_FAIR_GROUP_SCHED */
4420 #ifdef CONFIG_NO_HZ_COMMON
4421 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4423 u64 throttled = 0, now, lut;
4424 struct cfs_rq *cfs_rq;
4428 if (load_avg_is_decayed(&se->avg))
4431 cfs_rq = cfs_rq_of(se);
4435 is_idle = is_idle_task(rcu_dereference(rq->curr));
4439 * The lag estimation comes with a cost we don't want to pay all the
4440 * time. Hence, limiting to the case where the source CPU is idle and
4441 * we know we are at the greatest risk to have an outdated clock.
4447 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4449 * last_update_time (the cfs_rq's last_update_time)
4450 * = cfs_rq_clock_pelt()@cfs_rq_idle
4451 * = rq_clock_pelt()@cfs_rq_idle
4452 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4454 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4455 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4457 * rq_idle_lag (delta between now and rq's update)
4458 * = sched_clock_cpu() - rq_clock()@rq_idle
4460 * We can then write:
4462 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4463 * sched_clock_cpu() - rq_clock()@rq_idle
4465 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4466 * rq_clock()@rq_idle is rq->clock_idle
4467 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4468 * is cfs_rq->throttled_pelt_idle
4471 #ifdef CONFIG_CFS_BANDWIDTH
4472 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4473 /* The clock has been stopped for throttling */
4474 if (throttled == U64_MAX)
4477 now = u64_u32_load(rq->clock_pelt_idle);
4479 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4480 * is observed the old clock_pelt_idle value and the new clock_idle,
4481 * which lead to an underestimation. The opposite would lead to an
4485 lut = cfs_rq_last_update_time(cfs_rq);
4490 * cfs_rq->avg.last_update_time is more recent than our
4491 * estimation, let's use it.
4495 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4497 __update_load_avg_blocked_se(now, se);
4500 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4504 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4505 * @now: current time, as per cfs_rq_clock_pelt()
4506 * @cfs_rq: cfs_rq to update
4508 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4509 * avg. The immediate corollary is that all (fair) tasks must be attached.
4511 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4513 * Return: true if the load decayed or we removed load.
4515 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4516 * call update_tg_load_avg() when this function returns true.
4519 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4521 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4522 struct sched_avg *sa = &cfs_rq->avg;
4525 if (cfs_rq->removed.nr) {
4527 u32 divider = get_pelt_divider(&cfs_rq->avg);
4529 raw_spin_lock(&cfs_rq->removed.lock);
4530 swap(cfs_rq->removed.util_avg, removed_util);
4531 swap(cfs_rq->removed.load_avg, removed_load);
4532 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4533 cfs_rq->removed.nr = 0;
4534 raw_spin_unlock(&cfs_rq->removed.lock);
4537 sub_positive(&sa->load_avg, r);
4538 sub_positive(&sa->load_sum, r * divider);
4539 /* See sa->util_sum below */
4540 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4543 sub_positive(&sa->util_avg, r);
4544 sub_positive(&sa->util_sum, r * divider);
4546 * Because of rounding, se->util_sum might ends up being +1 more than
4547 * cfs->util_sum. Although this is not a problem by itself, detaching
4548 * a lot of tasks with the rounding problem between 2 updates of
4549 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4550 * cfs_util_avg is not.
4551 * Check that util_sum is still above its lower bound for the new
4552 * util_avg. Given that period_contrib might have moved since the last
4553 * sync, we are only sure that util_sum must be above or equal to
4554 * util_avg * minimum possible divider
4556 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4558 r = removed_runnable;
4559 sub_positive(&sa->runnable_avg, r);
4560 sub_positive(&sa->runnable_sum, r * divider);
4561 /* See sa->util_sum above */
4562 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4563 sa->runnable_avg * PELT_MIN_DIVIDER);
4566 * removed_runnable is the unweighted version of removed_load so we
4567 * can use it to estimate removed_load_sum.
4569 add_tg_cfs_propagate(cfs_rq,
4570 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4575 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4576 u64_u32_store_copy(sa->last_update_time,
4577 cfs_rq->last_update_time_copy,
4578 sa->last_update_time);
4583 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4584 * @cfs_rq: cfs_rq to attach to
4585 * @se: sched_entity to attach
4587 * Must call update_cfs_rq_load_avg() before this, since we rely on
4588 * cfs_rq->avg.last_update_time being current.
4590 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4593 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4594 * See ___update_load_avg() for details.
4596 u32 divider = get_pelt_divider(&cfs_rq->avg);
4599 * When we attach the @se to the @cfs_rq, we must align the decay
4600 * window because without that, really weird and wonderful things can
4605 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4606 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4609 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4610 * period_contrib. This isn't strictly correct, but since we're
4611 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4614 se->avg.util_sum = se->avg.util_avg * divider;
4616 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4618 se->avg.load_sum = se->avg.load_avg * divider;
4619 if (se_weight(se) < se->avg.load_sum)
4620 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4622 se->avg.load_sum = 1;
4624 enqueue_load_avg(cfs_rq, se);
4625 cfs_rq->avg.util_avg += se->avg.util_avg;
4626 cfs_rq->avg.util_sum += se->avg.util_sum;
4627 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4628 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4630 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4632 cfs_rq_util_change(cfs_rq, 0);
4634 trace_pelt_cfs_tp(cfs_rq);
4638 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4639 * @cfs_rq: cfs_rq to detach from
4640 * @se: sched_entity to detach
4642 * Must call update_cfs_rq_load_avg() before this, since we rely on
4643 * cfs_rq->avg.last_update_time being current.
4645 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4647 dequeue_load_avg(cfs_rq, se);
4648 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4649 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4650 /* See update_cfs_rq_load_avg() */
4651 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4652 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4654 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4655 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4656 /* See update_cfs_rq_load_avg() */
4657 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4658 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4660 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4662 cfs_rq_util_change(cfs_rq, 0);
4664 trace_pelt_cfs_tp(cfs_rq);
4668 * Optional action to be done while updating the load average
4670 #define UPDATE_TG 0x1
4671 #define SKIP_AGE_LOAD 0x2
4672 #define DO_ATTACH 0x4
4673 #define DO_DETACH 0x8
4675 /* Update task and its cfs_rq load average */
4676 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4678 u64 now = cfs_rq_clock_pelt(cfs_rq);
4682 * Track task load average for carrying it to new CPU after migrated, and
4683 * track group sched_entity load average for task_h_load calc in migration
4685 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4686 __update_load_avg_se(now, cfs_rq, se);
4688 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4689 decayed |= propagate_entity_load_avg(se);
4691 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4694 * DO_ATTACH means we're here from enqueue_entity().
4695 * !last_update_time means we've passed through
4696 * migrate_task_rq_fair() indicating we migrated.
4698 * IOW we're enqueueing a task on a new CPU.
4700 attach_entity_load_avg(cfs_rq, se);
4701 update_tg_load_avg(cfs_rq);
4703 } else if (flags & DO_DETACH) {
4705 * DO_DETACH means we're here from dequeue_entity()
4706 * and we are migrating task out of the CPU.
4708 detach_entity_load_avg(cfs_rq, se);
4709 update_tg_load_avg(cfs_rq);
4710 } else if (decayed) {
4711 cfs_rq_util_change(cfs_rq, 0);
4713 if (flags & UPDATE_TG)
4714 update_tg_load_avg(cfs_rq);
4719 * Synchronize entity load avg of dequeued entity without locking
4722 static void sync_entity_load_avg(struct sched_entity *se)
4724 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4725 u64 last_update_time;
4727 last_update_time = cfs_rq_last_update_time(cfs_rq);
4728 __update_load_avg_blocked_se(last_update_time, se);
4732 * Task first catches up with cfs_rq, and then subtract
4733 * itself from the cfs_rq (task must be off the queue now).
4735 static void remove_entity_load_avg(struct sched_entity *se)
4737 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4738 unsigned long flags;
4741 * tasks cannot exit without having gone through wake_up_new_task() ->
4742 * enqueue_task_fair() which will have added things to the cfs_rq,
4743 * so we can remove unconditionally.
4746 sync_entity_load_avg(se);
4748 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4749 ++cfs_rq->removed.nr;
4750 cfs_rq->removed.util_avg += se->avg.util_avg;
4751 cfs_rq->removed.load_avg += se->avg.load_avg;
4752 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4753 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4756 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4758 return cfs_rq->avg.runnable_avg;
4761 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4763 return cfs_rq->avg.load_avg;
4766 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4768 static inline unsigned long task_util(struct task_struct *p)
4770 return READ_ONCE(p->se.avg.util_avg);
4773 static inline unsigned long _task_util_est(struct task_struct *p)
4775 struct util_est ue = READ_ONCE(p->se.avg.util_est);
4777 return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4780 static inline unsigned long task_util_est(struct task_struct *p)
4782 return max(task_util(p), _task_util_est(p));
4785 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4786 struct task_struct *p)
4788 unsigned int enqueued;
4790 if (!sched_feat(UTIL_EST))
4793 /* Update root cfs_rq's estimated utilization */
4794 enqueued = cfs_rq->avg.util_est.enqueued;
4795 enqueued += _task_util_est(p);
4796 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4798 trace_sched_util_est_cfs_tp(cfs_rq);
4801 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4802 struct task_struct *p)
4804 unsigned int enqueued;
4806 if (!sched_feat(UTIL_EST))
4809 /* Update root cfs_rq's estimated utilization */
4810 enqueued = cfs_rq->avg.util_est.enqueued;
4811 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4812 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4814 trace_sched_util_est_cfs_tp(cfs_rq);
4817 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4820 * Check if a (signed) value is within a specified (unsigned) margin,
4821 * based on the observation that:
4823 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4825 * NOTE: this only works when value + margin < INT_MAX.
4827 static inline bool within_margin(int value, int margin)
4829 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4832 static inline void util_est_update(struct cfs_rq *cfs_rq,
4833 struct task_struct *p,
4836 long last_ewma_diff, last_enqueued_diff;
4839 if (!sched_feat(UTIL_EST))
4843 * Skip update of task's estimated utilization when the task has not
4844 * yet completed an activation, e.g. being migrated.
4850 * If the PELT values haven't changed since enqueue time,
4851 * skip the util_est update.
4853 ue = p->se.avg.util_est;
4854 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4857 last_enqueued_diff = ue.enqueued;
4860 * Reset EWMA on utilization increases, the moving average is used only
4861 * to smooth utilization decreases.
4863 ue.enqueued = task_util(p);
4864 if (sched_feat(UTIL_EST_FASTUP)) {
4865 if (ue.ewma < ue.enqueued) {
4866 ue.ewma = ue.enqueued;
4872 * Skip update of task's estimated utilization when its members are
4873 * already ~1% close to its last activation value.
4875 last_ewma_diff = ue.enqueued - ue.ewma;
4876 last_enqueued_diff -= ue.enqueued;
4877 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4878 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4885 * To avoid overestimation of actual task utilization, skip updates if
4886 * we cannot grant there is idle time in this CPU.
4888 if (task_util(p) > arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))))
4892 * Update Task's estimated utilization
4894 * When *p completes an activation we can consolidate another sample
4895 * of the task size. This is done by storing the current PELT value
4896 * as ue.enqueued and by using this value to update the Exponential
4897 * Weighted Moving Average (EWMA):
4899 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4900 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4901 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4902 * = w * ( last_ewma_diff ) + ewma(t-1)
4903 * = w * (last_ewma_diff + ewma(t-1) / w)
4905 * Where 'w' is the weight of new samples, which is configured to be
4906 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4908 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4909 ue.ewma += last_ewma_diff;
4910 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4912 ue.enqueued |= UTIL_AVG_UNCHANGED;
4913 WRITE_ONCE(p->se.avg.util_est, ue);
4915 trace_sched_util_est_se_tp(&p->se);
4918 static inline int util_fits_cpu(unsigned long util,
4919 unsigned long uclamp_min,
4920 unsigned long uclamp_max,
4923 unsigned long capacity_orig, capacity_orig_thermal;
4924 unsigned long capacity = capacity_of(cpu);
4925 bool fits, uclamp_max_fits;
4928 * Check if the real util fits without any uclamp boost/cap applied.
4930 fits = fits_capacity(util, capacity);
4932 if (!uclamp_is_used())
4936 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4937 * uclamp_max. We only care about capacity pressure (by using
4938 * capacity_of()) for comparing against the real util.
4940 * If a task is boosted to 1024 for example, we don't want a tiny
4941 * pressure to skew the check whether it fits a CPU or not.
4943 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4944 * should fit a little cpu even if there's some pressure.
4946 * Only exception is for thermal pressure since it has a direct impact
4947 * on available OPP of the system.
4949 * We honour it for uclamp_min only as a drop in performance level
4950 * could result in not getting the requested minimum performance level.
4952 * For uclamp_max, we can tolerate a drop in performance level as the
4953 * goal is to cap the task. So it's okay if it's getting less.
4955 capacity_orig = arch_scale_cpu_capacity(cpu);
4956 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4959 * We want to force a task to fit a cpu as implied by uclamp_max.
4960 * But we do have some corner cases to cater for..
4966 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4969 * | | | | | | | (util somewhere in this region)
4972 * +----------------------------------------
4975 * In the above example if a task is capped to a specific performance
4976 * point, y, then when:
4978 * * util = 80% of x then it does not fit on cpu0 and should migrate
4980 * * util = 80% of y then it is forced to fit on cpu1 to honour
4981 * uclamp_max request.
4983 * which is what we're enforcing here. A task always fits if
4984 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4985 * the normal upmigration rules should withhold still.
4987 * Only exception is when we are on max capacity, then we need to be
4988 * careful not to block overutilized state. This is so because:
4990 * 1. There's no concept of capping at max_capacity! We can't go
4991 * beyond this performance level anyway.
4992 * 2. The system is being saturated when we're operating near
4993 * max capacity, it doesn't make sense to block overutilized.
4995 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4996 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4997 fits = fits || uclamp_max_fits;
5002 * | ___ (region a, capped, util >= uclamp_max)
5004 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5006 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
5007 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5009 * | | | | | | | (region c, boosted, util < uclamp_min)
5010 * +----------------------------------------
5013 * a) If util > uclamp_max, then we're capped, we don't care about
5014 * actual fitness value here. We only care if uclamp_max fits
5015 * capacity without taking margin/pressure into account.
5016 * See comment above.
5018 * b) If uclamp_min <= util <= uclamp_max, then the normal
5019 * fits_capacity() rules apply. Except we need to ensure that we
5020 * enforce we remain within uclamp_max, see comment above.
5022 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5023 * need to take into account the boosted value fits the CPU without
5024 * taking margin/pressure into account.
5026 * Cases (a) and (b) are handled in the 'fits' variable already. We
5027 * just need to consider an extra check for case (c) after ensuring we
5028 * handle the case uclamp_min > uclamp_max.
5030 uclamp_min = min(uclamp_min, uclamp_max);
5031 if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
5037 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5039 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5040 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5041 unsigned long util = task_util_est(p);
5043 * Return true only if the cpu fully fits the task requirements, which
5044 * include the utilization but also the performance hints.
5046 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5049 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5051 if (!sched_asym_cpucap_active())
5054 if (!p || p->nr_cpus_allowed == 1) {
5055 rq->misfit_task_load = 0;
5059 if (task_fits_cpu(p, cpu_of(rq))) {
5060 rq->misfit_task_load = 0;
5065 * Make sure that misfit_task_load will not be null even if
5066 * task_h_load() returns 0.
5068 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5071 #else /* CONFIG_SMP */
5073 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5075 return !cfs_rq->nr_running;
5078 #define UPDATE_TG 0x0
5079 #define SKIP_AGE_LOAD 0x0
5080 #define DO_ATTACH 0x0
5081 #define DO_DETACH 0x0
5083 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
5085 cfs_rq_util_change(cfs_rq, 0);
5088 static inline void remove_entity_load_avg(struct sched_entity *se) {}
5091 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5093 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5095 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
5101 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5104 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5107 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
5109 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
5111 #endif /* CONFIG_SMP */
5114 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5116 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5119 se->slice = sysctl_sched_base_slice;
5120 vslice = calc_delta_fair(se->slice, se);
5123 * Due to how V is constructed as the weighted average of entities,
5124 * adding tasks with positive lag, or removing tasks with negative lag
5125 * will move 'time' backwards, this can screw around with the lag of
5128 * EEVDF: placement strategy #1 / #2
5130 if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
5131 struct sched_entity *curr = cfs_rq->curr;
5137 * If we want to place a task and preserve lag, we have to
5138 * consider the effect of the new entity on the weighted
5139 * average and compensate for this, otherwise lag can quickly
5142 * Lag is defined as:
5144 * lag_i = S - s_i = w_i * (V - v_i)
5146 * To avoid the 'w_i' term all over the place, we only track
5149 * vl_i = V - v_i <=> v_i = V - vl_i
5151 * And we take V to be the weighted average of all v:
5153 * V = (\Sum w_j*v_j) / W
5155 * Where W is: \Sum w_j
5157 * Then, the weighted average after adding an entity with lag
5160 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5161 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5162 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5163 * = (V*(W + w_i) - w_i*l) / (W + w_i)
5164 * = V - w_i*vl_i / (W + w_i)
5166 * And the actual lag after adding an entity with vl_i is:
5169 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5170 * = vl_i - w_i*vl_i / (W + w_i)
5172 * Which is strictly less than vl_i. So in order to preserve lag
5173 * we should inflate the lag before placement such that the
5174 * effective lag after placement comes out right.
5176 * As such, invert the above relation for vl'_i to get the vl_i
5177 * we need to use such that the lag after placement is the lag
5178 * we computed before dequeue.
5180 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5181 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5183 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5186 * vl_i = (W + w_i)*vl'_i / W
5188 load = cfs_rq->avg_load;
5189 if (curr && curr->on_rq)
5190 load += scale_load_down(curr->load.weight);
5192 lag *= load + scale_load_down(se->load.weight);
5193 if (WARN_ON_ONCE(!load))
5195 lag = div_s64(lag, load);
5198 se->vruntime = vruntime - lag;
5201 * When joining the competition; the exisiting tasks will be,
5202 * on average, halfway through their slice, as such start tasks
5203 * off with half a slice to ease into the competition.
5205 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5209 * EEVDF: vd_i = ve_i + r_i/w_i
5211 se->deadline = se->vruntime + vslice;
5214 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5215 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5217 static inline bool cfs_bandwidth_used(void);
5220 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5222 bool curr = cfs_rq->curr == se;
5225 * If we're the current task, we must renormalise before calling
5229 place_entity(cfs_rq, se, flags);
5231 update_curr(cfs_rq);
5234 * When enqueuing a sched_entity, we must:
5235 * - Update loads to have both entity and cfs_rq synced with now.
5236 * - For group_entity, update its runnable_weight to reflect the new
5237 * h_nr_running of its group cfs_rq.
5238 * - For group_entity, update its weight to reflect the new share of
5240 * - Add its new weight to cfs_rq->load.weight
5242 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5243 se_update_runnable(se);
5245 * XXX update_load_avg() above will have attached us to the pelt sum;
5246 * but update_cfs_group() here will re-adjust the weight and have to
5247 * undo/redo all that. Seems wasteful.
5249 update_cfs_group(se);
5252 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5253 * we can place the entity.
5256 place_entity(cfs_rq, se, flags);
5258 account_entity_enqueue(cfs_rq, se);
5260 /* Entity has migrated, no longer consider this task hot */
5261 if (flags & ENQUEUE_MIGRATED)
5264 check_schedstat_required();
5265 update_stats_enqueue_fair(cfs_rq, se, flags);
5267 __enqueue_entity(cfs_rq, se);
5270 if (cfs_rq->nr_running == 1) {
5271 check_enqueue_throttle(cfs_rq);
5272 if (!throttled_hierarchy(cfs_rq)) {
5273 list_add_leaf_cfs_rq(cfs_rq);
5275 #ifdef CONFIG_CFS_BANDWIDTH
5276 struct rq *rq = rq_of(cfs_rq);
5278 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5279 cfs_rq->throttled_clock = rq_clock(rq);
5280 if (!cfs_rq->throttled_clock_self)
5281 cfs_rq->throttled_clock_self = rq_clock(rq);
5287 static void __clear_buddies_next(struct sched_entity *se)
5289 for_each_sched_entity(se) {
5290 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5291 if (cfs_rq->next != se)
5294 cfs_rq->next = NULL;
5298 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5300 if (cfs_rq->next == se)
5301 __clear_buddies_next(se);
5304 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5307 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5309 int action = UPDATE_TG;
5311 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5312 action |= DO_DETACH;
5315 * Update run-time statistics of the 'current'.
5317 update_curr(cfs_rq);
5320 * When dequeuing a sched_entity, we must:
5321 * - Update loads to have both entity and cfs_rq synced with now.
5322 * - For group_entity, update its runnable_weight to reflect the new
5323 * h_nr_running of its group cfs_rq.
5324 * - Subtract its previous weight from cfs_rq->load.weight.
5325 * - For group entity, update its weight to reflect the new share
5326 * of its group cfs_rq.
5328 update_load_avg(cfs_rq, se, action);
5329 se_update_runnable(se);
5331 update_stats_dequeue_fair(cfs_rq, se, flags);
5333 clear_buddies(cfs_rq, se);
5335 update_entity_lag(cfs_rq, se);
5336 if (se != cfs_rq->curr)
5337 __dequeue_entity(cfs_rq, se);
5339 account_entity_dequeue(cfs_rq, se);
5341 /* return excess runtime on last dequeue */
5342 return_cfs_rq_runtime(cfs_rq);
5344 update_cfs_group(se);
5347 * Now advance min_vruntime if @se was the entity holding it back,
5348 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5349 * put back on, and if we advance min_vruntime, we'll be placed back
5350 * further than we started -- ie. we'll be penalized.
5352 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5353 update_min_vruntime(cfs_rq);
5355 if (cfs_rq->nr_running == 0)
5356 update_idle_cfs_rq_clock_pelt(cfs_rq);
5360 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5362 clear_buddies(cfs_rq, se);
5364 /* 'current' is not kept within the tree. */
5367 * Any task has to be enqueued before it get to execute on
5368 * a CPU. So account for the time it spent waiting on the
5371 update_stats_wait_end_fair(cfs_rq, se);
5372 __dequeue_entity(cfs_rq, se);
5373 update_load_avg(cfs_rq, se, UPDATE_TG);
5375 * HACK, stash a copy of deadline at the point of pick in vlag,
5376 * which isn't used until dequeue.
5378 se->vlag = se->deadline;
5381 update_stats_curr_start(cfs_rq, se);
5385 * Track our maximum slice length, if the CPU's load is at
5386 * least twice that of our own weight (i.e. dont track it
5387 * when there are only lesser-weight tasks around):
5389 if (schedstat_enabled() &&
5390 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5391 struct sched_statistics *stats;
5393 stats = __schedstats_from_se(se);
5394 __schedstat_set(stats->slice_max,
5395 max((u64)stats->slice_max,
5396 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5399 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5403 * Pick the next process, keeping these things in mind, in this order:
5404 * 1) keep things fair between processes/task groups
5405 * 2) pick the "next" process, since someone really wants that to run
5406 * 3) pick the "last" process, for cache locality
5407 * 4) do not run the "skip" process, if something else is available
5409 static struct sched_entity *
5410 pick_next_entity(struct cfs_rq *cfs_rq)
5413 * Enabling NEXT_BUDDY will affect latency but not fairness.
5415 if (sched_feat(NEXT_BUDDY) &&
5416 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5417 return cfs_rq->next;
5419 return pick_eevdf(cfs_rq);
5422 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5424 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5427 * If still on the runqueue then deactivate_task()
5428 * was not called and update_curr() has to be done:
5431 update_curr(cfs_rq);
5433 /* throttle cfs_rqs exceeding runtime */
5434 check_cfs_rq_runtime(cfs_rq);
5437 update_stats_wait_start_fair(cfs_rq, prev);
5438 /* Put 'current' back into the tree. */
5439 __enqueue_entity(cfs_rq, prev);
5440 /* in !on_rq case, update occurred at dequeue */
5441 update_load_avg(cfs_rq, prev, 0);
5443 cfs_rq->curr = NULL;
5447 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5450 * Update run-time statistics of the 'current'.
5452 update_curr(cfs_rq);
5455 * Ensure that runnable average is periodically updated.
5457 update_load_avg(cfs_rq, curr, UPDATE_TG);
5458 update_cfs_group(curr);
5460 #ifdef CONFIG_SCHED_HRTICK
5462 * queued ticks are scheduled to match the slice, so don't bother
5463 * validating it and just reschedule.
5466 resched_curr(rq_of(cfs_rq));
5470 * don't let the period tick interfere with the hrtick preemption
5472 if (!sched_feat(DOUBLE_TICK) &&
5473 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5479 /**************************************************
5480 * CFS bandwidth control machinery
5483 #ifdef CONFIG_CFS_BANDWIDTH
5485 #ifdef CONFIG_JUMP_LABEL
5486 static struct static_key __cfs_bandwidth_used;
5488 static inline bool cfs_bandwidth_used(void)
5490 return static_key_false(&__cfs_bandwidth_used);
5493 void cfs_bandwidth_usage_inc(void)
5495 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5498 void cfs_bandwidth_usage_dec(void)
5500 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5502 #else /* CONFIG_JUMP_LABEL */
5503 static bool cfs_bandwidth_used(void)
5508 void cfs_bandwidth_usage_inc(void) {}
5509 void cfs_bandwidth_usage_dec(void) {}
5510 #endif /* CONFIG_JUMP_LABEL */
5513 * default period for cfs group bandwidth.
5514 * default: 0.1s, units: nanoseconds
5516 static inline u64 default_cfs_period(void)
5518 return 100000000ULL;
5521 static inline u64 sched_cfs_bandwidth_slice(void)
5523 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5527 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5528 * directly instead of rq->clock to avoid adding additional synchronization
5531 * requires cfs_b->lock
5533 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5537 if (unlikely(cfs_b->quota == RUNTIME_INF))
5540 cfs_b->runtime += cfs_b->quota;
5541 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5543 cfs_b->burst_time += runtime;
5547 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5548 cfs_b->runtime_snap = cfs_b->runtime;
5551 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5553 return &tg->cfs_bandwidth;
5556 /* returns 0 on failure to allocate runtime */
5557 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5558 struct cfs_rq *cfs_rq, u64 target_runtime)
5560 u64 min_amount, amount = 0;
5562 lockdep_assert_held(&cfs_b->lock);
5564 /* note: this is a positive sum as runtime_remaining <= 0 */
5565 min_amount = target_runtime - cfs_rq->runtime_remaining;
5567 if (cfs_b->quota == RUNTIME_INF)
5568 amount = min_amount;
5570 start_cfs_bandwidth(cfs_b);
5572 if (cfs_b->runtime > 0) {
5573 amount = min(cfs_b->runtime, min_amount);
5574 cfs_b->runtime -= amount;
5579 cfs_rq->runtime_remaining += amount;
5581 return cfs_rq->runtime_remaining > 0;
5584 /* returns 0 on failure to allocate runtime */
5585 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5587 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5590 raw_spin_lock(&cfs_b->lock);
5591 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5592 raw_spin_unlock(&cfs_b->lock);
5597 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5599 /* dock delta_exec before expiring quota (as it could span periods) */
5600 cfs_rq->runtime_remaining -= delta_exec;
5602 if (likely(cfs_rq->runtime_remaining > 0))
5605 if (cfs_rq->throttled)
5608 * if we're unable to extend our runtime we resched so that the active
5609 * hierarchy can be throttled
5611 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5612 resched_curr(rq_of(cfs_rq));
5615 static __always_inline
5616 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5618 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5621 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5624 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5626 return cfs_bandwidth_used() && cfs_rq->throttled;
5629 /* check whether cfs_rq, or any parent, is throttled */
5630 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5632 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5636 * Ensure that neither of the group entities corresponding to src_cpu or
5637 * dest_cpu are members of a throttled hierarchy when performing group
5638 * load-balance operations.
5640 static inline int throttled_lb_pair(struct task_group *tg,
5641 int src_cpu, int dest_cpu)
5643 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5645 src_cfs_rq = tg->cfs_rq[src_cpu];
5646 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5648 return throttled_hierarchy(src_cfs_rq) ||
5649 throttled_hierarchy(dest_cfs_rq);
5652 static int tg_unthrottle_up(struct task_group *tg, void *data)
5654 struct rq *rq = data;
5655 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5657 cfs_rq->throttle_count--;
5658 if (!cfs_rq->throttle_count) {
5659 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5660 cfs_rq->throttled_clock_pelt;
5662 /* Add cfs_rq with load or one or more already running entities to the list */
5663 if (!cfs_rq_is_decayed(cfs_rq))
5664 list_add_leaf_cfs_rq(cfs_rq);
5666 if (cfs_rq->throttled_clock_self) {
5667 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5669 cfs_rq->throttled_clock_self = 0;
5671 if (SCHED_WARN_ON((s64)delta < 0))
5674 cfs_rq->throttled_clock_self_time += delta;
5681 static int tg_throttle_down(struct task_group *tg, void *data)
5683 struct rq *rq = data;
5684 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5686 /* group is entering throttled state, stop time */
5687 if (!cfs_rq->throttle_count) {
5688 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5689 list_del_leaf_cfs_rq(cfs_rq);
5691 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5692 if (cfs_rq->nr_running)
5693 cfs_rq->throttled_clock_self = rq_clock(rq);
5695 cfs_rq->throttle_count++;
5700 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5702 struct rq *rq = rq_of(cfs_rq);
5703 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5704 struct sched_entity *se;
5705 long task_delta, idle_task_delta, dequeue = 1;
5707 raw_spin_lock(&cfs_b->lock);
5708 /* This will start the period timer if necessary */
5709 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5711 * We have raced with bandwidth becoming available, and if we
5712 * actually throttled the timer might not unthrottle us for an
5713 * entire period. We additionally needed to make sure that any
5714 * subsequent check_cfs_rq_runtime calls agree not to throttle
5715 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5716 * for 1ns of runtime rather than just check cfs_b.
5720 list_add_tail_rcu(&cfs_rq->throttled_list,
5721 &cfs_b->throttled_cfs_rq);
5723 raw_spin_unlock(&cfs_b->lock);
5726 return false; /* Throttle no longer required. */
5728 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5730 /* freeze hierarchy runnable averages while throttled */
5732 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5735 task_delta = cfs_rq->h_nr_running;
5736 idle_task_delta = cfs_rq->idle_h_nr_running;
5737 for_each_sched_entity(se) {
5738 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5739 /* throttled entity or throttle-on-deactivate */
5743 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5745 if (cfs_rq_is_idle(group_cfs_rq(se)))
5746 idle_task_delta = cfs_rq->h_nr_running;
5748 qcfs_rq->h_nr_running -= task_delta;
5749 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5751 if (qcfs_rq->load.weight) {
5752 /* Avoid re-evaluating load for this entity: */
5753 se = parent_entity(se);
5758 for_each_sched_entity(se) {
5759 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5760 /* throttled entity or throttle-on-deactivate */
5764 update_load_avg(qcfs_rq, se, 0);
5765 se_update_runnable(se);
5767 if (cfs_rq_is_idle(group_cfs_rq(se)))
5768 idle_task_delta = cfs_rq->h_nr_running;
5770 qcfs_rq->h_nr_running -= task_delta;
5771 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5774 /* At this point se is NULL and we are at root level*/
5775 sub_nr_running(rq, task_delta);
5779 * Note: distribution will already see us throttled via the
5780 * throttled-list. rq->lock protects completion.
5782 cfs_rq->throttled = 1;
5783 SCHED_WARN_ON(cfs_rq->throttled_clock);
5784 if (cfs_rq->nr_running)
5785 cfs_rq->throttled_clock = rq_clock(rq);
5789 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5791 struct rq *rq = rq_of(cfs_rq);
5792 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5793 struct sched_entity *se;
5794 long task_delta, idle_task_delta;
5796 se = cfs_rq->tg->se[cpu_of(rq)];
5798 cfs_rq->throttled = 0;
5800 update_rq_clock(rq);
5802 raw_spin_lock(&cfs_b->lock);
5803 if (cfs_rq->throttled_clock) {
5804 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5805 cfs_rq->throttled_clock = 0;
5807 list_del_rcu(&cfs_rq->throttled_list);
5808 raw_spin_unlock(&cfs_b->lock);
5810 /* update hierarchical throttle state */
5811 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5813 if (!cfs_rq->load.weight) {
5814 if (!cfs_rq->on_list)
5817 * Nothing to run but something to decay (on_list)?
5818 * Complete the branch.
5820 for_each_sched_entity(se) {
5821 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5824 goto unthrottle_throttle;
5827 task_delta = cfs_rq->h_nr_running;
5828 idle_task_delta = cfs_rq->idle_h_nr_running;
5829 for_each_sched_entity(se) {
5830 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5834 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5836 if (cfs_rq_is_idle(group_cfs_rq(se)))
5837 idle_task_delta = cfs_rq->h_nr_running;
5839 qcfs_rq->h_nr_running += task_delta;
5840 qcfs_rq->idle_h_nr_running += idle_task_delta;
5842 /* end evaluation on encountering a throttled cfs_rq */
5843 if (cfs_rq_throttled(qcfs_rq))
5844 goto unthrottle_throttle;
5847 for_each_sched_entity(se) {
5848 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5850 update_load_avg(qcfs_rq, se, UPDATE_TG);
5851 se_update_runnable(se);
5853 if (cfs_rq_is_idle(group_cfs_rq(se)))
5854 idle_task_delta = cfs_rq->h_nr_running;
5856 qcfs_rq->h_nr_running += task_delta;
5857 qcfs_rq->idle_h_nr_running += idle_task_delta;
5859 /* end evaluation on encountering a throttled cfs_rq */
5860 if (cfs_rq_throttled(qcfs_rq))
5861 goto unthrottle_throttle;
5864 /* At this point se is NULL and we are at root level*/
5865 add_nr_running(rq, task_delta);
5867 unthrottle_throttle:
5868 assert_list_leaf_cfs_rq(rq);
5870 /* Determine whether we need to wake up potentially idle CPU: */
5871 if (rq->curr == rq->idle && rq->cfs.nr_running)
5876 static void __cfsb_csd_unthrottle(void *arg)
5878 struct cfs_rq *cursor, *tmp;
5879 struct rq *rq = arg;
5885 * Iterating over the list can trigger several call to
5886 * update_rq_clock() in unthrottle_cfs_rq().
5887 * Do it once and skip the potential next ones.
5889 update_rq_clock(rq);
5890 rq_clock_start_loop_update(rq);
5893 * Since we hold rq lock we're safe from concurrent manipulation of
5894 * the CSD list. However, this RCU critical section annotates the
5895 * fact that we pair with sched_free_group_rcu(), so that we cannot
5896 * race with group being freed in the window between removing it
5897 * from the list and advancing to the next entry in the list.
5901 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5902 throttled_csd_list) {
5903 list_del_init(&cursor->throttled_csd_list);
5905 if (cfs_rq_throttled(cursor))
5906 unthrottle_cfs_rq(cursor);
5911 rq_clock_stop_loop_update(rq);
5915 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5917 struct rq *rq = rq_of(cfs_rq);
5920 if (rq == this_rq()) {
5921 unthrottle_cfs_rq(cfs_rq);
5925 /* Already enqueued */
5926 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5929 first = list_empty(&rq->cfsb_csd_list);
5930 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5932 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5935 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5937 unthrottle_cfs_rq(cfs_rq);
5941 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5943 lockdep_assert_rq_held(rq_of(cfs_rq));
5945 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5946 cfs_rq->runtime_remaining <= 0))
5949 __unthrottle_cfs_rq_async(cfs_rq);
5952 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5954 int this_cpu = smp_processor_id();
5955 u64 runtime, remaining = 1;
5956 bool throttled = false;
5957 struct cfs_rq *cfs_rq, *tmp;
5960 LIST_HEAD(local_unthrottle);
5963 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5972 rq_lock_irqsave(rq, &rf);
5973 if (!cfs_rq_throttled(cfs_rq))
5976 /* Already queued for async unthrottle */
5977 if (!list_empty(&cfs_rq->throttled_csd_list))
5980 /* By the above checks, this should never be true */
5981 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5983 raw_spin_lock(&cfs_b->lock);
5984 runtime = -cfs_rq->runtime_remaining + 1;
5985 if (runtime > cfs_b->runtime)
5986 runtime = cfs_b->runtime;
5987 cfs_b->runtime -= runtime;
5988 remaining = cfs_b->runtime;
5989 raw_spin_unlock(&cfs_b->lock);
5991 cfs_rq->runtime_remaining += runtime;
5993 /* we check whether we're throttled above */
5994 if (cfs_rq->runtime_remaining > 0) {
5995 if (cpu_of(rq) != this_cpu) {
5996 unthrottle_cfs_rq_async(cfs_rq);
5999 * We currently only expect to be unthrottling
6000 * a single cfs_rq locally.
6002 SCHED_WARN_ON(!list_empty(&local_unthrottle));
6003 list_add_tail(&cfs_rq->throttled_csd_list,
6011 rq_unlock_irqrestore(rq, &rf);
6014 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6015 throttled_csd_list) {
6016 struct rq *rq = rq_of(cfs_rq);
6018 rq_lock_irqsave(rq, &rf);
6020 list_del_init(&cfs_rq->throttled_csd_list);
6022 if (cfs_rq_throttled(cfs_rq))
6023 unthrottle_cfs_rq(cfs_rq);
6025 rq_unlock_irqrestore(rq, &rf);
6027 SCHED_WARN_ON(!list_empty(&local_unthrottle));
6035 * Responsible for refilling a task_group's bandwidth and unthrottling its
6036 * cfs_rqs as appropriate. If there has been no activity within the last
6037 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6038 * used to track this state.
6040 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6044 /* no need to continue the timer with no bandwidth constraint */
6045 if (cfs_b->quota == RUNTIME_INF)
6046 goto out_deactivate;
6048 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6049 cfs_b->nr_periods += overrun;
6051 /* Refill extra burst quota even if cfs_b->idle */
6052 __refill_cfs_bandwidth_runtime(cfs_b);
6055 * idle depends on !throttled (for the case of a large deficit), and if
6056 * we're going inactive then everything else can be deferred
6058 if (cfs_b->idle && !throttled)
6059 goto out_deactivate;
6062 /* mark as potentially idle for the upcoming period */
6067 /* account preceding periods in which throttling occurred */
6068 cfs_b->nr_throttled += overrun;
6071 * This check is repeated as we release cfs_b->lock while we unthrottle.
6073 while (throttled && cfs_b->runtime > 0) {
6074 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6075 /* we can't nest cfs_b->lock while distributing bandwidth */
6076 throttled = distribute_cfs_runtime(cfs_b);
6077 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6081 * While we are ensured activity in the period following an
6082 * unthrottle, this also covers the case in which the new bandwidth is
6083 * insufficient to cover the existing bandwidth deficit. (Forcing the
6084 * timer to remain active while there are any throttled entities.)
6094 /* a cfs_rq won't donate quota below this amount */
6095 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6096 /* minimum remaining period time to redistribute slack quota */
6097 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6098 /* how long we wait to gather additional slack before distributing */
6099 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6102 * Are we near the end of the current quota period?
6104 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6105 * hrtimer base being cleared by hrtimer_start. In the case of
6106 * migrate_hrtimers, base is never cleared, so we are fine.
6108 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6110 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6113 /* if the call-back is running a quota refresh is already occurring */
6114 if (hrtimer_callback_running(refresh_timer))
6117 /* is a quota refresh about to occur? */
6118 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6119 if (remaining < (s64)min_expire)
6125 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6127 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6129 /* if there's a quota refresh soon don't bother with slack */
6130 if (runtime_refresh_within(cfs_b, min_left))
6133 /* don't push forwards an existing deferred unthrottle */
6134 if (cfs_b->slack_started)
6136 cfs_b->slack_started = true;
6138 hrtimer_start(&cfs_b->slack_timer,
6139 ns_to_ktime(cfs_bandwidth_slack_period),
6143 /* we know any runtime found here is valid as update_curr() precedes return */
6144 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6146 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6147 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6149 if (slack_runtime <= 0)
6152 raw_spin_lock(&cfs_b->lock);
6153 if (cfs_b->quota != RUNTIME_INF) {
6154 cfs_b->runtime += slack_runtime;
6156 /* we are under rq->lock, defer unthrottling using a timer */
6157 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6158 !list_empty(&cfs_b->throttled_cfs_rq))
6159 start_cfs_slack_bandwidth(cfs_b);
6161 raw_spin_unlock(&cfs_b->lock);
6163 /* even if it's not valid for return we don't want to try again */
6164 cfs_rq->runtime_remaining -= slack_runtime;
6167 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6169 if (!cfs_bandwidth_used())
6172 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6175 __return_cfs_rq_runtime(cfs_rq);
6179 * This is done with a timer (instead of inline with bandwidth return) since
6180 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6182 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6184 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6185 unsigned long flags;
6187 /* confirm we're still not at a refresh boundary */
6188 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6189 cfs_b->slack_started = false;
6191 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6192 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6196 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6197 runtime = cfs_b->runtime;
6199 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6204 distribute_cfs_runtime(cfs_b);
6208 * When a group wakes up we want to make sure that its quota is not already
6209 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6210 * runtime as update_curr() throttling can not trigger until it's on-rq.
6212 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6214 if (!cfs_bandwidth_used())
6217 /* an active group must be handled by the update_curr()->put() path */
6218 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6221 /* ensure the group is not already throttled */
6222 if (cfs_rq_throttled(cfs_rq))
6225 /* update runtime allocation */
6226 account_cfs_rq_runtime(cfs_rq, 0);
6227 if (cfs_rq->runtime_remaining <= 0)
6228 throttle_cfs_rq(cfs_rq);
6231 static void sync_throttle(struct task_group *tg, int cpu)
6233 struct cfs_rq *pcfs_rq, *cfs_rq;
6235 if (!cfs_bandwidth_used())
6241 cfs_rq = tg->cfs_rq[cpu];
6242 pcfs_rq = tg->parent->cfs_rq[cpu];
6244 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6245 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6248 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6249 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6251 if (!cfs_bandwidth_used())
6254 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6258 * it's possible for a throttled entity to be forced into a running
6259 * state (e.g. set_curr_task), in this case we're finished.
6261 if (cfs_rq_throttled(cfs_rq))
6264 return throttle_cfs_rq(cfs_rq);
6267 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6269 struct cfs_bandwidth *cfs_b =
6270 container_of(timer, struct cfs_bandwidth, slack_timer);
6272 do_sched_cfs_slack_timer(cfs_b);
6274 return HRTIMER_NORESTART;
6277 extern const u64 max_cfs_quota_period;
6279 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6281 struct cfs_bandwidth *cfs_b =
6282 container_of(timer, struct cfs_bandwidth, period_timer);
6283 unsigned long flags;
6288 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6290 overrun = hrtimer_forward_now(timer, cfs_b->period);
6294 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6297 u64 new, old = ktime_to_ns(cfs_b->period);
6300 * Grow period by a factor of 2 to avoid losing precision.
6301 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6305 if (new < max_cfs_quota_period) {
6306 cfs_b->period = ns_to_ktime(new);
6310 pr_warn_ratelimited(
6311 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6313 div_u64(new, NSEC_PER_USEC),
6314 div_u64(cfs_b->quota, NSEC_PER_USEC));
6316 pr_warn_ratelimited(
6317 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6319 div_u64(old, NSEC_PER_USEC),
6320 div_u64(cfs_b->quota, NSEC_PER_USEC));
6323 /* reset count so we don't come right back in here */
6328 cfs_b->period_active = 0;
6329 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6331 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6334 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6336 raw_spin_lock_init(&cfs_b->lock);
6338 cfs_b->quota = RUNTIME_INF;
6339 cfs_b->period = ns_to_ktime(default_cfs_period());
6341 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6343 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6344 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6345 cfs_b->period_timer.function = sched_cfs_period_timer;
6347 /* Add a random offset so that timers interleave */
6348 hrtimer_set_expires(&cfs_b->period_timer,
6349 get_random_u32_below(cfs_b->period));
6350 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6351 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6352 cfs_b->slack_started = false;
6355 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6357 cfs_rq->runtime_enabled = 0;
6358 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6359 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6362 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6364 lockdep_assert_held(&cfs_b->lock);
6366 if (cfs_b->period_active)
6369 cfs_b->period_active = 1;
6370 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6371 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6374 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6376 int __maybe_unused i;
6378 /* init_cfs_bandwidth() was not called */
6379 if (!cfs_b->throttled_cfs_rq.next)
6382 hrtimer_cancel(&cfs_b->period_timer);
6383 hrtimer_cancel(&cfs_b->slack_timer);
6386 * It is possible that we still have some cfs_rq's pending on a CSD
6387 * list, though this race is very rare. In order for this to occur, we
6388 * must have raced with the last task leaving the group while there
6389 * exist throttled cfs_rq(s), and the period_timer must have queued the
6390 * CSD item but the remote cpu has not yet processed it. To handle this,
6391 * we can simply flush all pending CSD work inline here. We're
6392 * guaranteed at this point that no additional cfs_rq of this group can
6396 for_each_possible_cpu(i) {
6397 struct rq *rq = cpu_rq(i);
6398 unsigned long flags;
6400 if (list_empty(&rq->cfsb_csd_list))
6403 local_irq_save(flags);
6404 __cfsb_csd_unthrottle(rq);
6405 local_irq_restore(flags);
6411 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6413 * The race is harmless, since modifying bandwidth settings of unhooked group
6414 * bits doesn't do much.
6417 /* cpu online callback */
6418 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6420 struct task_group *tg;
6422 lockdep_assert_rq_held(rq);
6425 list_for_each_entry_rcu(tg, &task_groups, list) {
6426 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6427 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6429 raw_spin_lock(&cfs_b->lock);
6430 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6431 raw_spin_unlock(&cfs_b->lock);
6436 /* cpu offline callback */
6437 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6439 struct task_group *tg;
6441 lockdep_assert_rq_held(rq);
6444 * The rq clock has already been updated in the
6445 * set_rq_offline(), so we should skip updating
6446 * the rq clock again in unthrottle_cfs_rq().
6448 rq_clock_start_loop_update(rq);
6451 list_for_each_entry_rcu(tg, &task_groups, list) {
6452 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6454 if (!cfs_rq->runtime_enabled)
6458 * clock_task is not advancing so we just need to make sure
6459 * there's some valid quota amount
6461 cfs_rq->runtime_remaining = 1;
6463 * Offline rq is schedulable till CPU is completely disabled
6464 * in take_cpu_down(), so we prevent new cfs throttling here.
6466 cfs_rq->runtime_enabled = 0;
6468 if (cfs_rq_throttled(cfs_rq))
6469 unthrottle_cfs_rq(cfs_rq);
6473 rq_clock_stop_loop_update(rq);
6476 bool cfs_task_bw_constrained(struct task_struct *p)
6478 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6480 if (!cfs_bandwidth_used())
6483 if (cfs_rq->runtime_enabled ||
6484 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6490 #ifdef CONFIG_NO_HZ_FULL
6491 /* called from pick_next_task_fair() */
6492 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6494 int cpu = cpu_of(rq);
6496 if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6499 if (!tick_nohz_full_cpu(cpu))
6502 if (rq->nr_running != 1)
6506 * We know there is only one task runnable and we've just picked it. The
6507 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6508 * be otherwise able to stop the tick. Just need to check if we are using
6509 * bandwidth control.
6511 if (cfs_task_bw_constrained(p))
6512 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6516 #else /* CONFIG_CFS_BANDWIDTH */
6518 static inline bool cfs_bandwidth_used(void)
6523 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6524 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6525 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6526 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6527 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6529 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6534 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6539 static inline int throttled_lb_pair(struct task_group *tg,
6540 int src_cpu, int dest_cpu)
6545 #ifdef CONFIG_FAIR_GROUP_SCHED
6546 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6547 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6550 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6554 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6555 static inline void update_runtime_enabled(struct rq *rq) {}
6556 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6557 #ifdef CONFIG_CGROUP_SCHED
6558 bool cfs_task_bw_constrained(struct task_struct *p)
6563 #endif /* CONFIG_CFS_BANDWIDTH */
6565 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6566 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6569 /**************************************************
6570 * CFS operations on tasks:
6573 #ifdef CONFIG_SCHED_HRTICK
6574 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6576 struct sched_entity *se = &p->se;
6578 SCHED_WARN_ON(task_rq(p) != rq);
6580 if (rq->cfs.h_nr_running > 1) {
6581 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6582 u64 slice = se->slice;
6583 s64 delta = slice - ran;
6586 if (task_current(rq, p))
6590 hrtick_start(rq, delta);
6595 * called from enqueue/dequeue and updates the hrtick when the
6596 * current task is from our class and nr_running is low enough
6599 static void hrtick_update(struct rq *rq)
6601 struct task_struct *curr = rq->curr;
6603 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6606 hrtick_start_fair(rq, curr);
6608 #else /* !CONFIG_SCHED_HRTICK */
6610 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6614 static inline void hrtick_update(struct rq *rq)
6620 static inline bool cpu_overutilized(int cpu)
6622 unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6623 unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6625 /* Return true only if the utilization doesn't fit CPU's capacity */
6626 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6629 static inline void update_overutilized_status(struct rq *rq)
6631 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6632 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6633 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6637 static inline void update_overutilized_status(struct rq *rq) { }
6640 /* Runqueue only has SCHED_IDLE tasks enqueued */
6641 static int sched_idle_rq(struct rq *rq)
6643 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6648 static int sched_idle_cpu(int cpu)
6650 return sched_idle_rq(cpu_rq(cpu));
6655 * The enqueue_task method is called before nr_running is
6656 * increased. Here we update the fair scheduling stats and
6657 * then put the task into the rbtree:
6660 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6662 struct cfs_rq *cfs_rq;
6663 struct sched_entity *se = &p->se;
6664 int idle_h_nr_running = task_has_idle_policy(p);
6665 int task_new = !(flags & ENQUEUE_WAKEUP);
6668 * The code below (indirectly) updates schedutil which looks at
6669 * the cfs_rq utilization to select a frequency.
6670 * Let's add the task's estimated utilization to the cfs_rq's
6671 * estimated utilization, before we update schedutil.
6673 util_est_enqueue(&rq->cfs, p);
6676 * If in_iowait is set, the code below may not trigger any cpufreq
6677 * utilization updates, so do it here explicitly with the IOWAIT flag
6681 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6683 for_each_sched_entity(se) {
6686 cfs_rq = cfs_rq_of(se);
6687 enqueue_entity(cfs_rq, se, flags);
6689 cfs_rq->h_nr_running++;
6690 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6692 if (cfs_rq_is_idle(cfs_rq))
6693 idle_h_nr_running = 1;
6695 /* end evaluation on encountering a throttled cfs_rq */
6696 if (cfs_rq_throttled(cfs_rq))
6697 goto enqueue_throttle;
6699 flags = ENQUEUE_WAKEUP;
6702 for_each_sched_entity(se) {
6703 cfs_rq = cfs_rq_of(se);
6705 update_load_avg(cfs_rq, se, UPDATE_TG);
6706 se_update_runnable(se);
6707 update_cfs_group(se);
6709 cfs_rq->h_nr_running++;
6710 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6712 if (cfs_rq_is_idle(cfs_rq))
6713 idle_h_nr_running = 1;
6715 /* end evaluation on encountering a throttled cfs_rq */
6716 if (cfs_rq_throttled(cfs_rq))
6717 goto enqueue_throttle;
6720 /* At this point se is NULL and we are at root level*/
6721 add_nr_running(rq, 1);
6724 * Since new tasks are assigned an initial util_avg equal to
6725 * half of the spare capacity of their CPU, tiny tasks have the
6726 * ability to cross the overutilized threshold, which will
6727 * result in the load balancer ruining all the task placement
6728 * done by EAS. As a way to mitigate that effect, do not account
6729 * for the first enqueue operation of new tasks during the
6730 * overutilized flag detection.
6732 * A better way of solving this problem would be to wait for
6733 * the PELT signals of tasks to converge before taking them
6734 * into account, but that is not straightforward to implement,
6735 * and the following generally works well enough in practice.
6738 update_overutilized_status(rq);
6741 assert_list_leaf_cfs_rq(rq);
6746 static void set_next_buddy(struct sched_entity *se);
6749 * The dequeue_task method is called before nr_running is
6750 * decreased. We remove the task from the rbtree and
6751 * update the fair scheduling stats:
6753 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6755 struct cfs_rq *cfs_rq;
6756 struct sched_entity *se = &p->se;
6757 int task_sleep = flags & DEQUEUE_SLEEP;
6758 int idle_h_nr_running = task_has_idle_policy(p);
6759 bool was_sched_idle = sched_idle_rq(rq);
6761 util_est_dequeue(&rq->cfs, p);
6763 for_each_sched_entity(se) {
6764 cfs_rq = cfs_rq_of(se);
6765 dequeue_entity(cfs_rq, se, flags);
6767 cfs_rq->h_nr_running--;
6768 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6770 if (cfs_rq_is_idle(cfs_rq))
6771 idle_h_nr_running = 1;
6773 /* end evaluation on encountering a throttled cfs_rq */
6774 if (cfs_rq_throttled(cfs_rq))
6775 goto dequeue_throttle;
6777 /* Don't dequeue parent if it has other entities besides us */
6778 if (cfs_rq->load.weight) {
6779 /* Avoid re-evaluating load for this entity: */
6780 se = parent_entity(se);
6782 * Bias pick_next to pick a task from this cfs_rq, as
6783 * p is sleeping when it is within its sched_slice.
6785 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6789 flags |= DEQUEUE_SLEEP;
6792 for_each_sched_entity(se) {
6793 cfs_rq = cfs_rq_of(se);
6795 update_load_avg(cfs_rq, se, UPDATE_TG);
6796 se_update_runnable(se);
6797 update_cfs_group(se);
6799 cfs_rq->h_nr_running--;
6800 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6802 if (cfs_rq_is_idle(cfs_rq))
6803 idle_h_nr_running = 1;
6805 /* end evaluation on encountering a throttled cfs_rq */
6806 if (cfs_rq_throttled(cfs_rq))
6807 goto dequeue_throttle;
6811 /* At this point se is NULL and we are at root level*/
6812 sub_nr_running(rq, 1);
6814 /* balance early to pull high priority tasks */
6815 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6816 rq->next_balance = jiffies;
6819 util_est_update(&rq->cfs, p, task_sleep);
6825 /* Working cpumask for: load_balance, load_balance_newidle. */
6826 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6827 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6828 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6830 #ifdef CONFIG_NO_HZ_COMMON
6833 cpumask_var_t idle_cpus_mask;
6835 int has_blocked; /* Idle CPUS has blocked load */
6836 int needs_update; /* Newly idle CPUs need their next_balance collated */
6837 unsigned long next_balance; /* in jiffy units */
6838 unsigned long next_blocked; /* Next update of blocked load in jiffies */
6839 } nohz ____cacheline_aligned;
6841 #endif /* CONFIG_NO_HZ_COMMON */
6843 static unsigned long cpu_load(struct rq *rq)
6845 return cfs_rq_load_avg(&rq->cfs);
6849 * cpu_load_without - compute CPU load without any contributions from *p
6850 * @cpu: the CPU which load is requested
6851 * @p: the task which load should be discounted
6853 * The load of a CPU is defined by the load of tasks currently enqueued on that
6854 * CPU as well as tasks which are currently sleeping after an execution on that
6857 * This method returns the load of the specified CPU by discounting the load of
6858 * the specified task, whenever the task is currently contributing to the CPU
6861 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6863 struct cfs_rq *cfs_rq;
6866 /* Task has no contribution or is new */
6867 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6868 return cpu_load(rq);
6871 load = READ_ONCE(cfs_rq->avg.load_avg);
6873 /* Discount task's util from CPU's util */
6874 lsub_positive(&load, task_h_load(p));
6879 static unsigned long cpu_runnable(struct rq *rq)
6881 return cfs_rq_runnable_avg(&rq->cfs);
6884 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6886 struct cfs_rq *cfs_rq;
6887 unsigned int runnable;
6889 /* Task has no contribution or is new */
6890 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6891 return cpu_runnable(rq);
6894 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6896 /* Discount task's runnable from CPU's runnable */
6897 lsub_positive(&runnable, p->se.avg.runnable_avg);
6902 static unsigned long capacity_of(int cpu)
6904 return cpu_rq(cpu)->cpu_capacity;
6907 static void record_wakee(struct task_struct *p)
6910 * Only decay a single time; tasks that have less then 1 wakeup per
6911 * jiffy will not have built up many flips.
6913 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6914 current->wakee_flips >>= 1;
6915 current->wakee_flip_decay_ts = jiffies;
6918 if (current->last_wakee != p) {
6919 current->last_wakee = p;
6920 current->wakee_flips++;
6925 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6927 * A waker of many should wake a different task than the one last awakened
6928 * at a frequency roughly N times higher than one of its wakees.
6930 * In order to determine whether we should let the load spread vs consolidating
6931 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6932 * partner, and a factor of lls_size higher frequency in the other.
6934 * With both conditions met, we can be relatively sure that the relationship is
6935 * non-monogamous, with partner count exceeding socket size.
6937 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6938 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6941 static int wake_wide(struct task_struct *p)
6943 unsigned int master = current->wakee_flips;
6944 unsigned int slave = p->wakee_flips;
6945 int factor = __this_cpu_read(sd_llc_size);
6948 swap(master, slave);
6949 if (slave < factor || master < slave * factor)
6955 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6956 * soonest. For the purpose of speed we only consider the waking and previous
6959 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6960 * cache-affine and is (or will be) idle.
6962 * wake_affine_weight() - considers the weight to reflect the average
6963 * scheduling latency of the CPUs. This seems to work
6964 * for the overloaded case.
6967 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6970 * If this_cpu is idle, it implies the wakeup is from interrupt
6971 * context. Only allow the move if cache is shared. Otherwise an
6972 * interrupt intensive workload could force all tasks onto one
6973 * node depending on the IO topology or IRQ affinity settings.
6975 * If the prev_cpu is idle and cache affine then avoid a migration.
6976 * There is no guarantee that the cache hot data from an interrupt
6977 * is more important than cache hot data on the prev_cpu and from
6978 * a cpufreq perspective, it's better to have higher utilisation
6981 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6982 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6984 if (sync && cpu_rq(this_cpu)->nr_running == 1)
6987 if (available_idle_cpu(prev_cpu))
6990 return nr_cpumask_bits;
6994 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6995 int this_cpu, int prev_cpu, int sync)
6997 s64 this_eff_load, prev_eff_load;
6998 unsigned long task_load;
7000 this_eff_load = cpu_load(cpu_rq(this_cpu));
7003 unsigned long current_load = task_h_load(current);
7005 if (current_load > this_eff_load)
7008 this_eff_load -= current_load;
7011 task_load = task_h_load(p);
7013 this_eff_load += task_load;
7014 if (sched_feat(WA_BIAS))
7015 this_eff_load *= 100;
7016 this_eff_load *= capacity_of(prev_cpu);
7018 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7019 prev_eff_load -= task_load;
7020 if (sched_feat(WA_BIAS))
7021 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7022 prev_eff_load *= capacity_of(this_cpu);
7025 * If sync, adjust the weight of prev_eff_load such that if
7026 * prev_eff == this_eff that select_idle_sibling() will consider
7027 * stacking the wakee on top of the waker if no other CPU is
7033 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7036 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7037 int this_cpu, int prev_cpu, int sync)
7039 int target = nr_cpumask_bits;
7041 if (sched_feat(WA_IDLE))
7042 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7044 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7045 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7047 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7048 if (target != this_cpu)
7051 schedstat_inc(sd->ttwu_move_affine);
7052 schedstat_inc(p->stats.nr_wakeups_affine);
7056 static struct sched_group *
7057 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7060 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
7063 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7065 unsigned long load, min_load = ULONG_MAX;
7066 unsigned int min_exit_latency = UINT_MAX;
7067 u64 latest_idle_timestamp = 0;
7068 int least_loaded_cpu = this_cpu;
7069 int shallowest_idle_cpu = -1;
7072 /* Check if we have any choice: */
7073 if (group->group_weight == 1)
7074 return cpumask_first(sched_group_span(group));
7076 /* Traverse only the allowed CPUs */
7077 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7078 struct rq *rq = cpu_rq(i);
7080 if (!sched_core_cookie_match(rq, p))
7083 if (sched_idle_cpu(i))
7086 if (available_idle_cpu(i)) {
7087 struct cpuidle_state *idle = idle_get_state(rq);
7088 if (idle && idle->exit_latency < min_exit_latency) {
7090 * We give priority to a CPU whose idle state
7091 * has the smallest exit latency irrespective
7092 * of any idle timestamp.
7094 min_exit_latency = idle->exit_latency;
7095 latest_idle_timestamp = rq->idle_stamp;
7096 shallowest_idle_cpu = i;
7097 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7098 rq->idle_stamp > latest_idle_timestamp) {
7100 * If equal or no active idle state, then
7101 * the most recently idled CPU might have
7104 latest_idle_timestamp = rq->idle_stamp;
7105 shallowest_idle_cpu = i;
7107 } else if (shallowest_idle_cpu == -1) {
7108 load = cpu_load(cpu_rq(i));
7109 if (load < min_load) {
7111 least_loaded_cpu = i;
7116 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7119 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
7120 int cpu, int prev_cpu, int sd_flag)
7124 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7128 * We need task's util for cpu_util_without, sync it up to
7129 * prev_cpu's last_update_time.
7131 if (!(sd_flag & SD_BALANCE_FORK))
7132 sync_entity_load_avg(&p->se);
7135 struct sched_group *group;
7136 struct sched_domain *tmp;
7139 if (!(sd->flags & sd_flag)) {
7144 group = find_idlest_group(sd, p, cpu);
7150 new_cpu = find_idlest_group_cpu(group, p, cpu);
7151 if (new_cpu == cpu) {
7152 /* Now try balancing at a lower domain level of 'cpu': */
7157 /* Now try balancing at a lower domain level of 'new_cpu': */
7159 weight = sd->span_weight;
7161 for_each_domain(cpu, tmp) {
7162 if (weight <= tmp->span_weight)
7164 if (tmp->flags & sd_flag)
7172 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7174 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7175 sched_cpu_cookie_match(cpu_rq(cpu), p))
7181 #ifdef CONFIG_SCHED_SMT
7182 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7183 EXPORT_SYMBOL_GPL(sched_smt_present);
7185 static inline void set_idle_cores(int cpu, int val)
7187 struct sched_domain_shared *sds;
7189 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7191 WRITE_ONCE(sds->has_idle_cores, val);
7194 static inline bool test_idle_cores(int cpu)
7196 struct sched_domain_shared *sds;
7198 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7200 return READ_ONCE(sds->has_idle_cores);
7206 * Scans the local SMT mask to see if the entire core is idle, and records this
7207 * information in sd_llc_shared->has_idle_cores.
7209 * Since SMT siblings share all cache levels, inspecting this limited remote
7210 * state should be fairly cheap.
7212 void __update_idle_core(struct rq *rq)
7214 int core = cpu_of(rq);
7218 if (test_idle_cores(core))
7221 for_each_cpu(cpu, cpu_smt_mask(core)) {
7225 if (!available_idle_cpu(cpu))
7229 set_idle_cores(core, 1);
7235 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7236 * there are no idle cores left in the system; tracked through
7237 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7239 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7244 for_each_cpu(cpu, cpu_smt_mask(core)) {
7245 if (!available_idle_cpu(cpu)) {
7247 if (*idle_cpu == -1) {
7248 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
7256 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
7263 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7268 * Scan the local SMT mask for idle CPUs.
7270 static int select_idle_smt(struct task_struct *p, int target)
7274 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7277 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7284 #else /* CONFIG_SCHED_SMT */
7286 static inline void set_idle_cores(int cpu, int val)
7290 static inline bool test_idle_cores(int cpu)
7295 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7297 return __select_idle_cpu(core, p);
7300 static inline int select_idle_smt(struct task_struct *p, int target)
7305 #endif /* CONFIG_SCHED_SMT */
7308 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7309 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7310 * average idle time for this rq (as found in rq->avg_idle).
7312 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7314 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7315 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7316 struct sched_domain_shared *sd_share;
7318 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7320 if (sched_feat(SIS_UTIL)) {
7321 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7323 /* because !--nr is the condition to stop scan */
7324 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7325 /* overloaded LLC is unlikely to have idle cpu/core */
7331 if (static_branch_unlikely(&sched_cluster_active)) {
7332 struct sched_group *sg = sd->groups;
7334 if (sg->flags & SD_CLUSTER) {
7335 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7336 if (!cpumask_test_cpu(cpu, cpus))
7339 if (has_idle_core) {
7340 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7341 if ((unsigned int)i < nr_cpumask_bits)
7346 idle_cpu = __select_idle_cpu(cpu, p);
7347 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7351 cpumask_andnot(cpus, cpus, sched_group_span(sg));
7355 for_each_cpu_wrap(cpu, cpus, target + 1) {
7356 if (has_idle_core) {
7357 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7358 if ((unsigned int)i < nr_cpumask_bits)
7364 idle_cpu = __select_idle_cpu(cpu, p);
7365 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7371 set_idle_cores(target, false);
7377 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7378 * the task fits. If no CPU is big enough, but there are idle ones, try to
7379 * maximize capacity.
7382 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7384 unsigned long task_util, util_min, util_max, best_cap = 0;
7385 int fits, best_fits = 0;
7386 int cpu, best_cpu = -1;
7387 struct cpumask *cpus;
7389 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7390 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7392 task_util = task_util_est(p);
7393 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7394 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7396 for_each_cpu_wrap(cpu, cpus, target) {
7397 unsigned long cpu_cap = capacity_of(cpu);
7399 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7402 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7404 /* This CPU fits with all requirements */
7408 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7409 * Look for the CPU with best capacity.
7412 cpu_cap = arch_scale_cpu_capacity(cpu) - thermal_load_avg(cpu_rq(cpu));
7415 * First, select CPU which fits better (-1 being better than 0).
7416 * Then, select the one with best capacity at same level.
7418 if ((fits < best_fits) ||
7419 ((fits == best_fits) && (cpu_cap > best_cap))) {
7429 static inline bool asym_fits_cpu(unsigned long util,
7430 unsigned long util_min,
7431 unsigned long util_max,
7434 if (sched_asym_cpucap_active())
7436 * Return true only if the cpu fully fits the task requirements
7437 * which include the utilization and the performance hints.
7439 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7445 * Try and locate an idle core/thread in the LLC cache domain.
7447 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7449 bool has_idle_core = false;
7450 struct sched_domain *sd;
7451 unsigned long task_util, util_min, util_max;
7452 int i, recent_used_cpu, prev_aff = -1;
7455 * On asymmetric system, update task utilization because we will check
7456 * that the task fits with cpu's capacity.
7458 if (sched_asym_cpucap_active()) {
7459 sync_entity_load_avg(&p->se);
7460 task_util = task_util_est(p);
7461 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7462 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7466 * per-cpu select_rq_mask usage
7468 lockdep_assert_irqs_disabled();
7470 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7471 asym_fits_cpu(task_util, util_min, util_max, target))
7475 * If the previous CPU is cache affine and idle, don't be stupid:
7477 if (prev != target && cpus_share_cache(prev, target) &&
7478 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7479 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7481 if (!static_branch_unlikely(&sched_cluster_active) ||
7482 cpus_share_resources(prev, target))
7489 * Allow a per-cpu kthread to stack with the wakee if the
7490 * kworker thread and the tasks previous CPUs are the same.
7491 * The assumption is that the wakee queued work for the
7492 * per-cpu kthread that is now complete and the wakeup is
7493 * essentially a sync wakeup. An obvious example of this
7494 * pattern is IO completions.
7496 if (is_per_cpu_kthread(current) &&
7498 prev == smp_processor_id() &&
7499 this_rq()->nr_running <= 1 &&
7500 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7504 /* Check a recently used CPU as a potential idle candidate: */
7505 recent_used_cpu = p->recent_used_cpu;
7506 p->recent_used_cpu = prev;
7507 if (recent_used_cpu != prev &&
7508 recent_used_cpu != target &&
7509 cpus_share_cache(recent_used_cpu, target) &&
7510 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7511 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7512 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7514 if (!static_branch_unlikely(&sched_cluster_active) ||
7515 cpus_share_resources(recent_used_cpu, target))
7516 return recent_used_cpu;
7519 recent_used_cpu = -1;
7523 * For asymmetric CPU capacity systems, our domain of interest is
7524 * sd_asym_cpucapacity rather than sd_llc.
7526 if (sched_asym_cpucap_active()) {
7527 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7529 * On an asymmetric CPU capacity system where an exclusive
7530 * cpuset defines a symmetric island (i.e. one unique
7531 * capacity_orig value through the cpuset), the key will be set
7532 * but the CPUs within that cpuset will not have a domain with
7533 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7537 i = select_idle_capacity(p, sd, target);
7538 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7542 sd = rcu_dereference(per_cpu(sd_llc, target));
7546 if (sched_smt_active()) {
7547 has_idle_core = test_idle_cores(target);
7549 if (!has_idle_core && cpus_share_cache(prev, target)) {
7550 i = select_idle_smt(p, prev);
7551 if ((unsigned int)i < nr_cpumask_bits)
7556 i = select_idle_cpu(p, sd, has_idle_core, target);
7557 if ((unsigned)i < nr_cpumask_bits)
7561 * For cluster machines which have lower sharing cache like L2 or
7562 * LLC Tag, we tend to find an idle CPU in the target's cluster
7563 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7564 * use them if possible when no idle CPU found in select_idle_cpu().
7566 if ((unsigned int)prev_aff < nr_cpumask_bits)
7568 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7569 return recent_used_cpu;
7575 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7576 * @cpu: the CPU to get the utilization for
7577 * @p: task for which the CPU utilization should be predicted or NULL
7578 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7579 * @boost: 1 to enable boosting, otherwise 0
7581 * The unit of the return value must be the same as the one of CPU capacity
7582 * so that CPU utilization can be compared with CPU capacity.
7584 * CPU utilization is the sum of running time of runnable tasks plus the
7585 * recent utilization of currently non-runnable tasks on that CPU.
7586 * It represents the amount of CPU capacity currently used by CFS tasks in
7587 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7588 * capacity at f_max.
7590 * The estimated CPU utilization is defined as the maximum between CPU
7591 * utilization and sum of the estimated utilization of the currently
7592 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7593 * previously-executed tasks, which helps better deduce how busy a CPU will
7594 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7595 * of such a task would be significantly decayed at this point of time.
7597 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7598 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7599 * utilization. Boosting is implemented in cpu_util() so that internal
7600 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7601 * latter via cpu_util_cfs_boost().
7603 * CPU utilization can be higher than the current CPU capacity
7604 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7605 * of rounding errors as well as task migrations or wakeups of new tasks.
7606 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7607 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7608 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7609 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7610 * though since this is useful for predicting the CPU capacity required
7611 * after task migrations (scheduler-driven DVFS).
7613 * Return: (Boosted) (estimated) utilization for the specified CPU.
7615 static unsigned long
7616 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7618 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7619 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7620 unsigned long runnable;
7623 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7624 util = max(util, runnable);
7628 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7629 * contribution. If @p migrates from another CPU to @cpu add its
7630 * contribution. In all the other cases @cpu is not impacted by the
7631 * migration so its util_avg is already correct.
7633 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7634 lsub_positive(&util, task_util(p));
7635 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7636 util += task_util(p);
7638 if (sched_feat(UTIL_EST)) {
7639 unsigned long util_est;
7641 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7644 * During wake-up @p isn't enqueued yet and doesn't contribute
7645 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7646 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7647 * has been enqueued.
7649 * During exec (@dst_cpu = -1) @p is enqueued and does
7650 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7651 * Remove it to "simulate" cpu_util without @p's contribution.
7653 * Despite the task_on_rq_queued(@p) check there is still a
7654 * small window for a possible race when an exec
7655 * select_task_rq_fair() races with LB's detach_task().
7659 * p->on_rq = TASK_ON_RQ_MIGRATING;
7660 * -------------------------------- A
7662 * dequeue_task_fair() + Race Time
7663 * util_est_dequeue() /
7664 * -------------------------------- B
7666 * The additional check "current == p" is required to further
7667 * reduce the race window.
7670 util_est += _task_util_est(p);
7671 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7672 lsub_positive(&util_est, _task_util_est(p));
7674 util = max(util, util_est);
7677 return min(util, arch_scale_cpu_capacity(cpu));
7680 unsigned long cpu_util_cfs(int cpu)
7682 return cpu_util(cpu, NULL, -1, 0);
7685 unsigned long cpu_util_cfs_boost(int cpu)
7687 return cpu_util(cpu, NULL, -1, 1);
7691 * cpu_util_without: compute cpu utilization without any contributions from *p
7692 * @cpu: the CPU which utilization is requested
7693 * @p: the task which utilization should be discounted
7695 * The utilization of a CPU is defined by the utilization of tasks currently
7696 * enqueued on that CPU as well as tasks which are currently sleeping after an
7697 * execution on that CPU.
7699 * This method returns the utilization of the specified CPU by discounting the
7700 * utilization of the specified task, whenever the task is currently
7701 * contributing to the CPU utilization.
7703 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7705 /* Task has no contribution or is new */
7706 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7709 return cpu_util(cpu, p, -1, 0);
7713 * energy_env - Utilization landscape for energy estimation.
7714 * @task_busy_time: Utilization contribution by the task for which we test the
7715 * placement. Given by eenv_task_busy_time().
7716 * @pd_busy_time: Utilization of the whole perf domain without the task
7717 * contribution. Given by eenv_pd_busy_time().
7718 * @cpu_cap: Maximum CPU capacity for the perf domain.
7719 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7722 unsigned long task_busy_time;
7723 unsigned long pd_busy_time;
7724 unsigned long cpu_cap;
7725 unsigned long pd_cap;
7729 * Compute the task busy time for compute_energy(). This time cannot be
7730 * injected directly into effective_cpu_util() because of the IRQ scaling.
7731 * The latter only makes sense with the most recent CPUs where the task has
7734 static inline void eenv_task_busy_time(struct energy_env *eenv,
7735 struct task_struct *p, int prev_cpu)
7737 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7738 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7740 if (unlikely(irq >= max_cap))
7741 busy_time = max_cap;
7743 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7745 eenv->task_busy_time = busy_time;
7749 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7750 * utilization for each @pd_cpus, it however doesn't take into account
7751 * clamping since the ratio (utilization / cpu_capacity) is already enough to
7752 * scale the EM reported power consumption at the (eventually clamped)
7755 * The contribution of the task @p for which we want to estimate the
7756 * energy cost is removed (by cpu_util()) and must be calculated
7757 * separately (see eenv_task_busy_time). This ensures:
7759 * - A stable PD utilization, no matter which CPU of that PD we want to place
7762 * - A fair comparison between CPUs as the task contribution (task_util())
7763 * will always be the same no matter which CPU utilization we rely on
7764 * (util_avg or util_est).
7766 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7767 * exceed @eenv->pd_cap.
7769 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7770 struct cpumask *pd_cpus,
7771 struct task_struct *p)
7773 unsigned long busy_time = 0;
7776 for_each_cpu(cpu, pd_cpus) {
7777 unsigned long util = cpu_util(cpu, p, -1, 0);
7779 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7782 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7786 * Compute the maximum utilization for compute_energy() when the task @p
7787 * is placed on the cpu @dst_cpu.
7789 * Returns the maximum utilization among @eenv->cpus. This utilization can't
7790 * exceed @eenv->cpu_cap.
7792 static inline unsigned long
7793 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7794 struct task_struct *p, int dst_cpu)
7796 unsigned long max_util = 0;
7799 for_each_cpu(cpu, pd_cpus) {
7800 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7801 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7802 unsigned long eff_util;
7805 * Performance domain frequency: utilization clamping
7806 * must be considered since it affects the selection
7807 * of the performance domain frequency.
7808 * NOTE: in case RT tasks are running, by default the
7809 * FREQUENCY_UTIL's utilization can be max OPP.
7811 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7812 max_util = max(max_util, eff_util);
7815 return min(max_util, eenv->cpu_cap);
7819 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7820 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7821 * contribution is ignored.
7823 static inline unsigned long
7824 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7825 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7827 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7828 unsigned long busy_time = eenv->pd_busy_time;
7829 unsigned long energy;
7832 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7834 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7836 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
7842 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7843 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7844 * spare capacity in each performance domain and uses it as a potential
7845 * candidate to execute the task. Then, it uses the Energy Model to figure
7846 * out which of the CPU candidates is the most energy-efficient.
7848 * The rationale for this heuristic is as follows. In a performance domain,
7849 * all the most energy efficient CPU candidates (according to the Energy
7850 * Model) are those for which we'll request a low frequency. When there are
7851 * several CPUs for which the frequency request will be the same, we don't
7852 * have enough data to break the tie between them, because the Energy Model
7853 * only includes active power costs. With this model, if we assume that
7854 * frequency requests follow utilization (e.g. using schedutil), the CPU with
7855 * the maximum spare capacity in a performance domain is guaranteed to be among
7856 * the best candidates of the performance domain.
7858 * In practice, it could be preferable from an energy standpoint to pack
7859 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7860 * but that could also hurt our chances to go cluster idle, and we have no
7861 * ways to tell with the current Energy Model if this is actually a good
7862 * idea or not. So, find_energy_efficient_cpu() basically favors
7863 * cluster-packing, and spreading inside a cluster. That should at least be
7864 * a good thing for latency, and this is consistent with the idea that most
7865 * of the energy savings of EAS come from the asymmetry of the system, and
7866 * not so much from breaking the tie between identical CPUs. That's also the
7867 * reason why EAS is enabled in the topology code only for systems where
7868 * SD_ASYM_CPUCAPACITY is set.
7870 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7871 * they don't have any useful utilization data yet and it's not possible to
7872 * forecast their impact on energy consumption. Consequently, they will be
7873 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7874 * to be energy-inefficient in some use-cases. The alternative would be to
7875 * bias new tasks towards specific types of CPUs first, or to try to infer
7876 * their util_avg from the parent task, but those heuristics could hurt
7877 * other use-cases too. So, until someone finds a better way to solve this,
7878 * let's keep things simple by re-using the existing slow path.
7880 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7882 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7883 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7884 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7885 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7886 struct root_domain *rd = this_rq()->rd;
7887 int cpu, best_energy_cpu, target = -1;
7888 int prev_fits = -1, best_fits = -1;
7889 unsigned long best_thermal_cap = 0;
7890 unsigned long prev_thermal_cap = 0;
7891 struct sched_domain *sd;
7892 struct perf_domain *pd;
7893 struct energy_env eenv;
7896 pd = rcu_dereference(rd->pd);
7897 if (!pd || READ_ONCE(rd->overutilized))
7901 * Energy-aware wake-up happens on the lowest sched_domain starting
7902 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7904 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7905 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7912 sync_entity_load_avg(&p->se);
7913 if (!task_util_est(p) && p_util_min == 0)
7916 eenv_task_busy_time(&eenv, p, prev_cpu);
7918 for (; pd; pd = pd->next) {
7919 unsigned long util_min = p_util_min, util_max = p_util_max;
7920 unsigned long cpu_cap, cpu_thermal_cap, util;
7921 long prev_spare_cap = -1, max_spare_cap = -1;
7922 unsigned long rq_util_min, rq_util_max;
7923 unsigned long cur_delta, base_energy;
7924 int max_spare_cap_cpu = -1;
7925 int fits, max_fits = -1;
7927 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7929 if (cpumask_empty(cpus))
7932 /* Account thermal pressure for the energy estimation */
7933 cpu = cpumask_first(cpus);
7934 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7935 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7937 eenv.cpu_cap = cpu_thermal_cap;
7940 for_each_cpu(cpu, cpus) {
7941 struct rq *rq = cpu_rq(cpu);
7943 eenv.pd_cap += cpu_thermal_cap;
7945 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7948 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7951 util = cpu_util(cpu, p, cpu, 0);
7952 cpu_cap = capacity_of(cpu);
7955 * Skip CPUs that cannot satisfy the capacity request.
7956 * IOW, placing the task there would make the CPU
7957 * overutilized. Take uclamp into account to see how
7958 * much capacity we can get out of the CPU; this is
7959 * aligned with sched_cpu_util().
7961 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7963 * Open code uclamp_rq_util_with() except for
7964 * the clamp() part. Ie: apply max aggregation
7965 * only. util_fits_cpu() logic requires to
7966 * operate on non clamped util but must use the
7967 * max-aggregated uclamp_{min, max}.
7969 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7970 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7972 util_min = max(rq_util_min, p_util_min);
7973 util_max = max(rq_util_max, p_util_max);
7976 fits = util_fits_cpu(util, util_min, util_max, cpu);
7980 lsub_positive(&cpu_cap, util);
7982 if (cpu == prev_cpu) {
7983 /* Always use prev_cpu as a candidate. */
7984 prev_spare_cap = cpu_cap;
7986 } else if ((fits > max_fits) ||
7987 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
7989 * Find the CPU with the maximum spare capacity
7990 * among the remaining CPUs in the performance
7993 max_spare_cap = cpu_cap;
7994 max_spare_cap_cpu = cpu;
7999 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8002 eenv_pd_busy_time(&eenv, cpus, p);
8003 /* Compute the 'base' energy of the pd, without @p */
8004 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8006 /* Evaluate the energy impact of using prev_cpu. */
8007 if (prev_spare_cap > -1) {
8008 prev_delta = compute_energy(&eenv, pd, cpus, p,
8010 /* CPU utilization has changed */
8011 if (prev_delta < base_energy)
8013 prev_delta -= base_energy;
8014 prev_thermal_cap = cpu_thermal_cap;
8015 best_delta = min(best_delta, prev_delta);
8018 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8019 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8020 /* Current best energy cpu fits better */
8021 if (max_fits < best_fits)
8025 * Both don't fit performance hint (i.e. uclamp_min)
8026 * but best energy cpu has better capacity.
8028 if ((max_fits < 0) &&
8029 (cpu_thermal_cap <= best_thermal_cap))
8032 cur_delta = compute_energy(&eenv, pd, cpus, p,
8034 /* CPU utilization has changed */
8035 if (cur_delta < base_energy)
8037 cur_delta -= base_energy;
8040 * Both fit for the task but best energy cpu has lower
8043 if ((max_fits > 0) && (best_fits > 0) &&
8044 (cur_delta >= best_delta))
8047 best_delta = cur_delta;
8048 best_energy_cpu = max_spare_cap_cpu;
8049 best_fits = max_fits;
8050 best_thermal_cap = cpu_thermal_cap;
8055 if ((best_fits > prev_fits) ||
8056 ((best_fits > 0) && (best_delta < prev_delta)) ||
8057 ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
8058 target = best_energy_cpu;
8069 * select_task_rq_fair: Select target runqueue for the waking task in domains
8070 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8071 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8073 * Balances load by selecting the idlest CPU in the idlest group, or under
8074 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8076 * Returns the target CPU number.
8079 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8081 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8082 struct sched_domain *tmp, *sd = NULL;
8083 int cpu = smp_processor_id();
8084 int new_cpu = prev_cpu;
8085 int want_affine = 0;
8086 /* SD_flags and WF_flags share the first nibble */
8087 int sd_flag = wake_flags & 0xF;
8090 * required for stable ->cpus_allowed
8092 lockdep_assert_held(&p->pi_lock);
8093 if (wake_flags & WF_TTWU) {
8096 if ((wake_flags & WF_CURRENT_CPU) &&
8097 cpumask_test_cpu(cpu, p->cpus_ptr))
8100 if (sched_energy_enabled()) {
8101 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8107 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8111 for_each_domain(cpu, tmp) {
8113 * If both 'cpu' and 'prev_cpu' are part of this domain,
8114 * cpu is a valid SD_WAKE_AFFINE target.
8116 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8117 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8118 if (cpu != prev_cpu)
8119 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8121 sd = NULL; /* Prefer wake_affine over balance flags */
8126 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8127 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8128 * will usually go to the fast path.
8130 if (tmp->flags & sd_flag)
8132 else if (!want_affine)
8138 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
8139 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
8141 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8149 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8150 * cfs_rq_of(p) references at time of call are still valid and identify the
8151 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8153 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8155 struct sched_entity *se = &p->se;
8157 if (!task_on_rq_migrating(p)) {
8158 remove_entity_load_avg(se);
8161 * Here, the task's PELT values have been updated according to
8162 * the current rq's clock. But if that clock hasn't been
8163 * updated in a while, a substantial idle time will be missed,
8164 * leading to an inflation after wake-up on the new rq.
8166 * Estimate the missing time from the cfs_rq last_update_time
8167 * and update sched_avg to improve the PELT continuity after
8170 migrate_se_pelt_lag(se);
8173 /* Tell new CPU we are migrated */
8174 se->avg.last_update_time = 0;
8176 update_scan_period(p, new_cpu);
8179 static void task_dead_fair(struct task_struct *p)
8181 remove_entity_load_avg(&p->se);
8185 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8190 return newidle_balance(rq, rf) != 0;
8192 #endif /* CONFIG_SMP */
8194 static void set_next_buddy(struct sched_entity *se)
8196 for_each_sched_entity(se) {
8197 if (SCHED_WARN_ON(!se->on_rq))
8201 cfs_rq_of(se)->next = se;
8206 * Preempt the current task with a newly woken task if needed:
8208 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8210 struct task_struct *curr = rq->curr;
8211 struct sched_entity *se = &curr->se, *pse = &p->se;
8212 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8213 int next_buddy_marked = 0;
8214 int cse_is_idle, pse_is_idle;
8216 if (unlikely(se == pse))
8220 * This is possible from callers such as attach_tasks(), in which we
8221 * unconditionally wakeup_preempt() after an enqueue (which may have
8222 * lead to a throttle). This both saves work and prevents false
8223 * next-buddy nomination below.
8225 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8228 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8229 set_next_buddy(pse);
8230 next_buddy_marked = 1;
8234 * We can come here with TIF_NEED_RESCHED already set from new task
8237 * Note: this also catches the edge-case of curr being in a throttled
8238 * group (e.g. via set_curr_task), since update_curr() (in the
8239 * enqueue of curr) will have resulted in resched being set. This
8240 * prevents us from potentially nominating it as a false LAST_BUDDY
8243 if (test_tsk_need_resched(curr))
8246 /* Idle tasks are by definition preempted by non-idle tasks. */
8247 if (unlikely(task_has_idle_policy(curr)) &&
8248 likely(!task_has_idle_policy(p)))
8252 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8253 * is driven by the tick):
8255 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8258 find_matching_se(&se, &pse);
8261 cse_is_idle = se_is_idle(se);
8262 pse_is_idle = se_is_idle(pse);
8265 * Preempt an idle group in favor of a non-idle group (and don't preempt
8266 * in the inverse case).
8268 if (cse_is_idle && !pse_is_idle)
8270 if (cse_is_idle != pse_is_idle)
8273 cfs_rq = cfs_rq_of(se);
8274 update_curr(cfs_rq);
8277 * XXX pick_eevdf(cfs_rq) != se ?
8279 if (pick_eevdf(cfs_rq) == pse)
8289 static struct task_struct *pick_task_fair(struct rq *rq)
8291 struct sched_entity *se;
8292 struct cfs_rq *cfs_rq;
8296 if (!cfs_rq->nr_running)
8300 struct sched_entity *curr = cfs_rq->curr;
8302 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8305 update_curr(cfs_rq);
8309 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8313 se = pick_next_entity(cfs_rq);
8314 cfs_rq = group_cfs_rq(se);
8321 struct task_struct *
8322 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8324 struct cfs_rq *cfs_rq = &rq->cfs;
8325 struct sched_entity *se;
8326 struct task_struct *p;
8330 if (!sched_fair_runnable(rq))
8333 #ifdef CONFIG_FAIR_GROUP_SCHED
8334 if (!prev || prev->sched_class != &fair_sched_class)
8338 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8339 * likely that a next task is from the same cgroup as the current.
8341 * Therefore attempt to avoid putting and setting the entire cgroup
8342 * hierarchy, only change the part that actually changes.
8346 struct sched_entity *curr = cfs_rq->curr;
8349 * Since we got here without doing put_prev_entity() we also
8350 * have to consider cfs_rq->curr. If it is still a runnable
8351 * entity, update_curr() will update its vruntime, otherwise
8352 * forget we've ever seen it.
8356 update_curr(cfs_rq);
8361 * This call to check_cfs_rq_runtime() will do the
8362 * throttle and dequeue its entity in the parent(s).
8363 * Therefore the nr_running test will indeed
8366 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8369 if (!cfs_rq->nr_running)
8376 se = pick_next_entity(cfs_rq);
8377 cfs_rq = group_cfs_rq(se);
8383 * Since we haven't yet done put_prev_entity and if the selected task
8384 * is a different task than we started out with, try and touch the
8385 * least amount of cfs_rqs.
8388 struct sched_entity *pse = &prev->se;
8390 while (!(cfs_rq = is_same_group(se, pse))) {
8391 int se_depth = se->depth;
8392 int pse_depth = pse->depth;
8394 if (se_depth <= pse_depth) {
8395 put_prev_entity(cfs_rq_of(pse), pse);
8396 pse = parent_entity(pse);
8398 if (se_depth >= pse_depth) {
8399 set_next_entity(cfs_rq_of(se), se);
8400 se = parent_entity(se);
8404 put_prev_entity(cfs_rq, pse);
8405 set_next_entity(cfs_rq, se);
8412 put_prev_task(rq, prev);
8415 se = pick_next_entity(cfs_rq);
8416 set_next_entity(cfs_rq, se);
8417 cfs_rq = group_cfs_rq(se);
8422 done: __maybe_unused;
8425 * Move the next running task to the front of
8426 * the list, so our cfs_tasks list becomes MRU
8429 list_move(&p->se.group_node, &rq->cfs_tasks);
8432 if (hrtick_enabled_fair(rq))
8433 hrtick_start_fair(rq, p);
8435 update_misfit_status(p, rq);
8436 sched_fair_update_stop_tick(rq, p);
8444 new_tasks = newidle_balance(rq, rf);
8447 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8448 * possible for any higher priority task to appear. In that case we
8449 * must re-start the pick_next_entity() loop.
8458 * rq is about to be idle, check if we need to update the
8459 * lost_idle_time of clock_pelt
8461 update_idle_rq_clock_pelt(rq);
8466 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8468 return pick_next_task_fair(rq, NULL, NULL);
8472 * Account for a descheduled task:
8474 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8476 struct sched_entity *se = &prev->se;
8477 struct cfs_rq *cfs_rq;
8479 for_each_sched_entity(se) {
8480 cfs_rq = cfs_rq_of(se);
8481 put_prev_entity(cfs_rq, se);
8486 * sched_yield() is very simple
8488 static void yield_task_fair(struct rq *rq)
8490 struct task_struct *curr = rq->curr;
8491 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8492 struct sched_entity *se = &curr->se;
8495 * Are we the only task in the tree?
8497 if (unlikely(rq->nr_running == 1))
8500 clear_buddies(cfs_rq, se);
8502 update_rq_clock(rq);
8504 * Update run-time statistics of the 'current'.
8506 update_curr(cfs_rq);
8508 * Tell update_rq_clock() that we've just updated,
8509 * so we don't do microscopic update in schedule()
8510 * and double the fastpath cost.
8512 rq_clock_skip_update(rq);
8514 se->deadline += calc_delta_fair(se->slice, se);
8517 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8519 struct sched_entity *se = &p->se;
8521 /* throttled hierarchies are not runnable */
8522 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8525 /* Tell the scheduler that we'd really like pse to run next. */
8528 yield_task_fair(rq);
8534 /**************************************************
8535 * Fair scheduling class load-balancing methods.
8539 * The purpose of load-balancing is to achieve the same basic fairness the
8540 * per-CPU scheduler provides, namely provide a proportional amount of compute
8541 * time to each task. This is expressed in the following equation:
8543 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8545 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8546 * W_i,0 is defined as:
8548 * W_i,0 = \Sum_j w_i,j (2)
8550 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8551 * is derived from the nice value as per sched_prio_to_weight[].
8553 * The weight average is an exponential decay average of the instantaneous
8556 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8558 * C_i is the compute capacity of CPU i, typically it is the
8559 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8560 * can also include other factors [XXX].
8562 * To achieve this balance we define a measure of imbalance which follows
8563 * directly from (1):
8565 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8567 * We them move tasks around to minimize the imbalance. In the continuous
8568 * function space it is obvious this converges, in the discrete case we get
8569 * a few fun cases generally called infeasible weight scenarios.
8572 * - infeasible weights;
8573 * - local vs global optima in the discrete case. ]
8578 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8579 * for all i,j solution, we create a tree of CPUs that follows the hardware
8580 * topology where each level pairs two lower groups (or better). This results
8581 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8582 * tree to only the first of the previous level and we decrease the frequency
8583 * of load-balance at each level inv. proportional to the number of CPUs in
8589 * \Sum { --- * --- * 2^i } = O(n) (5)
8591 * `- size of each group
8592 * | | `- number of CPUs doing load-balance
8594 * `- sum over all levels
8596 * Coupled with a limit on how many tasks we can migrate every balance pass,
8597 * this makes (5) the runtime complexity of the balancer.
8599 * An important property here is that each CPU is still (indirectly) connected
8600 * to every other CPU in at most O(log n) steps:
8602 * The adjacency matrix of the resulting graph is given by:
8605 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8608 * And you'll find that:
8610 * A^(log_2 n)_i,j != 0 for all i,j (7)
8612 * Showing there's indeed a path between every CPU in at most O(log n) steps.
8613 * The task movement gives a factor of O(m), giving a convergence complexity
8616 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8621 * In order to avoid CPUs going idle while there's still work to do, new idle
8622 * balancing is more aggressive and has the newly idle CPU iterate up the domain
8623 * tree itself instead of relying on other CPUs to bring it work.
8625 * This adds some complexity to both (5) and (8) but it reduces the total idle
8633 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8636 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8641 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8643 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8645 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8648 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8649 * rewrite all of this once again.]
8652 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8654 enum fbq_type { regular, remote, all };
8657 * 'group_type' describes the group of CPUs at the moment of load balancing.
8659 * The enum is ordered by pulling priority, with the group with lowest priority
8660 * first so the group_type can simply be compared when selecting the busiest
8661 * group. See update_sd_pick_busiest().
8664 /* The group has spare capacity that can be used to run more tasks. */
8665 group_has_spare = 0,
8667 * The group is fully used and the tasks don't compete for more CPU
8668 * cycles. Nevertheless, some tasks might wait before running.
8672 * One task doesn't fit with CPU's capacity and must be migrated to a
8673 * more powerful CPU.
8677 * Balance SMT group that's fully busy. Can benefit from migration
8678 * a task on SMT with busy sibling to another CPU on idle core.
8682 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8683 * and the task should be migrated to it instead of running on the
8688 * The tasks' affinity constraints previously prevented the scheduler
8689 * from balancing the load across the system.
8693 * The CPU is overloaded and can't provide expected CPU cycles to all
8699 enum migration_type {
8706 #define LBF_ALL_PINNED 0x01
8707 #define LBF_NEED_BREAK 0x02
8708 #define LBF_DST_PINNED 0x04
8709 #define LBF_SOME_PINNED 0x08
8710 #define LBF_ACTIVE_LB 0x10
8713 struct sched_domain *sd;
8721 struct cpumask *dst_grpmask;
8723 enum cpu_idle_type idle;
8725 /* The set of CPUs under consideration for load-balancing */
8726 struct cpumask *cpus;
8731 unsigned int loop_break;
8732 unsigned int loop_max;
8734 enum fbq_type fbq_type;
8735 enum migration_type migration_type;
8736 struct list_head tasks;
8740 * Is this task likely cache-hot:
8742 static int task_hot(struct task_struct *p, struct lb_env *env)
8746 lockdep_assert_rq_held(env->src_rq);
8748 if (p->sched_class != &fair_sched_class)
8751 if (unlikely(task_has_idle_policy(p)))
8754 /* SMT siblings share cache */
8755 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8759 * Buddy candidates are cache hot:
8761 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8762 (&p->se == cfs_rq_of(&p->se)->next))
8765 if (sysctl_sched_migration_cost == -1)
8769 * Don't migrate task if the task's cookie does not match
8770 * with the destination CPU's core cookie.
8772 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8775 if (sysctl_sched_migration_cost == 0)
8778 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8780 return delta < (s64)sysctl_sched_migration_cost;
8783 #ifdef CONFIG_NUMA_BALANCING
8785 * Returns 1, if task migration degrades locality
8786 * Returns 0, if task migration improves locality i.e migration preferred.
8787 * Returns -1, if task migration is not affected by locality.
8789 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8791 struct numa_group *numa_group = rcu_dereference(p->numa_group);
8792 unsigned long src_weight, dst_weight;
8793 int src_nid, dst_nid, dist;
8795 if (!static_branch_likely(&sched_numa_balancing))
8798 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8801 src_nid = cpu_to_node(env->src_cpu);
8802 dst_nid = cpu_to_node(env->dst_cpu);
8804 if (src_nid == dst_nid)
8807 /* Migrating away from the preferred node is always bad. */
8808 if (src_nid == p->numa_preferred_nid) {
8809 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8815 /* Encourage migration to the preferred node. */
8816 if (dst_nid == p->numa_preferred_nid)
8819 /* Leaving a core idle is often worse than degrading locality. */
8820 if (env->idle == CPU_IDLE)
8823 dist = node_distance(src_nid, dst_nid);
8825 src_weight = group_weight(p, src_nid, dist);
8826 dst_weight = group_weight(p, dst_nid, dist);
8828 src_weight = task_weight(p, src_nid, dist);
8829 dst_weight = task_weight(p, dst_nid, dist);
8832 return dst_weight < src_weight;
8836 static inline int migrate_degrades_locality(struct task_struct *p,
8844 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8847 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8851 lockdep_assert_rq_held(env->src_rq);
8854 * We do not migrate tasks that are:
8855 * 1) throttled_lb_pair, or
8856 * 2) cannot be migrated to this CPU due to cpus_ptr, or
8857 * 3) running (obviously), or
8858 * 4) are cache-hot on their current CPU.
8860 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8863 /* Disregard pcpu kthreads; they are where they need to be. */
8864 if (kthread_is_per_cpu(p))
8867 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8870 schedstat_inc(p->stats.nr_failed_migrations_affine);
8872 env->flags |= LBF_SOME_PINNED;
8875 * Remember if this task can be migrated to any other CPU in
8876 * our sched_group. We may want to revisit it if we couldn't
8877 * meet load balance goals by pulling other tasks on src_cpu.
8879 * Avoid computing new_dst_cpu
8881 * - if we have already computed one in current iteration
8882 * - if it's an active balance
8884 if (env->idle == CPU_NEWLY_IDLE ||
8885 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8888 /* Prevent to re-select dst_cpu via env's CPUs: */
8889 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8890 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8891 env->flags |= LBF_DST_PINNED;
8892 env->new_dst_cpu = cpu;
8900 /* Record that we found at least one task that could run on dst_cpu */
8901 env->flags &= ~LBF_ALL_PINNED;
8903 if (task_on_cpu(env->src_rq, p)) {
8904 schedstat_inc(p->stats.nr_failed_migrations_running);
8909 * Aggressive migration if:
8911 * 2) destination numa is preferred
8912 * 3) task is cache cold, or
8913 * 4) too many balance attempts have failed.
8915 if (env->flags & LBF_ACTIVE_LB)
8918 tsk_cache_hot = migrate_degrades_locality(p, env);
8919 if (tsk_cache_hot == -1)
8920 tsk_cache_hot = task_hot(p, env);
8922 if (tsk_cache_hot <= 0 ||
8923 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
8924 if (tsk_cache_hot == 1) {
8925 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
8926 schedstat_inc(p->stats.nr_forced_migrations);
8931 schedstat_inc(p->stats.nr_failed_migrations_hot);
8936 * detach_task() -- detach the task for the migration specified in env
8938 static void detach_task(struct task_struct *p, struct lb_env *env)
8940 lockdep_assert_rq_held(env->src_rq);
8942 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8943 set_task_cpu(p, env->dst_cpu);
8947 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8948 * part of active balancing operations within "domain".
8950 * Returns a task if successful and NULL otherwise.
8952 static struct task_struct *detach_one_task(struct lb_env *env)
8954 struct task_struct *p;
8956 lockdep_assert_rq_held(env->src_rq);
8958 list_for_each_entry_reverse(p,
8959 &env->src_rq->cfs_tasks, se.group_node) {
8960 if (!can_migrate_task(p, env))
8963 detach_task(p, env);
8966 * Right now, this is only the second place where
8967 * lb_gained[env->idle] is updated (other is detach_tasks)
8968 * so we can safely collect stats here rather than
8969 * inside detach_tasks().
8971 schedstat_inc(env->sd->lb_gained[env->idle]);
8978 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8979 * busiest_rq, as part of a balancing operation within domain "sd".
8981 * Returns number of detached tasks if successful and 0 otherwise.
8983 static int detach_tasks(struct lb_env *env)
8985 struct list_head *tasks = &env->src_rq->cfs_tasks;
8986 unsigned long util, load;
8987 struct task_struct *p;
8990 lockdep_assert_rq_held(env->src_rq);
8993 * Source run queue has been emptied by another CPU, clear
8994 * LBF_ALL_PINNED flag as we will not test any task.
8996 if (env->src_rq->nr_running <= 1) {
8997 env->flags &= ~LBF_ALL_PINNED;
9001 if (env->imbalance <= 0)
9004 while (!list_empty(tasks)) {
9006 * We don't want to steal all, otherwise we may be treated likewise,
9007 * which could at worst lead to a livelock crash.
9009 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
9014 * We've more or less seen every task there is, call it quits
9015 * unless we haven't found any movable task yet.
9017 if (env->loop > env->loop_max &&
9018 !(env->flags & LBF_ALL_PINNED))
9021 /* take a breather every nr_migrate tasks */
9022 if (env->loop > env->loop_break) {
9023 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9024 env->flags |= LBF_NEED_BREAK;
9028 p = list_last_entry(tasks, struct task_struct, se.group_node);
9030 if (!can_migrate_task(p, env))
9033 switch (env->migration_type) {
9036 * Depending of the number of CPUs and tasks and the
9037 * cgroup hierarchy, task_h_load() can return a null
9038 * value. Make sure that env->imbalance decreases
9039 * otherwise detach_tasks() will stop only after
9040 * detaching up to loop_max tasks.
9042 load = max_t(unsigned long, task_h_load(p), 1);
9044 if (sched_feat(LB_MIN) &&
9045 load < 16 && !env->sd->nr_balance_failed)
9049 * Make sure that we don't migrate too much load.
9050 * Nevertheless, let relax the constraint if
9051 * scheduler fails to find a good waiting task to
9054 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9057 env->imbalance -= load;
9061 util = task_util_est(p);
9063 if (util > env->imbalance)
9066 env->imbalance -= util;
9073 case migrate_misfit:
9074 /* This is not a misfit task */
9075 if (task_fits_cpu(p, env->src_cpu))
9082 detach_task(p, env);
9083 list_add(&p->se.group_node, &env->tasks);
9087 #ifdef CONFIG_PREEMPTION
9089 * NEWIDLE balancing is a source of latency, so preemptible
9090 * kernels will stop after the first task is detached to minimize
9091 * the critical section.
9093 if (env->idle == CPU_NEWLY_IDLE)
9098 * We only want to steal up to the prescribed amount of
9101 if (env->imbalance <= 0)
9106 list_move(&p->se.group_node, tasks);
9110 * Right now, this is one of only two places we collect this stat
9111 * so we can safely collect detach_one_task() stats here rather
9112 * than inside detach_one_task().
9114 schedstat_add(env->sd->lb_gained[env->idle], detached);
9120 * attach_task() -- attach the task detached by detach_task() to its new rq.
9122 static void attach_task(struct rq *rq, struct task_struct *p)
9124 lockdep_assert_rq_held(rq);
9126 WARN_ON_ONCE(task_rq(p) != rq);
9127 activate_task(rq, p, ENQUEUE_NOCLOCK);
9128 wakeup_preempt(rq, p, 0);
9132 * attach_one_task() -- attaches the task returned from detach_one_task() to
9135 static void attach_one_task(struct rq *rq, struct task_struct *p)
9140 update_rq_clock(rq);
9146 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9149 static void attach_tasks(struct lb_env *env)
9151 struct list_head *tasks = &env->tasks;
9152 struct task_struct *p;
9155 rq_lock(env->dst_rq, &rf);
9156 update_rq_clock(env->dst_rq);
9158 while (!list_empty(tasks)) {
9159 p = list_first_entry(tasks, struct task_struct, se.group_node);
9160 list_del_init(&p->se.group_node);
9162 attach_task(env->dst_rq, p);
9165 rq_unlock(env->dst_rq, &rf);
9168 #ifdef CONFIG_NO_HZ_COMMON
9169 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9171 if (cfs_rq->avg.load_avg)
9174 if (cfs_rq->avg.util_avg)
9180 static inline bool others_have_blocked(struct rq *rq)
9182 if (READ_ONCE(rq->avg_rt.util_avg))
9185 if (READ_ONCE(rq->avg_dl.util_avg))
9188 if (thermal_load_avg(rq))
9191 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
9192 if (READ_ONCE(rq->avg_irq.util_avg))
9199 static inline void update_blocked_load_tick(struct rq *rq)
9201 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9204 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9207 rq->has_blocked_load = 0;
9210 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
9211 static inline bool others_have_blocked(struct rq *rq) { return false; }
9212 static inline void update_blocked_load_tick(struct rq *rq) {}
9213 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9216 static bool __update_blocked_others(struct rq *rq, bool *done)
9218 const struct sched_class *curr_class;
9219 u64 now = rq_clock_pelt(rq);
9220 unsigned long thermal_pressure;
9224 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9225 * DL and IRQ signals have been updated before updating CFS.
9227 curr_class = rq->curr->sched_class;
9229 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9231 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9232 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9233 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9234 update_irq_load_avg(rq, 0);
9236 if (others_have_blocked(rq))
9242 #ifdef CONFIG_FAIR_GROUP_SCHED
9244 static bool __update_blocked_fair(struct rq *rq, bool *done)
9246 struct cfs_rq *cfs_rq, *pos;
9247 bool decayed = false;
9248 int cpu = cpu_of(rq);
9251 * Iterates the task_group tree in a bottom up fashion, see
9252 * list_add_leaf_cfs_rq() for details.
9254 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9255 struct sched_entity *se;
9257 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9258 update_tg_load_avg(cfs_rq);
9260 if (cfs_rq->nr_running == 0)
9261 update_idle_cfs_rq_clock_pelt(cfs_rq);
9263 if (cfs_rq == &rq->cfs)
9267 /* Propagate pending load changes to the parent, if any: */
9268 se = cfs_rq->tg->se[cpu];
9269 if (se && !skip_blocked_update(se))
9270 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9273 * There can be a lot of idle CPU cgroups. Don't let fully
9274 * decayed cfs_rqs linger on the list.
9276 if (cfs_rq_is_decayed(cfs_rq))
9277 list_del_leaf_cfs_rq(cfs_rq);
9279 /* Don't need periodic decay once load/util_avg are null */
9280 if (cfs_rq_has_blocked(cfs_rq))
9288 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9289 * This needs to be done in a top-down fashion because the load of a child
9290 * group is a fraction of its parents load.
9292 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9294 struct rq *rq = rq_of(cfs_rq);
9295 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9296 unsigned long now = jiffies;
9299 if (cfs_rq->last_h_load_update == now)
9302 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9303 for_each_sched_entity(se) {
9304 cfs_rq = cfs_rq_of(se);
9305 WRITE_ONCE(cfs_rq->h_load_next, se);
9306 if (cfs_rq->last_h_load_update == now)
9311 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9312 cfs_rq->last_h_load_update = now;
9315 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9316 load = cfs_rq->h_load;
9317 load = div64_ul(load * se->avg.load_avg,
9318 cfs_rq_load_avg(cfs_rq) + 1);
9319 cfs_rq = group_cfs_rq(se);
9320 cfs_rq->h_load = load;
9321 cfs_rq->last_h_load_update = now;
9325 static unsigned long task_h_load(struct task_struct *p)
9327 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9329 update_cfs_rq_h_load(cfs_rq);
9330 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9331 cfs_rq_load_avg(cfs_rq) + 1);
9334 static bool __update_blocked_fair(struct rq *rq, bool *done)
9336 struct cfs_rq *cfs_rq = &rq->cfs;
9339 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9340 if (cfs_rq_has_blocked(cfs_rq))
9346 static unsigned long task_h_load(struct task_struct *p)
9348 return p->se.avg.load_avg;
9352 static void update_blocked_averages(int cpu)
9354 bool decayed = false, done = true;
9355 struct rq *rq = cpu_rq(cpu);
9358 rq_lock_irqsave(rq, &rf);
9359 update_blocked_load_tick(rq);
9360 update_rq_clock(rq);
9362 decayed |= __update_blocked_others(rq, &done);
9363 decayed |= __update_blocked_fair(rq, &done);
9365 update_blocked_load_status(rq, !done);
9367 cpufreq_update_util(rq, 0);
9368 rq_unlock_irqrestore(rq, &rf);
9371 /********** Helpers for find_busiest_group ************************/
9374 * sg_lb_stats - stats of a sched_group required for load_balancing
9376 struct sg_lb_stats {
9377 unsigned long avg_load; /*Avg load across the CPUs of the group */
9378 unsigned long group_load; /* Total load over the CPUs of the group */
9379 unsigned long group_capacity;
9380 unsigned long group_util; /* Total utilization over the CPUs of the group */
9381 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9382 unsigned int sum_nr_running; /* Nr of tasks running in the group */
9383 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9384 unsigned int idle_cpus;
9385 unsigned int group_weight;
9386 enum group_type group_type;
9387 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9388 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9389 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9390 #ifdef CONFIG_NUMA_BALANCING
9391 unsigned int nr_numa_running;
9392 unsigned int nr_preferred_running;
9397 * sd_lb_stats - Structure to store the statistics of a sched_domain
9398 * during load balancing.
9400 struct sd_lb_stats {
9401 struct sched_group *busiest; /* Busiest group in this sd */
9402 struct sched_group *local; /* Local group in this sd */
9403 unsigned long total_load; /* Total load of all groups in sd */
9404 unsigned long total_capacity; /* Total capacity of all groups in sd */
9405 unsigned long avg_load; /* Average load across all groups in sd */
9406 unsigned int prefer_sibling; /* tasks should go to sibling first */
9408 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9409 struct sg_lb_stats local_stat; /* Statistics of the local group */
9412 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9415 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9416 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9417 * We must however set busiest_stat::group_type and
9418 * busiest_stat::idle_cpus to the worst busiest group because
9419 * update_sd_pick_busiest() reads these before assignment.
9421 *sds = (struct sd_lb_stats){
9425 .total_capacity = 0UL,
9427 .idle_cpus = UINT_MAX,
9428 .group_type = group_has_spare,
9433 static unsigned long scale_rt_capacity(int cpu)
9435 struct rq *rq = cpu_rq(cpu);
9436 unsigned long max = arch_scale_cpu_capacity(cpu);
9437 unsigned long used, free;
9440 irq = cpu_util_irq(rq);
9442 if (unlikely(irq >= max))
9446 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9447 * (running and not running) with weights 0 and 1024 respectively.
9448 * avg_thermal.load_avg tracks thermal pressure and the weighted
9449 * average uses the actual delta max capacity(load).
9451 used = READ_ONCE(rq->avg_rt.util_avg);
9452 used += READ_ONCE(rq->avg_dl.util_avg);
9453 used += thermal_load_avg(rq);
9455 if (unlikely(used >= max))
9460 return scale_irq_capacity(free, irq, max);
9463 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9465 unsigned long capacity = scale_rt_capacity(cpu);
9466 struct sched_group *sdg = sd->groups;
9471 cpu_rq(cpu)->cpu_capacity = capacity;
9472 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9474 sdg->sgc->capacity = capacity;
9475 sdg->sgc->min_capacity = capacity;
9476 sdg->sgc->max_capacity = capacity;
9479 void update_group_capacity(struct sched_domain *sd, int cpu)
9481 struct sched_domain *child = sd->child;
9482 struct sched_group *group, *sdg = sd->groups;
9483 unsigned long capacity, min_capacity, max_capacity;
9484 unsigned long interval;
9486 interval = msecs_to_jiffies(sd->balance_interval);
9487 interval = clamp(interval, 1UL, max_load_balance_interval);
9488 sdg->sgc->next_update = jiffies + interval;
9491 update_cpu_capacity(sd, cpu);
9496 min_capacity = ULONG_MAX;
9499 if (child->flags & SD_OVERLAP) {
9501 * SD_OVERLAP domains cannot assume that child groups
9502 * span the current group.
9505 for_each_cpu(cpu, sched_group_span(sdg)) {
9506 unsigned long cpu_cap = capacity_of(cpu);
9508 capacity += cpu_cap;
9509 min_capacity = min(cpu_cap, min_capacity);
9510 max_capacity = max(cpu_cap, max_capacity);
9514 * !SD_OVERLAP domains can assume that child groups
9515 * span the current group.
9518 group = child->groups;
9520 struct sched_group_capacity *sgc = group->sgc;
9522 capacity += sgc->capacity;
9523 min_capacity = min(sgc->min_capacity, min_capacity);
9524 max_capacity = max(sgc->max_capacity, max_capacity);
9525 group = group->next;
9526 } while (group != child->groups);
9529 sdg->sgc->capacity = capacity;
9530 sdg->sgc->min_capacity = min_capacity;
9531 sdg->sgc->max_capacity = max_capacity;
9535 * Check whether the capacity of the rq has been noticeably reduced by side
9536 * activity. The imbalance_pct is used for the threshold.
9537 * Return true is the capacity is reduced
9540 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9542 return ((rq->cpu_capacity * sd->imbalance_pct) <
9543 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
9547 * Check whether a rq has a misfit task and if it looks like we can actually
9548 * help that task: we can migrate the task to a CPU of higher capacity, or
9549 * the task's current CPU is heavily pressured.
9551 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9553 return rq->misfit_task_load &&
9554 (arch_scale_cpu_capacity(rq->cpu) < rq->rd->max_cpu_capacity ||
9555 check_cpu_capacity(rq, sd));
9559 * Group imbalance indicates (and tries to solve) the problem where balancing
9560 * groups is inadequate due to ->cpus_ptr constraints.
9562 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9563 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9566 * { 0 1 2 3 } { 4 5 6 7 }
9569 * If we were to balance group-wise we'd place two tasks in the first group and
9570 * two tasks in the second group. Clearly this is undesired as it will overload
9571 * cpu 3 and leave one of the CPUs in the second group unused.
9573 * The current solution to this issue is detecting the skew in the first group
9574 * by noticing the lower domain failed to reach balance and had difficulty
9575 * moving tasks due to affinity constraints.
9577 * When this is so detected; this group becomes a candidate for busiest; see
9578 * update_sd_pick_busiest(). And calculate_imbalance() and
9579 * find_busiest_group() avoid some of the usual balance conditions to allow it
9580 * to create an effective group imbalance.
9582 * This is a somewhat tricky proposition since the next run might not find the
9583 * group imbalance and decide the groups need to be balanced again. A most
9584 * subtle and fragile situation.
9587 static inline int sg_imbalanced(struct sched_group *group)
9589 return group->sgc->imbalance;
9593 * group_has_capacity returns true if the group has spare capacity that could
9594 * be used by some tasks.
9595 * We consider that a group has spare capacity if the number of task is
9596 * smaller than the number of CPUs or if the utilization is lower than the
9597 * available capacity for CFS tasks.
9598 * For the latter, we use a threshold to stabilize the state, to take into
9599 * account the variance of the tasks' load and to return true if the available
9600 * capacity in meaningful for the load balancer.
9601 * As an example, an available capacity of 1% can appear but it doesn't make
9602 * any benefit for the load balance.
9605 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9607 if (sgs->sum_nr_running < sgs->group_weight)
9610 if ((sgs->group_capacity * imbalance_pct) <
9611 (sgs->group_runnable * 100))
9614 if ((sgs->group_capacity * 100) >
9615 (sgs->group_util * imbalance_pct))
9622 * group_is_overloaded returns true if the group has more tasks than it can
9624 * group_is_overloaded is not equals to !group_has_capacity because a group
9625 * with the exact right number of tasks, has no more spare capacity but is not
9626 * overloaded so both group_has_capacity and group_is_overloaded return
9630 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9632 if (sgs->sum_nr_running <= sgs->group_weight)
9635 if ((sgs->group_capacity * 100) <
9636 (sgs->group_util * imbalance_pct))
9639 if ((sgs->group_capacity * imbalance_pct) <
9640 (sgs->group_runnable * 100))
9647 group_type group_classify(unsigned int imbalance_pct,
9648 struct sched_group *group,
9649 struct sg_lb_stats *sgs)
9651 if (group_is_overloaded(imbalance_pct, sgs))
9652 return group_overloaded;
9654 if (sg_imbalanced(group))
9655 return group_imbalanced;
9657 if (sgs->group_asym_packing)
9658 return group_asym_packing;
9660 if (sgs->group_smt_balance)
9661 return group_smt_balance;
9663 if (sgs->group_misfit_task_load)
9664 return group_misfit_task;
9666 if (!group_has_capacity(imbalance_pct, sgs))
9667 return group_fully_busy;
9669 return group_has_spare;
9673 * sched_use_asym_prio - Check whether asym_packing priority must be used
9674 * @sd: The scheduling domain of the load balancing
9677 * Always use CPU priority when balancing load between SMT siblings. When
9678 * balancing load between cores, it is not sufficient that @cpu is idle. Only
9679 * use CPU priority if the whole core is idle.
9681 * Returns: True if the priority of @cpu must be followed. False otherwise.
9683 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9685 if (!sched_smt_active())
9688 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9692 * sched_asym - Check if the destination CPU can do asym_packing load balance
9693 * @env: The load balancing environment
9694 * @sds: Load-balancing data with statistics of the local group
9695 * @sgs: Load-balancing statistics of the candidate busiest group
9696 * @group: The candidate busiest group
9698 * @env::dst_cpu can do asym_packing if it has higher priority than the
9699 * preferred CPU of @group.
9701 * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9702 * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9703 * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9704 * imbalances in the number of CPUS are dealt with in find_busiest_group().
9706 * If we are balancing load within an SMT core, or at PKG domain level, always
9709 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9713 sched_asym(struct lb_env *env, struct sd_lb_stats *sds, struct sg_lb_stats *sgs,
9714 struct sched_group *group)
9716 /* Ensure that the whole local core is idle, if applicable. */
9717 if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9721 * CPU priorities does not make sense for SMT cores with more than one
9724 if (group->flags & SD_SHARE_CPUCAPACITY) {
9725 if (sgs->group_weight - sgs->idle_cpus != 1)
9729 return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9732 /* One group has more than one SMT CPU while the other group does not */
9733 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9734 struct sched_group *sg2)
9739 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9740 (sg2->flags & SD_SHARE_CPUCAPACITY);
9743 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9744 struct sched_group *group)
9746 if (env->idle == CPU_NOT_IDLE)
9750 * For SMT source group, it is better to move a task
9751 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9752 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9755 if (group->flags & SD_SHARE_CPUCAPACITY &&
9756 sgs->sum_h_nr_running > 1)
9762 static inline long sibling_imbalance(struct lb_env *env,
9763 struct sd_lb_stats *sds,
9764 struct sg_lb_stats *busiest,
9765 struct sg_lb_stats *local)
9767 int ncores_busiest, ncores_local;
9770 if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9773 ncores_busiest = sds->busiest->cores;
9774 ncores_local = sds->local->cores;
9776 if (ncores_busiest == ncores_local) {
9777 imbalance = busiest->sum_nr_running;
9778 lsub_positive(&imbalance, local->sum_nr_running);
9782 /* Balance such that nr_running/ncores ratio are same on both groups */
9783 imbalance = ncores_local * busiest->sum_nr_running;
9784 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9785 /* Normalize imbalance and do rounding on normalization */
9786 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9787 imbalance /= ncores_local + ncores_busiest;
9789 /* Take advantage of resource in an empty sched group */
9790 if (imbalance <= 1 && local->sum_nr_running == 0 &&
9791 busiest->sum_nr_running > 1)
9798 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9801 * When there is more than 1 task, the group_overloaded case already
9802 * takes care of cpu with reduced capacity
9804 if (rq->cfs.h_nr_running != 1)
9807 return check_cpu_capacity(rq, sd);
9811 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9812 * @env: The load balancing environment.
9813 * @sds: Load-balancing data with statistics of the local group.
9814 * @group: sched_group whose statistics are to be updated.
9815 * @sgs: variable to hold the statistics for this group.
9816 * @sg_status: Holds flag indicating the status of the sched_group
9818 static inline void update_sg_lb_stats(struct lb_env *env,
9819 struct sd_lb_stats *sds,
9820 struct sched_group *group,
9821 struct sg_lb_stats *sgs,
9824 int i, nr_running, local_group;
9826 memset(sgs, 0, sizeof(*sgs));
9828 local_group = group == sds->local;
9830 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9831 struct rq *rq = cpu_rq(i);
9832 unsigned long load = cpu_load(rq);
9834 sgs->group_load += load;
9835 sgs->group_util += cpu_util_cfs(i);
9836 sgs->group_runnable += cpu_runnable(rq);
9837 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9839 nr_running = rq->nr_running;
9840 sgs->sum_nr_running += nr_running;
9843 *sg_status |= SG_OVERLOAD;
9845 if (cpu_overutilized(i))
9846 *sg_status |= SG_OVERUTILIZED;
9848 #ifdef CONFIG_NUMA_BALANCING
9849 sgs->nr_numa_running += rq->nr_numa_running;
9850 sgs->nr_preferred_running += rq->nr_preferred_running;
9853 * No need to call idle_cpu() if nr_running is not 0
9855 if (!nr_running && idle_cpu(i)) {
9857 /* Idle cpu can't have misfit task */
9864 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9865 /* Check for a misfit task on the cpu */
9866 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9867 sgs->group_misfit_task_load = rq->misfit_task_load;
9868 *sg_status |= SG_OVERLOAD;
9870 } else if ((env->idle != CPU_NOT_IDLE) &&
9871 sched_reduced_capacity(rq, env->sd)) {
9872 /* Check for a task running on a CPU with reduced capacity */
9873 if (sgs->group_misfit_task_load < load)
9874 sgs->group_misfit_task_load = load;
9878 sgs->group_capacity = group->sgc->capacity;
9880 sgs->group_weight = group->group_weight;
9882 /* Check if dst CPU is idle and preferred to this group */
9883 if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9884 env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9885 sched_asym(env, sds, sgs, group)) {
9886 sgs->group_asym_packing = 1;
9889 /* Check for loaded SMT group to be balanced to dst CPU */
9890 if (!local_group && smt_balance(env, sgs, group))
9891 sgs->group_smt_balance = 1;
9893 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
9895 /* Computing avg_load makes sense only when group is overloaded */
9896 if (sgs->group_type == group_overloaded)
9897 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9898 sgs->group_capacity;
9902 * update_sd_pick_busiest - return 1 on busiest group
9903 * @env: The load balancing environment.
9904 * @sds: sched_domain statistics
9905 * @sg: sched_group candidate to be checked for being the busiest
9906 * @sgs: sched_group statistics
9908 * Determine if @sg is a busier group than the previously selected
9911 * Return: %true if @sg is a busier group than the previously selected
9912 * busiest group. %false otherwise.
9914 static bool update_sd_pick_busiest(struct lb_env *env,
9915 struct sd_lb_stats *sds,
9916 struct sched_group *sg,
9917 struct sg_lb_stats *sgs)
9919 struct sg_lb_stats *busiest = &sds->busiest_stat;
9921 /* Make sure that there is at least one task to pull */
9922 if (!sgs->sum_h_nr_running)
9926 * Don't try to pull misfit tasks we can't help.
9927 * We can use max_capacity here as reduction in capacity on some
9928 * CPUs in the group should either be possible to resolve
9929 * internally or be covered by avg_load imbalance (eventually).
9931 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9932 (sgs->group_type == group_misfit_task) &&
9933 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
9934 sds->local_stat.group_type != group_has_spare))
9937 if (sgs->group_type > busiest->group_type)
9940 if (sgs->group_type < busiest->group_type)
9944 * The candidate and the current busiest group are the same type of
9945 * group. Let check which one is the busiest according to the type.
9948 switch (sgs->group_type) {
9949 case group_overloaded:
9950 /* Select the overloaded group with highest avg_load. */
9951 if (sgs->avg_load <= busiest->avg_load)
9955 case group_imbalanced:
9957 * Select the 1st imbalanced group as we don't have any way to
9958 * choose one more than another.
9962 case group_asym_packing:
9963 /* Prefer to move from lowest priority CPU's work */
9964 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
9968 case group_misfit_task:
9970 * If we have more than one misfit sg go with the biggest
9973 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
9977 case group_smt_balance:
9979 * Check if we have spare CPUs on either SMT group to
9980 * choose has spare or fully busy handling.
9982 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
9987 case group_fully_busy:
9989 * Select the fully busy group with highest avg_load. In
9990 * theory, there is no need to pull task from such kind of
9991 * group because tasks have all compute capacity that they need
9992 * but we can still improve the overall throughput by reducing
9993 * contention when accessing shared HW resources.
9995 * XXX for now avg_load is not computed and always 0 so we
9996 * select the 1st one, except if @sg is composed of SMT
10000 if (sgs->avg_load < busiest->avg_load)
10003 if (sgs->avg_load == busiest->avg_load) {
10005 * SMT sched groups need more help than non-SMT groups.
10006 * If @sg happens to also be SMT, either choice is good.
10008 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10014 case group_has_spare:
10016 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10017 * as we do not want to pull task off SMT core with one task
10018 * and make the core idle.
10020 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10021 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10029 * Select not overloaded group with lowest number of idle cpus
10030 * and highest number of running tasks. We could also compare
10031 * the spare capacity which is more stable but it can end up
10032 * that the group has less spare capacity but finally more idle
10033 * CPUs which means less opportunity to pull tasks.
10035 if (sgs->idle_cpus > busiest->idle_cpus)
10037 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10038 (sgs->sum_nr_running <= busiest->sum_nr_running))
10045 * Candidate sg has no more than one task per CPU and has higher
10046 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10047 * throughput. Maximize throughput, power/energy consequences are not
10050 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10051 (sgs->group_type <= group_fully_busy) &&
10052 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10058 #ifdef CONFIG_NUMA_BALANCING
10059 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10061 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10063 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10068 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10070 if (rq->nr_running > rq->nr_numa_running)
10072 if (rq->nr_running > rq->nr_preferred_running)
10077 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10082 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10086 #endif /* CONFIG_NUMA_BALANCING */
10089 struct sg_lb_stats;
10092 * task_running_on_cpu - return 1 if @p is running on @cpu.
10095 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10097 /* Task has no contribution or is new */
10098 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10101 if (task_on_rq_queued(p))
10108 * idle_cpu_without - would a given CPU be idle without p ?
10109 * @cpu: the processor on which idleness is tested.
10110 * @p: task which should be ignored.
10112 * Return: 1 if the CPU would be idle. 0 otherwise.
10114 static int idle_cpu_without(int cpu, struct task_struct *p)
10116 struct rq *rq = cpu_rq(cpu);
10118 if (rq->curr != rq->idle && rq->curr != p)
10122 * rq->nr_running can't be used but an updated version without the
10123 * impact of p on cpu must be used instead. The updated nr_running
10124 * be computed and tested before calling idle_cpu_without().
10128 if (rq->ttwu_pending)
10136 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10137 * @sd: The sched_domain level to look for idlest group.
10138 * @group: sched_group whose statistics are to be updated.
10139 * @sgs: variable to hold the statistics for this group.
10140 * @p: The task for which we look for the idlest group/CPU.
10142 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10143 struct sched_group *group,
10144 struct sg_lb_stats *sgs,
10145 struct task_struct *p)
10149 memset(sgs, 0, sizeof(*sgs));
10151 /* Assume that task can't fit any CPU of the group */
10152 if (sd->flags & SD_ASYM_CPUCAPACITY)
10153 sgs->group_misfit_task_load = 1;
10155 for_each_cpu(i, sched_group_span(group)) {
10156 struct rq *rq = cpu_rq(i);
10157 unsigned int local;
10159 sgs->group_load += cpu_load_without(rq, p);
10160 sgs->group_util += cpu_util_without(i, p);
10161 sgs->group_runnable += cpu_runnable_without(rq, p);
10162 local = task_running_on_cpu(i, p);
10163 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10165 nr_running = rq->nr_running - local;
10166 sgs->sum_nr_running += nr_running;
10169 * No need to call idle_cpu_without() if nr_running is not 0
10171 if (!nr_running && idle_cpu_without(i, p))
10174 /* Check if task fits in the CPU */
10175 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10176 sgs->group_misfit_task_load &&
10177 task_fits_cpu(p, i))
10178 sgs->group_misfit_task_load = 0;
10182 sgs->group_capacity = group->sgc->capacity;
10184 sgs->group_weight = group->group_weight;
10186 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10189 * Computing avg_load makes sense only when group is fully busy or
10192 if (sgs->group_type == group_fully_busy ||
10193 sgs->group_type == group_overloaded)
10194 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10195 sgs->group_capacity;
10198 static bool update_pick_idlest(struct sched_group *idlest,
10199 struct sg_lb_stats *idlest_sgs,
10200 struct sched_group *group,
10201 struct sg_lb_stats *sgs)
10203 if (sgs->group_type < idlest_sgs->group_type)
10206 if (sgs->group_type > idlest_sgs->group_type)
10210 * The candidate and the current idlest group are the same type of
10211 * group. Let check which one is the idlest according to the type.
10214 switch (sgs->group_type) {
10215 case group_overloaded:
10216 case group_fully_busy:
10217 /* Select the group with lowest avg_load. */
10218 if (idlest_sgs->avg_load <= sgs->avg_load)
10222 case group_imbalanced:
10223 case group_asym_packing:
10224 case group_smt_balance:
10225 /* Those types are not used in the slow wakeup path */
10228 case group_misfit_task:
10229 /* Select group with the highest max capacity */
10230 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10234 case group_has_spare:
10235 /* Select group with most idle CPUs */
10236 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10239 /* Select group with lowest group_util */
10240 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10241 idlest_sgs->group_util <= sgs->group_util)
10251 * find_idlest_group() finds and returns the least busy CPU group within the
10254 * Assumes p is allowed on at least one CPU in sd.
10256 static struct sched_group *
10257 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10259 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10260 struct sg_lb_stats local_sgs, tmp_sgs;
10261 struct sg_lb_stats *sgs;
10262 unsigned long imbalance;
10263 struct sg_lb_stats idlest_sgs = {
10264 .avg_load = UINT_MAX,
10265 .group_type = group_overloaded,
10271 /* Skip over this group if it has no CPUs allowed */
10272 if (!cpumask_intersects(sched_group_span(group),
10276 /* Skip over this group if no cookie matched */
10277 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10280 local_group = cpumask_test_cpu(this_cpu,
10281 sched_group_span(group));
10290 update_sg_wakeup_stats(sd, group, sgs, p);
10292 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10297 } while (group = group->next, group != sd->groups);
10300 /* There is no idlest group to push tasks to */
10304 /* The local group has been skipped because of CPU affinity */
10309 * If the local group is idler than the selected idlest group
10310 * don't try and push the task.
10312 if (local_sgs.group_type < idlest_sgs.group_type)
10316 * If the local group is busier than the selected idlest group
10317 * try and push the task.
10319 if (local_sgs.group_type > idlest_sgs.group_type)
10322 switch (local_sgs.group_type) {
10323 case group_overloaded:
10324 case group_fully_busy:
10326 /* Calculate allowed imbalance based on load */
10327 imbalance = scale_load_down(NICE_0_LOAD) *
10328 (sd->imbalance_pct-100) / 100;
10331 * When comparing groups across NUMA domains, it's possible for
10332 * the local domain to be very lightly loaded relative to the
10333 * remote domains but "imbalance" skews the comparison making
10334 * remote CPUs look much more favourable. When considering
10335 * cross-domain, add imbalance to the load on the remote node
10336 * and consider staying local.
10339 if ((sd->flags & SD_NUMA) &&
10340 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10344 * If the local group is less loaded than the selected
10345 * idlest group don't try and push any tasks.
10347 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10350 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10354 case group_imbalanced:
10355 case group_asym_packing:
10356 case group_smt_balance:
10357 /* Those type are not used in the slow wakeup path */
10360 case group_misfit_task:
10361 /* Select group with the highest max capacity */
10362 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10366 case group_has_spare:
10368 if (sd->flags & SD_NUMA) {
10369 int imb_numa_nr = sd->imb_numa_nr;
10370 #ifdef CONFIG_NUMA_BALANCING
10373 * If there is spare capacity at NUMA, try to select
10374 * the preferred node
10376 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10379 idlest_cpu = cpumask_first(sched_group_span(idlest));
10380 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10382 #endif /* CONFIG_NUMA_BALANCING */
10384 * Otherwise, keep the task close to the wakeup source
10385 * and improve locality if the number of running tasks
10386 * would remain below threshold where an imbalance is
10387 * allowed while accounting for the possibility the
10388 * task is pinned to a subset of CPUs. If there is a
10389 * real need of migration, periodic load balance will
10392 if (p->nr_cpus_allowed != NR_CPUS) {
10393 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10395 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10396 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10399 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10400 if (!adjust_numa_imbalance(imbalance,
10401 local_sgs.sum_nr_running + 1,
10406 #endif /* CONFIG_NUMA */
10409 * Select group with highest number of idle CPUs. We could also
10410 * compare the utilization which is more stable but it can end
10411 * up that the group has less spare capacity but finally more
10412 * idle CPUs which means more opportunity to run task.
10414 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10422 static void update_idle_cpu_scan(struct lb_env *env,
10423 unsigned long sum_util)
10425 struct sched_domain_shared *sd_share;
10426 int llc_weight, pct;
10429 * Update the number of CPUs to scan in LLC domain, which could
10430 * be used as a hint in select_idle_cpu(). The update of sd_share
10431 * could be expensive because it is within a shared cache line.
10432 * So the write of this hint only occurs during periodic load
10433 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10434 * can fire way more frequently than the former.
10436 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10439 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10440 if (env->sd->span_weight != llc_weight)
10443 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10448 * The number of CPUs to search drops as sum_util increases, when
10449 * sum_util hits 85% or above, the scan stops.
10450 * The reason to choose 85% as the threshold is because this is the
10451 * imbalance_pct(117) when a LLC sched group is overloaded.
10453 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10454 * and y'= y / SCHED_CAPACITY_SCALE
10456 * x is the ratio of sum_util compared to the CPU capacity:
10457 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10458 * y' is the ratio of CPUs to be scanned in the LLC domain,
10459 * and the number of CPUs to scan is calculated by:
10461 * nr_scan = llc_weight * y' [2]
10463 * When x hits the threshold of overloaded, AKA, when
10464 * x = 100 / pct, y drops to 0. According to [1],
10465 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10467 * Scale x by SCHED_CAPACITY_SCALE:
10468 * x' = sum_util / llc_weight; [3]
10470 * and finally [1] becomes:
10471 * y = SCHED_CAPACITY_SCALE -
10472 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10477 do_div(x, llc_weight);
10480 pct = env->sd->imbalance_pct;
10481 tmp = x * x * pct * pct;
10482 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10483 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10484 y = SCHED_CAPACITY_SCALE - tmp;
10488 do_div(y, SCHED_CAPACITY_SCALE);
10489 if ((int)y != sd_share->nr_idle_scan)
10490 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10494 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10495 * @env: The load balancing environment.
10496 * @sds: variable to hold the statistics for this sched_domain.
10499 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10501 struct sched_group *sg = env->sd->groups;
10502 struct sg_lb_stats *local = &sds->local_stat;
10503 struct sg_lb_stats tmp_sgs;
10504 unsigned long sum_util = 0;
10508 struct sg_lb_stats *sgs = &tmp_sgs;
10511 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10516 if (env->idle != CPU_NEWLY_IDLE ||
10517 time_after_eq(jiffies, sg->sgc->next_update))
10518 update_group_capacity(env->sd, env->dst_cpu);
10521 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10527 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10529 sds->busiest_stat = *sgs;
10533 /* Now, start updating sd_lb_stats */
10534 sds->total_load += sgs->group_load;
10535 sds->total_capacity += sgs->group_capacity;
10537 sum_util += sgs->group_util;
10539 } while (sg != env->sd->groups);
10542 * Indicate that the child domain of the busiest group prefers tasks
10543 * go to a child's sibling domains first. NB the flags of a sched group
10544 * are those of the child domain.
10547 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10550 if (env->sd->flags & SD_NUMA)
10551 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10553 if (!env->sd->parent) {
10554 struct root_domain *rd = env->dst_rq->rd;
10556 /* update overload indicator if we are at root domain */
10557 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10559 /* Update over-utilization (tipping point, U >= 0) indicator */
10560 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10561 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10562 } else if (sg_status & SG_OVERUTILIZED) {
10563 struct root_domain *rd = env->dst_rq->rd;
10565 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10566 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10569 update_idle_cpu_scan(env, sum_util);
10573 * calculate_imbalance - Calculate the amount of imbalance present within the
10574 * groups of a given sched_domain during load balance.
10575 * @env: load balance environment
10576 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10578 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10580 struct sg_lb_stats *local, *busiest;
10582 local = &sds->local_stat;
10583 busiest = &sds->busiest_stat;
10585 if (busiest->group_type == group_misfit_task) {
10586 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10587 /* Set imbalance to allow misfit tasks to be balanced. */
10588 env->migration_type = migrate_misfit;
10589 env->imbalance = 1;
10592 * Set load imbalance to allow moving task from cpu
10593 * with reduced capacity.
10595 env->migration_type = migrate_load;
10596 env->imbalance = busiest->group_misfit_task_load;
10601 if (busiest->group_type == group_asym_packing) {
10603 * In case of asym capacity, we will try to migrate all load to
10604 * the preferred CPU.
10606 env->migration_type = migrate_task;
10607 env->imbalance = busiest->sum_h_nr_running;
10611 if (busiest->group_type == group_smt_balance) {
10612 /* Reduce number of tasks sharing CPU capacity */
10613 env->migration_type = migrate_task;
10614 env->imbalance = 1;
10618 if (busiest->group_type == group_imbalanced) {
10620 * In the group_imb case we cannot rely on group-wide averages
10621 * to ensure CPU-load equilibrium, try to move any task to fix
10622 * the imbalance. The next load balance will take care of
10623 * balancing back the system.
10625 env->migration_type = migrate_task;
10626 env->imbalance = 1;
10631 * Try to use spare capacity of local group without overloading it or
10632 * emptying busiest.
10634 if (local->group_type == group_has_spare) {
10635 if ((busiest->group_type > group_fully_busy) &&
10636 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10638 * If busiest is overloaded, try to fill spare
10639 * capacity. This might end up creating spare capacity
10640 * in busiest or busiest still being overloaded but
10641 * there is no simple way to directly compute the
10642 * amount of load to migrate in order to balance the
10645 env->migration_type = migrate_util;
10646 env->imbalance = max(local->group_capacity, local->group_util) -
10650 * In some cases, the group's utilization is max or even
10651 * higher than capacity because of migrations but the
10652 * local CPU is (newly) idle. There is at least one
10653 * waiting task in this overloaded busiest group. Let's
10656 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10657 env->migration_type = migrate_task;
10658 env->imbalance = 1;
10664 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10666 * When prefer sibling, evenly spread running tasks on
10669 env->migration_type = migrate_task;
10670 env->imbalance = sibling_imbalance(env, sds, busiest, local);
10674 * If there is no overload, we just want to even the number of
10677 env->migration_type = migrate_task;
10678 env->imbalance = max_t(long, 0,
10679 (local->idle_cpus - busiest->idle_cpus));
10683 /* Consider allowing a small imbalance between NUMA groups */
10684 if (env->sd->flags & SD_NUMA) {
10685 env->imbalance = adjust_numa_imbalance(env->imbalance,
10686 local->sum_nr_running + 1,
10687 env->sd->imb_numa_nr);
10691 /* Number of tasks to move to restore balance */
10692 env->imbalance >>= 1;
10698 * Local is fully busy but has to take more load to relieve the
10701 if (local->group_type < group_overloaded) {
10703 * Local will become overloaded so the avg_load metrics are
10707 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10708 local->group_capacity;
10711 * If the local group is more loaded than the selected
10712 * busiest group don't try to pull any tasks.
10714 if (local->avg_load >= busiest->avg_load) {
10715 env->imbalance = 0;
10719 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10720 sds->total_capacity;
10723 * If the local group is more loaded than the average system
10724 * load, don't try to pull any tasks.
10726 if (local->avg_load >= sds->avg_load) {
10727 env->imbalance = 0;
10734 * Both group are or will become overloaded and we're trying to get all
10735 * the CPUs to the average_load, so we don't want to push ourselves
10736 * above the average load, nor do we wish to reduce the max loaded CPU
10737 * below the average load. At the same time, we also don't want to
10738 * reduce the group load below the group capacity. Thus we look for
10739 * the minimum possible imbalance.
10741 env->migration_type = migrate_load;
10742 env->imbalance = min(
10743 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10744 (sds->avg_load - local->avg_load) * local->group_capacity
10745 ) / SCHED_CAPACITY_SCALE;
10748 /******* find_busiest_group() helpers end here *********************/
10751 * Decision matrix according to the local and busiest group type:
10753 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10754 * has_spare nr_idle balanced N/A N/A balanced balanced
10755 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
10756 * misfit_task force N/A N/A N/A N/A N/A
10757 * asym_packing force force N/A N/A force force
10758 * imbalanced force force N/A N/A force force
10759 * overloaded force force N/A N/A force avg_load
10761 * N/A : Not Applicable because already filtered while updating
10763 * balanced : The system is balanced for these 2 groups.
10764 * force : Calculate the imbalance as load migration is probably needed.
10765 * avg_load : Only if imbalance is significant enough.
10766 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
10767 * different in groups.
10771 * find_busiest_group - Returns the busiest group within the sched_domain
10772 * if there is an imbalance.
10773 * @env: The load balancing environment.
10775 * Also calculates the amount of runnable load which should be moved
10776 * to restore balance.
10778 * Return: - The busiest group if imbalance exists.
10780 static struct sched_group *find_busiest_group(struct lb_env *env)
10782 struct sg_lb_stats *local, *busiest;
10783 struct sd_lb_stats sds;
10785 init_sd_lb_stats(&sds);
10788 * Compute the various statistics relevant for load balancing at
10791 update_sd_lb_stats(env, &sds);
10793 /* There is no busy sibling group to pull tasks from */
10797 busiest = &sds.busiest_stat;
10799 /* Misfit tasks should be dealt with regardless of the avg load */
10800 if (busiest->group_type == group_misfit_task)
10801 goto force_balance;
10803 if (sched_energy_enabled()) {
10804 struct root_domain *rd = env->dst_rq->rd;
10806 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10810 /* ASYM feature bypasses nice load balance check */
10811 if (busiest->group_type == group_asym_packing)
10812 goto force_balance;
10815 * If the busiest group is imbalanced the below checks don't
10816 * work because they assume all things are equal, which typically
10817 * isn't true due to cpus_ptr constraints and the like.
10819 if (busiest->group_type == group_imbalanced)
10820 goto force_balance;
10822 local = &sds.local_stat;
10824 * If the local group is busier than the selected busiest group
10825 * don't try and pull any tasks.
10827 if (local->group_type > busiest->group_type)
10831 * When groups are overloaded, use the avg_load to ensure fairness
10834 if (local->group_type == group_overloaded) {
10836 * If the local group is more loaded than the selected
10837 * busiest group don't try to pull any tasks.
10839 if (local->avg_load >= busiest->avg_load)
10842 /* XXX broken for overlapping NUMA groups */
10843 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10844 sds.total_capacity;
10847 * Don't pull any tasks if this group is already above the
10848 * domain average load.
10850 if (local->avg_load >= sds.avg_load)
10854 * If the busiest group is more loaded, use imbalance_pct to be
10857 if (100 * busiest->avg_load <=
10858 env->sd->imbalance_pct * local->avg_load)
10863 * Try to move all excess tasks to a sibling domain of the busiest
10864 * group's child domain.
10866 if (sds.prefer_sibling && local->group_type == group_has_spare &&
10867 sibling_imbalance(env, &sds, busiest, local) > 1)
10868 goto force_balance;
10870 if (busiest->group_type != group_overloaded) {
10871 if (env->idle == CPU_NOT_IDLE) {
10873 * If the busiest group is not overloaded (and as a
10874 * result the local one too) but this CPU is already
10875 * busy, let another idle CPU try to pull task.
10880 if (busiest->group_type == group_smt_balance &&
10881 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10882 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10883 goto force_balance;
10886 if (busiest->group_weight > 1 &&
10887 local->idle_cpus <= (busiest->idle_cpus + 1)) {
10889 * If the busiest group is not overloaded
10890 * and there is no imbalance between this and busiest
10891 * group wrt idle CPUs, it is balanced. The imbalance
10892 * becomes significant if the diff is greater than 1
10893 * otherwise we might end up to just move the imbalance
10894 * on another group. Of course this applies only if
10895 * there is more than 1 CPU per group.
10900 if (busiest->sum_h_nr_running == 1) {
10902 * busiest doesn't have any tasks waiting to run
10909 /* Looks like there is an imbalance. Compute it */
10910 calculate_imbalance(env, &sds);
10911 return env->imbalance ? sds.busiest : NULL;
10914 env->imbalance = 0;
10919 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
10921 static struct rq *find_busiest_queue(struct lb_env *env,
10922 struct sched_group *group)
10924 struct rq *busiest = NULL, *rq;
10925 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
10926 unsigned int busiest_nr = 0;
10929 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10930 unsigned long capacity, load, util;
10931 unsigned int nr_running;
10935 rt = fbq_classify_rq(rq);
10938 * We classify groups/runqueues into three groups:
10939 * - regular: there are !numa tasks
10940 * - remote: there are numa tasks that run on the 'wrong' node
10941 * - all: there is no distinction
10943 * In order to avoid migrating ideally placed numa tasks,
10944 * ignore those when there's better options.
10946 * If we ignore the actual busiest queue to migrate another
10947 * task, the next balance pass can still reduce the busiest
10948 * queue by moving tasks around inside the node.
10950 * If we cannot move enough load due to this classification
10951 * the next pass will adjust the group classification and
10952 * allow migration of more tasks.
10954 * Both cases only affect the total convergence complexity.
10956 if (rt > env->fbq_type)
10959 nr_running = rq->cfs.h_nr_running;
10963 capacity = capacity_of(i);
10966 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
10967 * eventually lead to active_balancing high->low capacity.
10968 * Higher per-CPU capacity is considered better than balancing
10971 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
10972 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
10977 * Make sure we only pull tasks from a CPU of lower priority
10978 * when balancing between SMT siblings.
10980 * If balancing between cores, let lower priority CPUs help
10981 * SMT cores with more than one busy sibling.
10983 if ((env->sd->flags & SD_ASYM_PACKING) &&
10984 sched_use_asym_prio(env->sd, i) &&
10985 sched_asym_prefer(i, env->dst_cpu) &&
10989 switch (env->migration_type) {
10992 * When comparing with load imbalance, use cpu_load()
10993 * which is not scaled with the CPU capacity.
10995 load = cpu_load(rq);
10997 if (nr_running == 1 && load > env->imbalance &&
10998 !check_cpu_capacity(rq, env->sd))
11002 * For the load comparisons with the other CPUs,
11003 * consider the cpu_load() scaled with the CPU
11004 * capacity, so that the load can be moved away
11005 * from the CPU that is potentially running at a
11008 * Thus we're looking for max(load_i / capacity_i),
11009 * crosswise multiplication to rid ourselves of the
11010 * division works out to:
11011 * load_i * capacity_j > load_j * capacity_i;
11012 * where j is our previous maximum.
11014 if (load * busiest_capacity > busiest_load * capacity) {
11015 busiest_load = load;
11016 busiest_capacity = capacity;
11022 util = cpu_util_cfs_boost(i);
11025 * Don't try to pull utilization from a CPU with one
11026 * running task. Whatever its utilization, we will fail
11029 if (nr_running <= 1)
11032 if (busiest_util < util) {
11033 busiest_util = util;
11039 if (busiest_nr < nr_running) {
11040 busiest_nr = nr_running;
11045 case migrate_misfit:
11047 * For ASYM_CPUCAPACITY domains with misfit tasks we
11048 * simply seek the "biggest" misfit task.
11050 if (rq->misfit_task_load > busiest_load) {
11051 busiest_load = rq->misfit_task_load;
11064 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11065 * so long as it is large enough.
11067 #define MAX_PINNED_INTERVAL 512
11070 asym_active_balance(struct lb_env *env)
11073 * ASYM_PACKING needs to force migrate tasks from busy but lower
11074 * priority CPUs in order to pack all tasks in the highest priority
11075 * CPUs. When done between cores, do it only if the whole core if the
11076 * whole core is idle.
11078 * If @env::src_cpu is an SMT core with busy siblings, let
11079 * the lower priority @env::dst_cpu help it. Do not follow
11082 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
11083 sched_use_asym_prio(env->sd, env->dst_cpu) &&
11084 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11085 !sched_use_asym_prio(env->sd, env->src_cpu));
11089 imbalanced_active_balance(struct lb_env *env)
11091 struct sched_domain *sd = env->sd;
11094 * The imbalanced case includes the case of pinned tasks preventing a fair
11095 * distribution of the load on the system but also the even distribution of the
11096 * threads on a system with spare capacity
11098 if ((env->migration_type == migrate_task) &&
11099 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11105 static int need_active_balance(struct lb_env *env)
11107 struct sched_domain *sd = env->sd;
11109 if (asym_active_balance(env))
11112 if (imbalanced_active_balance(env))
11116 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11117 * It's worth migrating the task if the src_cpu's capacity is reduced
11118 * because of other sched_class or IRQs if more capacity stays
11119 * available on dst_cpu.
11121 if ((env->idle != CPU_NOT_IDLE) &&
11122 (env->src_rq->cfs.h_nr_running == 1)) {
11123 if ((check_cpu_capacity(env->src_rq, sd)) &&
11124 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11128 if (env->migration_type == migrate_misfit)
11134 static int active_load_balance_cpu_stop(void *data);
11136 static int should_we_balance(struct lb_env *env)
11138 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11139 struct sched_group *sg = env->sd->groups;
11140 int cpu, idle_smt = -1;
11143 * Ensure the balancing environment is consistent; can happen
11144 * when the softirq triggers 'during' hotplug.
11146 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11150 * In the newly idle case, we will allow all the CPUs
11151 * to do the newly idle load balance.
11153 * However, we bail out if we already have tasks or a wakeup pending,
11154 * to optimize wakeup latency.
11156 if (env->idle == CPU_NEWLY_IDLE) {
11157 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11162 cpumask_copy(swb_cpus, group_balance_mask(sg));
11163 /* Try to find first idle CPU */
11164 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11165 if (!idle_cpu(cpu))
11169 * Don't balance to idle SMT in busy core right away when
11170 * balancing cores, but remember the first idle SMT CPU for
11171 * later consideration. Find CPU on an idle core first.
11173 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11174 if (idle_smt == -1)
11177 * If the core is not idle, and first SMT sibling which is
11178 * idle has been found, then its not needed to check other
11179 * SMT siblings for idleness:
11181 #ifdef CONFIG_SCHED_SMT
11182 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11188 * Are we the first idle core in a non-SMT domain or higher,
11189 * or the first idle CPU in a SMT domain?
11191 return cpu == env->dst_cpu;
11194 /* Are we the first idle CPU with busy siblings? */
11195 if (idle_smt != -1)
11196 return idle_smt == env->dst_cpu;
11198 /* Are we the first CPU of this group ? */
11199 return group_balance_cpu(sg) == env->dst_cpu;
11203 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11204 * tasks if there is an imbalance.
11206 static int load_balance(int this_cpu, struct rq *this_rq,
11207 struct sched_domain *sd, enum cpu_idle_type idle,
11208 int *continue_balancing)
11210 int ld_moved, cur_ld_moved, active_balance = 0;
11211 struct sched_domain *sd_parent = sd->parent;
11212 struct sched_group *group;
11213 struct rq *busiest;
11214 struct rq_flags rf;
11215 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11216 struct lb_env env = {
11218 .dst_cpu = this_cpu,
11220 .dst_grpmask = group_balance_mask(sd->groups),
11222 .loop_break = SCHED_NR_MIGRATE_BREAK,
11225 .tasks = LIST_HEAD_INIT(env.tasks),
11228 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11230 schedstat_inc(sd->lb_count[idle]);
11233 if (!should_we_balance(&env)) {
11234 *continue_balancing = 0;
11238 group = find_busiest_group(&env);
11240 schedstat_inc(sd->lb_nobusyg[idle]);
11244 busiest = find_busiest_queue(&env, group);
11246 schedstat_inc(sd->lb_nobusyq[idle]);
11250 WARN_ON_ONCE(busiest == env.dst_rq);
11252 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11254 env.src_cpu = busiest->cpu;
11255 env.src_rq = busiest;
11258 /* Clear this flag as soon as we find a pullable task */
11259 env.flags |= LBF_ALL_PINNED;
11260 if (busiest->nr_running > 1) {
11262 * Attempt to move tasks. If find_busiest_group has found
11263 * an imbalance but busiest->nr_running <= 1, the group is
11264 * still unbalanced. ld_moved simply stays zero, so it is
11265 * correctly treated as an imbalance.
11267 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11270 rq_lock_irqsave(busiest, &rf);
11271 update_rq_clock(busiest);
11274 * cur_ld_moved - load moved in current iteration
11275 * ld_moved - cumulative load moved across iterations
11277 cur_ld_moved = detach_tasks(&env);
11280 * We've detached some tasks from busiest_rq. Every
11281 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11282 * unlock busiest->lock, and we are able to be sure
11283 * that nobody can manipulate the tasks in parallel.
11284 * See task_rq_lock() family for the details.
11287 rq_unlock(busiest, &rf);
11289 if (cur_ld_moved) {
11290 attach_tasks(&env);
11291 ld_moved += cur_ld_moved;
11294 local_irq_restore(rf.flags);
11296 if (env.flags & LBF_NEED_BREAK) {
11297 env.flags &= ~LBF_NEED_BREAK;
11298 /* Stop if we tried all running tasks */
11299 if (env.loop < busiest->nr_running)
11304 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11305 * us and move them to an alternate dst_cpu in our sched_group
11306 * where they can run. The upper limit on how many times we
11307 * iterate on same src_cpu is dependent on number of CPUs in our
11310 * This changes load balance semantics a bit on who can move
11311 * load to a given_cpu. In addition to the given_cpu itself
11312 * (or a ilb_cpu acting on its behalf where given_cpu is
11313 * nohz-idle), we now have balance_cpu in a position to move
11314 * load to given_cpu. In rare situations, this may cause
11315 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11316 * _independently_ and at _same_ time to move some load to
11317 * given_cpu) causing excess load to be moved to given_cpu.
11318 * This however should not happen so much in practice and
11319 * moreover subsequent load balance cycles should correct the
11320 * excess load moved.
11322 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11324 /* Prevent to re-select dst_cpu via env's CPUs */
11325 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11327 env.dst_rq = cpu_rq(env.new_dst_cpu);
11328 env.dst_cpu = env.new_dst_cpu;
11329 env.flags &= ~LBF_DST_PINNED;
11331 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11334 * Go back to "more_balance" rather than "redo" since we
11335 * need to continue with same src_cpu.
11341 * We failed to reach balance because of affinity.
11344 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11346 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11347 *group_imbalance = 1;
11350 /* All tasks on this runqueue were pinned by CPU affinity */
11351 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11352 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11354 * Attempting to continue load balancing at the current
11355 * sched_domain level only makes sense if there are
11356 * active CPUs remaining as possible busiest CPUs to
11357 * pull load from which are not contained within the
11358 * destination group that is receiving any migrated
11361 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11363 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11366 goto out_all_pinned;
11371 schedstat_inc(sd->lb_failed[idle]);
11373 * Increment the failure counter only on periodic balance.
11374 * We do not want newidle balance, which can be very
11375 * frequent, pollute the failure counter causing
11376 * excessive cache_hot migrations and active balances.
11378 if (idle != CPU_NEWLY_IDLE)
11379 sd->nr_balance_failed++;
11381 if (need_active_balance(&env)) {
11382 unsigned long flags;
11384 raw_spin_rq_lock_irqsave(busiest, flags);
11387 * Don't kick the active_load_balance_cpu_stop,
11388 * if the curr task on busiest CPU can't be
11389 * moved to this_cpu:
11391 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11392 raw_spin_rq_unlock_irqrestore(busiest, flags);
11393 goto out_one_pinned;
11396 /* Record that we found at least one task that could run on this_cpu */
11397 env.flags &= ~LBF_ALL_PINNED;
11400 * ->active_balance synchronizes accesses to
11401 * ->active_balance_work. Once set, it's cleared
11402 * only after active load balance is finished.
11404 if (!busiest->active_balance) {
11405 busiest->active_balance = 1;
11406 busiest->push_cpu = this_cpu;
11407 active_balance = 1;
11411 raw_spin_rq_unlock_irqrestore(busiest, flags);
11412 if (active_balance) {
11413 stop_one_cpu_nowait(cpu_of(busiest),
11414 active_load_balance_cpu_stop, busiest,
11415 &busiest->active_balance_work);
11420 sd->nr_balance_failed = 0;
11423 if (likely(!active_balance) || need_active_balance(&env)) {
11424 /* We were unbalanced, so reset the balancing interval */
11425 sd->balance_interval = sd->min_interval;
11432 * We reach balance although we may have faced some affinity
11433 * constraints. Clear the imbalance flag only if other tasks got
11434 * a chance to move and fix the imbalance.
11436 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11437 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11439 if (*group_imbalance)
11440 *group_imbalance = 0;
11445 * We reach balance because all tasks are pinned at this level so
11446 * we can't migrate them. Let the imbalance flag set so parent level
11447 * can try to migrate them.
11449 schedstat_inc(sd->lb_balanced[idle]);
11451 sd->nr_balance_failed = 0;
11457 * newidle_balance() disregards balance intervals, so we could
11458 * repeatedly reach this code, which would lead to balance_interval
11459 * skyrocketing in a short amount of time. Skip the balance_interval
11460 * increase logic to avoid that.
11462 if (env.idle == CPU_NEWLY_IDLE)
11465 /* tune up the balancing interval */
11466 if ((env.flags & LBF_ALL_PINNED &&
11467 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11468 sd->balance_interval < sd->max_interval)
11469 sd->balance_interval *= 2;
11474 static inline unsigned long
11475 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11477 unsigned long interval = sd->balance_interval;
11480 interval *= sd->busy_factor;
11482 /* scale ms to jiffies */
11483 interval = msecs_to_jiffies(interval);
11486 * Reduce likelihood of busy balancing at higher domains racing with
11487 * balancing at lower domains by preventing their balancing periods
11488 * from being multiples of each other.
11493 interval = clamp(interval, 1UL, max_load_balance_interval);
11499 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11501 unsigned long interval, next;
11503 /* used by idle balance, so cpu_busy = 0 */
11504 interval = get_sd_balance_interval(sd, 0);
11505 next = sd->last_balance + interval;
11507 if (time_after(*next_balance, next))
11508 *next_balance = next;
11512 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11513 * running tasks off the busiest CPU onto idle CPUs. It requires at
11514 * least 1 task to be running on each physical CPU where possible, and
11515 * avoids physical / logical imbalances.
11517 static int active_load_balance_cpu_stop(void *data)
11519 struct rq *busiest_rq = data;
11520 int busiest_cpu = cpu_of(busiest_rq);
11521 int target_cpu = busiest_rq->push_cpu;
11522 struct rq *target_rq = cpu_rq(target_cpu);
11523 struct sched_domain *sd;
11524 struct task_struct *p = NULL;
11525 struct rq_flags rf;
11527 rq_lock_irq(busiest_rq, &rf);
11529 * Between queueing the stop-work and running it is a hole in which
11530 * CPUs can become inactive. We should not move tasks from or to
11533 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11536 /* Make sure the requested CPU hasn't gone down in the meantime: */
11537 if (unlikely(busiest_cpu != smp_processor_id() ||
11538 !busiest_rq->active_balance))
11541 /* Is there any task to move? */
11542 if (busiest_rq->nr_running <= 1)
11546 * This condition is "impossible", if it occurs
11547 * we need to fix it. Originally reported by
11548 * Bjorn Helgaas on a 128-CPU setup.
11550 WARN_ON_ONCE(busiest_rq == target_rq);
11552 /* Search for an sd spanning us and the target CPU. */
11554 for_each_domain(target_cpu, sd) {
11555 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11560 struct lb_env env = {
11562 .dst_cpu = target_cpu,
11563 .dst_rq = target_rq,
11564 .src_cpu = busiest_rq->cpu,
11565 .src_rq = busiest_rq,
11567 .flags = LBF_ACTIVE_LB,
11570 schedstat_inc(sd->alb_count);
11571 update_rq_clock(busiest_rq);
11573 p = detach_one_task(&env);
11575 schedstat_inc(sd->alb_pushed);
11576 /* Active balancing done, reset the failure counter. */
11577 sd->nr_balance_failed = 0;
11579 schedstat_inc(sd->alb_failed);
11584 busiest_rq->active_balance = 0;
11585 rq_unlock(busiest_rq, &rf);
11588 attach_one_task(target_rq, p);
11590 local_irq_enable();
11595 static DEFINE_SPINLOCK(balancing);
11598 * Scale the max load_balance interval with the number of CPUs in the system.
11599 * This trades load-balance latency on larger machines for less cross talk.
11601 void update_max_interval(void)
11603 max_load_balance_interval = HZ*num_online_cpus()/10;
11606 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11608 if (cost > sd->max_newidle_lb_cost) {
11610 * Track max cost of a domain to make sure to not delay the
11611 * next wakeup on the CPU.
11613 sd->max_newidle_lb_cost = cost;
11614 sd->last_decay_max_lb_cost = jiffies;
11615 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11617 * Decay the newidle max times by ~1% per second to ensure that
11618 * it is not outdated and the current max cost is actually
11621 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11622 sd->last_decay_max_lb_cost = jiffies;
11631 * It checks each scheduling domain to see if it is due to be balanced,
11632 * and initiates a balancing operation if so.
11634 * Balancing parameters are set up in init_sched_domains.
11636 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11638 int continue_balancing = 1;
11640 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11641 unsigned long interval;
11642 struct sched_domain *sd;
11643 /* Earliest time when we have to do rebalance again */
11644 unsigned long next_balance = jiffies + 60*HZ;
11645 int update_next_balance = 0;
11646 int need_serialize, need_decay = 0;
11650 for_each_domain(cpu, sd) {
11652 * Decay the newidle max times here because this is a regular
11653 * visit to all the domains.
11655 need_decay = update_newidle_cost(sd, 0);
11656 max_cost += sd->max_newidle_lb_cost;
11659 * Stop the load balance at this level. There is another
11660 * CPU in our sched group which is doing load balancing more
11663 if (!continue_balancing) {
11669 interval = get_sd_balance_interval(sd, busy);
11671 need_serialize = sd->flags & SD_SERIALIZE;
11672 if (need_serialize) {
11673 if (!spin_trylock(&balancing))
11677 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11678 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11680 * The LBF_DST_PINNED logic could have changed
11681 * env->dst_cpu, so we can't know our idle
11682 * state even if we migrated tasks. Update it.
11684 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11685 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11687 sd->last_balance = jiffies;
11688 interval = get_sd_balance_interval(sd, busy);
11690 if (need_serialize)
11691 spin_unlock(&balancing);
11693 if (time_after(next_balance, sd->last_balance + interval)) {
11694 next_balance = sd->last_balance + interval;
11695 update_next_balance = 1;
11700 * Ensure the rq-wide value also decays but keep it at a
11701 * reasonable floor to avoid funnies with rq->avg_idle.
11703 rq->max_idle_balance_cost =
11704 max((u64)sysctl_sched_migration_cost, max_cost);
11709 * next_balance will be updated only when there is a need.
11710 * When the cpu is attached to null domain for ex, it will not be
11713 if (likely(update_next_balance))
11714 rq->next_balance = next_balance;
11718 static inline int on_null_domain(struct rq *rq)
11720 return unlikely(!rcu_dereference_sched(rq->sd));
11723 #ifdef CONFIG_NO_HZ_COMMON
11725 * NOHZ idle load balancing (ILB) details:
11727 * - When one of the busy CPUs notices that there may be an idle rebalancing
11728 * needed, they will kick the idle load balancer, which then does idle
11729 * load balancing for all the idle CPUs.
11731 * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED is not set
11734 static inline int find_new_ilb(void)
11736 const struct cpumask *hk_mask;
11739 hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11741 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
11743 if (ilb_cpu == smp_processor_id())
11746 if (idle_cpu(ilb_cpu))
11754 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
11755 * SMP function call (IPI).
11757 * We pick the first idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11759 static void kick_ilb(unsigned int flags)
11764 * Increase nohz.next_balance only when if full ilb is triggered but
11765 * not if we only update stats.
11767 if (flags & NOHZ_BALANCE_KICK)
11768 nohz.next_balance = jiffies+1;
11770 ilb_cpu = find_new_ilb();
11775 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11776 * the first flag owns it; cleared by nohz_csd_func().
11778 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11779 if (flags & NOHZ_KICK_MASK)
11783 * This way we generate an IPI on the target CPU which
11784 * is idle, and the softirq performing NOHZ idle load balancing
11785 * will be run before returning from the IPI.
11787 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11791 * Current decision point for kicking the idle load balancer in the presence
11792 * of idle CPUs in the system.
11794 static void nohz_balancer_kick(struct rq *rq)
11796 unsigned long now = jiffies;
11797 struct sched_domain_shared *sds;
11798 struct sched_domain *sd;
11799 int nr_busy, i, cpu = rq->cpu;
11800 unsigned int flags = 0;
11802 if (unlikely(rq->idle_balance))
11806 * We may be recently in ticked or tickless idle mode. At the first
11807 * busy tick after returning from idle, we will update the busy stats.
11809 nohz_balance_exit_idle(rq);
11812 * None are in tickless mode and hence no need for NOHZ idle load
11815 if (likely(!atomic_read(&nohz.nr_cpus)))
11818 if (READ_ONCE(nohz.has_blocked) &&
11819 time_after(now, READ_ONCE(nohz.next_blocked)))
11820 flags = NOHZ_STATS_KICK;
11822 if (time_before(now, nohz.next_balance))
11825 if (rq->nr_running >= 2) {
11826 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11832 sd = rcu_dereference(rq->sd);
11835 * If there's a runnable CFS task and the current CPU has reduced
11836 * capacity, kick the ILB to see if there's a better CPU to run on:
11838 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11839 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11844 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11847 * When ASYM_PACKING; see if there's a more preferred CPU
11848 * currently idle; in which case, kick the ILB to move tasks
11851 * When balancing betwen cores, all the SMT siblings of the
11852 * preferred CPU must be idle.
11854 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11855 if (sched_use_asym_prio(sd, i) &&
11856 sched_asym_prefer(i, cpu)) {
11857 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11863 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11866 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11867 * to run the misfit task on.
11869 if (check_misfit_status(rq, sd)) {
11870 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11875 * For asymmetric systems, we do not want to nicely balance
11876 * cache use, instead we want to embrace asymmetry and only
11877 * ensure tasks have enough CPU capacity.
11879 * Skip the LLC logic because it's not relevant in that case.
11884 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11887 * If there is an imbalance between LLC domains (IOW we could
11888 * increase the overall cache utilization), we need a less-loaded LLC
11889 * domain to pull some load from. Likewise, we may need to spread
11890 * load within the current LLC domain (e.g. packed SMT cores but
11891 * other CPUs are idle). We can't really know from here how busy
11892 * the others are - so just get a NOHZ balance going if it looks
11893 * like this LLC domain has tasks we could move.
11895 nr_busy = atomic_read(&sds->nr_busy_cpus);
11897 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11904 if (READ_ONCE(nohz.needs_update))
11905 flags |= NOHZ_NEXT_KICK;
11911 static void set_cpu_sd_state_busy(int cpu)
11913 struct sched_domain *sd;
11916 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11918 if (!sd || !sd->nohz_idle)
11922 atomic_inc(&sd->shared->nr_busy_cpus);
11927 void nohz_balance_exit_idle(struct rq *rq)
11929 SCHED_WARN_ON(rq != this_rq());
11931 if (likely(!rq->nohz_tick_stopped))
11934 rq->nohz_tick_stopped = 0;
11935 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
11936 atomic_dec(&nohz.nr_cpus);
11938 set_cpu_sd_state_busy(rq->cpu);
11941 static void set_cpu_sd_state_idle(int cpu)
11943 struct sched_domain *sd;
11946 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11948 if (!sd || sd->nohz_idle)
11952 atomic_dec(&sd->shared->nr_busy_cpus);
11958 * This routine will record that the CPU is going idle with tick stopped.
11959 * This info will be used in performing idle load balancing in the future.
11961 void nohz_balance_enter_idle(int cpu)
11963 struct rq *rq = cpu_rq(cpu);
11965 SCHED_WARN_ON(cpu != smp_processor_id());
11967 /* If this CPU is going down, then nothing needs to be done: */
11968 if (!cpu_active(cpu))
11971 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
11972 if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
11976 * Can be set safely without rq->lock held
11977 * If a clear happens, it will have evaluated last additions because
11978 * rq->lock is held during the check and the clear
11980 rq->has_blocked_load = 1;
11983 * The tick is still stopped but load could have been added in the
11984 * meantime. We set the nohz.has_blocked flag to trig a check of the
11985 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
11986 * of nohz.has_blocked can only happen after checking the new load
11988 if (rq->nohz_tick_stopped)
11991 /* If we're a completely isolated CPU, we don't play: */
11992 if (on_null_domain(rq))
11995 rq->nohz_tick_stopped = 1;
11997 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
11998 atomic_inc(&nohz.nr_cpus);
12001 * Ensures that if nohz_idle_balance() fails to observe our
12002 * @idle_cpus_mask store, it must observe the @has_blocked
12003 * and @needs_update stores.
12005 smp_mb__after_atomic();
12007 set_cpu_sd_state_idle(cpu);
12009 WRITE_ONCE(nohz.needs_update, 1);
12012 * Each time a cpu enter idle, we assume that it has blocked load and
12013 * enable the periodic update of the load of idle cpus
12015 WRITE_ONCE(nohz.has_blocked, 1);
12018 static bool update_nohz_stats(struct rq *rq)
12020 unsigned int cpu = rq->cpu;
12022 if (!rq->has_blocked_load)
12025 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12028 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12031 update_blocked_averages(cpu);
12033 return rq->has_blocked_load;
12037 * Internal function that runs load balance for all idle cpus. The load balance
12038 * can be a simple update of blocked load or a complete load balance with
12039 * tasks movement depending of flags.
12041 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12043 /* Earliest time when we have to do rebalance again */
12044 unsigned long now = jiffies;
12045 unsigned long next_balance = now + 60*HZ;
12046 bool has_blocked_load = false;
12047 int update_next_balance = 0;
12048 int this_cpu = this_rq->cpu;
12052 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12055 * We assume there will be no idle load after this update and clear
12056 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12057 * set the has_blocked flag and trigger another update of idle load.
12058 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12059 * setting the flag, we are sure to not clear the state and not
12060 * check the load of an idle cpu.
12062 * Same applies to idle_cpus_mask vs needs_update.
12064 if (flags & NOHZ_STATS_KICK)
12065 WRITE_ONCE(nohz.has_blocked, 0);
12066 if (flags & NOHZ_NEXT_KICK)
12067 WRITE_ONCE(nohz.needs_update, 0);
12070 * Ensures that if we miss the CPU, we must see the has_blocked
12071 * store from nohz_balance_enter_idle().
12076 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12077 * chance for other idle cpu to pull load.
12079 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12080 if (!idle_cpu(balance_cpu))
12084 * If this CPU gets work to do, stop the load balancing
12085 * work being done for other CPUs. Next load
12086 * balancing owner will pick it up.
12088 if (need_resched()) {
12089 if (flags & NOHZ_STATS_KICK)
12090 has_blocked_load = true;
12091 if (flags & NOHZ_NEXT_KICK)
12092 WRITE_ONCE(nohz.needs_update, 1);
12096 rq = cpu_rq(balance_cpu);
12098 if (flags & NOHZ_STATS_KICK)
12099 has_blocked_load |= update_nohz_stats(rq);
12102 * If time for next balance is due,
12105 if (time_after_eq(jiffies, rq->next_balance)) {
12106 struct rq_flags rf;
12108 rq_lock_irqsave(rq, &rf);
12109 update_rq_clock(rq);
12110 rq_unlock_irqrestore(rq, &rf);
12112 if (flags & NOHZ_BALANCE_KICK)
12113 rebalance_domains(rq, CPU_IDLE);
12116 if (time_after(next_balance, rq->next_balance)) {
12117 next_balance = rq->next_balance;
12118 update_next_balance = 1;
12123 * next_balance will be updated only when there is a need.
12124 * When the CPU is attached to null domain for ex, it will not be
12127 if (likely(update_next_balance))
12128 nohz.next_balance = next_balance;
12130 if (flags & NOHZ_STATS_KICK)
12131 WRITE_ONCE(nohz.next_blocked,
12132 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12135 /* There is still blocked load, enable periodic update */
12136 if (has_blocked_load)
12137 WRITE_ONCE(nohz.has_blocked, 1);
12141 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12142 * rebalancing for all the cpus for whom scheduler ticks are stopped.
12144 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12146 unsigned int flags = this_rq->nohz_idle_balance;
12151 this_rq->nohz_idle_balance = 0;
12153 if (idle != CPU_IDLE)
12156 _nohz_idle_balance(this_rq, flags);
12162 * Check if we need to directly run the ILB for updating blocked load before
12163 * entering idle state. Here we run ILB directly without issuing IPIs.
12165 * Note that when this function is called, the tick may not yet be stopped on
12166 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12167 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12168 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12169 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12170 * called from this function on (this) CPU that's not yet in the mask. That's
12171 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12172 * updating the blocked load of already idle CPUs without waking up one of
12173 * those idle CPUs and outside the preempt disable / irq off phase of the local
12174 * cpu about to enter idle, because it can take a long time.
12176 void nohz_run_idle_balance(int cpu)
12178 unsigned int flags;
12180 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12183 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12184 * (ie NOHZ_STATS_KICK set) and will do the same.
12186 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12187 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12190 static void nohz_newidle_balance(struct rq *this_rq)
12192 int this_cpu = this_rq->cpu;
12195 * This CPU doesn't want to be disturbed by scheduler
12198 if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
12201 /* Will wake up very soon. No time for doing anything else*/
12202 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12205 /* Don't need to update blocked load of idle CPUs*/
12206 if (!READ_ONCE(nohz.has_blocked) ||
12207 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12211 * Set the need to trigger ILB in order to update blocked load
12212 * before entering idle state.
12214 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12217 #else /* !CONFIG_NO_HZ_COMMON */
12218 static inline void nohz_balancer_kick(struct rq *rq) { }
12220 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12225 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12226 #endif /* CONFIG_NO_HZ_COMMON */
12229 * newidle_balance is called by schedule() if this_cpu is about to become
12230 * idle. Attempts to pull tasks from other CPUs.
12233 * < 0 - we released the lock and there are !fair tasks present
12234 * 0 - failed, no new tasks
12235 * > 0 - success, new (fair) tasks present
12237 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12239 unsigned long next_balance = jiffies + HZ;
12240 int this_cpu = this_rq->cpu;
12241 u64 t0, t1, curr_cost = 0;
12242 struct sched_domain *sd;
12243 int pulled_task = 0;
12245 update_misfit_status(NULL, this_rq);
12248 * There is a task waiting to run. No need to search for one.
12249 * Return 0; the task will be enqueued when switching to idle.
12251 if (this_rq->ttwu_pending)
12255 * We must set idle_stamp _before_ calling idle_balance(), such that we
12256 * measure the duration of idle_balance() as idle time.
12258 this_rq->idle_stamp = rq_clock(this_rq);
12261 * Do not pull tasks towards !active CPUs...
12263 if (!cpu_active(this_cpu))
12267 * This is OK, because current is on_cpu, which avoids it being picked
12268 * for load-balance and preemption/IRQs are still disabled avoiding
12269 * further scheduler activity on it and we're being very careful to
12270 * re-start the picking loop.
12272 rq_unpin_lock(this_rq, rf);
12275 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12277 if (!READ_ONCE(this_rq->rd->overload) ||
12278 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12281 update_next_balance(sd, &next_balance);
12288 raw_spin_rq_unlock(this_rq);
12290 t0 = sched_clock_cpu(this_cpu);
12291 update_blocked_averages(this_cpu);
12294 for_each_domain(this_cpu, sd) {
12295 int continue_balancing = 1;
12298 update_next_balance(sd, &next_balance);
12300 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12303 if (sd->flags & SD_BALANCE_NEWIDLE) {
12305 pulled_task = load_balance(this_cpu, this_rq,
12306 sd, CPU_NEWLY_IDLE,
12307 &continue_balancing);
12309 t1 = sched_clock_cpu(this_cpu);
12310 domain_cost = t1 - t0;
12311 update_newidle_cost(sd, domain_cost);
12313 curr_cost += domain_cost;
12318 * Stop searching for tasks to pull if there are
12319 * now runnable tasks on this rq.
12321 if (pulled_task || this_rq->nr_running > 0 ||
12322 this_rq->ttwu_pending)
12327 raw_spin_rq_lock(this_rq);
12329 if (curr_cost > this_rq->max_idle_balance_cost)
12330 this_rq->max_idle_balance_cost = curr_cost;
12333 * While browsing the domains, we released the rq lock, a task could
12334 * have been enqueued in the meantime. Since we're not going idle,
12335 * pretend we pulled a task.
12337 if (this_rq->cfs.h_nr_running && !pulled_task)
12340 /* Is there a task of a high priority class? */
12341 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12345 /* Move the next balance forward */
12346 if (time_after(this_rq->next_balance, next_balance))
12347 this_rq->next_balance = next_balance;
12350 this_rq->idle_stamp = 0;
12352 nohz_newidle_balance(this_rq);
12354 rq_repin_lock(this_rq, rf);
12356 return pulled_task;
12360 * run_rebalance_domains is triggered when needed from the scheduler tick.
12361 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12363 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12365 struct rq *this_rq = this_rq();
12366 enum cpu_idle_type idle = this_rq->idle_balance ?
12367 CPU_IDLE : CPU_NOT_IDLE;
12370 * If this CPU has a pending nohz_balance_kick, then do the
12371 * balancing on behalf of the other idle CPUs whose ticks are
12372 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12373 * give the idle CPUs a chance to load balance. Else we may
12374 * load balance only within the local sched_domain hierarchy
12375 * and abort nohz_idle_balance altogether if we pull some load.
12377 if (nohz_idle_balance(this_rq, idle))
12380 /* normal load balance */
12381 update_blocked_averages(this_rq->cpu);
12382 rebalance_domains(this_rq, idle);
12386 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12388 void trigger_load_balance(struct rq *rq)
12391 * Don't need to rebalance while attached to NULL domain or
12392 * runqueue CPU is not active
12394 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12397 if (time_after_eq(jiffies, rq->next_balance))
12398 raise_softirq(SCHED_SOFTIRQ);
12400 nohz_balancer_kick(rq);
12403 static void rq_online_fair(struct rq *rq)
12407 update_runtime_enabled(rq);
12410 static void rq_offline_fair(struct rq *rq)
12414 /* Ensure any throttled groups are reachable by pick_next_task */
12415 unthrottle_offline_cfs_rqs(rq);
12418 #endif /* CONFIG_SMP */
12420 #ifdef CONFIG_SCHED_CORE
12422 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12424 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12425 u64 slice = se->slice;
12427 return (rtime * min_nr_tasks > slice);
12430 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
12431 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12433 if (!sched_core_enabled(rq))
12437 * If runqueue has only one task which used up its slice and
12438 * if the sibling is forced idle, then trigger schedule to
12439 * give forced idle task a chance.
12441 * sched_slice() considers only this active rq and it gets the
12442 * whole slice. But during force idle, we have siblings acting
12443 * like a single runqueue and hence we need to consider runnable
12444 * tasks on this CPU and the forced idle CPU. Ideally, we should
12445 * go through the forced idle rq, but that would be a perf hit.
12446 * We can assume that the forced idle CPU has at least
12447 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12448 * if we need to give up the CPU.
12450 if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12451 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12456 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12458 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12461 for_each_sched_entity(se) {
12462 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12465 if (cfs_rq->forceidle_seq == fi_seq)
12467 cfs_rq->forceidle_seq = fi_seq;
12470 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12474 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12476 struct sched_entity *se = &p->se;
12478 if (p->sched_class != &fair_sched_class)
12481 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12484 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12487 struct rq *rq = task_rq(a);
12488 const struct sched_entity *sea = &a->se;
12489 const struct sched_entity *seb = &b->se;
12490 struct cfs_rq *cfs_rqa;
12491 struct cfs_rq *cfs_rqb;
12494 SCHED_WARN_ON(task_rq(b)->core != rq->core);
12496 #ifdef CONFIG_FAIR_GROUP_SCHED
12498 * Find an se in the hierarchy for tasks a and b, such that the se's
12499 * are immediate siblings.
12501 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12502 int sea_depth = sea->depth;
12503 int seb_depth = seb->depth;
12505 if (sea_depth >= seb_depth)
12506 sea = parent_entity(sea);
12507 if (sea_depth <= seb_depth)
12508 seb = parent_entity(seb);
12511 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12512 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12514 cfs_rqa = sea->cfs_rq;
12515 cfs_rqb = seb->cfs_rq;
12517 cfs_rqa = &task_rq(a)->cfs;
12518 cfs_rqb = &task_rq(b)->cfs;
12522 * Find delta after normalizing se's vruntime with its cfs_rq's
12523 * min_vruntime_fi, which would have been updated in prior calls
12524 * to se_fi_update().
12526 delta = (s64)(sea->vruntime - seb->vruntime) +
12527 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12532 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12534 struct cfs_rq *cfs_rq;
12536 #ifdef CONFIG_FAIR_GROUP_SCHED
12537 cfs_rq = task_group(p)->cfs_rq[cpu];
12539 cfs_rq = &cpu_rq(cpu)->cfs;
12541 return throttled_hierarchy(cfs_rq);
12544 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12548 * scheduler tick hitting a task of our scheduling class.
12550 * NOTE: This function can be called remotely by the tick offload that
12551 * goes along full dynticks. Therefore no local assumption can be made
12552 * and everything must be accessed through the @rq and @curr passed in
12555 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12557 struct cfs_rq *cfs_rq;
12558 struct sched_entity *se = &curr->se;
12560 for_each_sched_entity(se) {
12561 cfs_rq = cfs_rq_of(se);
12562 entity_tick(cfs_rq, se, queued);
12565 if (static_branch_unlikely(&sched_numa_balancing))
12566 task_tick_numa(rq, curr);
12568 update_misfit_status(curr, rq);
12569 update_overutilized_status(task_rq(curr));
12571 task_tick_core(rq, curr);
12575 * called on fork with the child task as argument from the parent's context
12576 * - child not yet on the tasklist
12577 * - preemption disabled
12579 static void task_fork_fair(struct task_struct *p)
12581 struct sched_entity *se = &p->se, *curr;
12582 struct cfs_rq *cfs_rq;
12583 struct rq *rq = this_rq();
12584 struct rq_flags rf;
12587 update_rq_clock(rq);
12589 cfs_rq = task_cfs_rq(current);
12590 curr = cfs_rq->curr;
12592 update_curr(cfs_rq);
12593 place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12594 rq_unlock(rq, &rf);
12598 * Priority of the task has changed. Check to see if we preempt
12599 * the current task.
12602 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12604 if (!task_on_rq_queued(p))
12607 if (rq->cfs.nr_running == 1)
12611 * Reschedule if we are currently running on this runqueue and
12612 * our priority decreased, or if we are not currently running on
12613 * this runqueue and our priority is higher than the current's
12615 if (task_current(rq, p)) {
12616 if (p->prio > oldprio)
12619 wakeup_preempt(rq, p, 0);
12622 #ifdef CONFIG_FAIR_GROUP_SCHED
12624 * Propagate the changes of the sched_entity across the tg tree to make it
12625 * visible to the root
12627 static void propagate_entity_cfs_rq(struct sched_entity *se)
12629 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12631 if (cfs_rq_throttled(cfs_rq))
12634 if (!throttled_hierarchy(cfs_rq))
12635 list_add_leaf_cfs_rq(cfs_rq);
12637 /* Start to propagate at parent */
12640 for_each_sched_entity(se) {
12641 cfs_rq = cfs_rq_of(se);
12643 update_load_avg(cfs_rq, se, UPDATE_TG);
12645 if (cfs_rq_throttled(cfs_rq))
12648 if (!throttled_hierarchy(cfs_rq))
12649 list_add_leaf_cfs_rq(cfs_rq);
12653 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12656 static void detach_entity_cfs_rq(struct sched_entity *se)
12658 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12662 * In case the task sched_avg hasn't been attached:
12663 * - A forked task which hasn't been woken up by wake_up_new_task().
12664 * - A task which has been woken up by try_to_wake_up() but is
12665 * waiting for actually being woken up by sched_ttwu_pending().
12667 if (!se->avg.last_update_time)
12671 /* Catch up with the cfs_rq and remove our load when we leave */
12672 update_load_avg(cfs_rq, se, 0);
12673 detach_entity_load_avg(cfs_rq, se);
12674 update_tg_load_avg(cfs_rq);
12675 propagate_entity_cfs_rq(se);
12678 static void attach_entity_cfs_rq(struct sched_entity *se)
12680 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12682 /* Synchronize entity with its cfs_rq */
12683 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12684 attach_entity_load_avg(cfs_rq, se);
12685 update_tg_load_avg(cfs_rq);
12686 propagate_entity_cfs_rq(se);
12689 static void detach_task_cfs_rq(struct task_struct *p)
12691 struct sched_entity *se = &p->se;
12693 detach_entity_cfs_rq(se);
12696 static void attach_task_cfs_rq(struct task_struct *p)
12698 struct sched_entity *se = &p->se;
12700 attach_entity_cfs_rq(se);
12703 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12705 detach_task_cfs_rq(p);
12708 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12710 attach_task_cfs_rq(p);
12712 if (task_on_rq_queued(p)) {
12714 * We were most likely switched from sched_rt, so
12715 * kick off the schedule if running, otherwise just see
12716 * if we can still preempt the current task.
12718 if (task_current(rq, p))
12721 wakeup_preempt(rq, p, 0);
12725 /* Account for a task changing its policy or group.
12727 * This routine is mostly called to set cfs_rq->curr field when a task
12728 * migrates between groups/classes.
12730 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12732 struct sched_entity *se = &p->se;
12735 if (task_on_rq_queued(p)) {
12737 * Move the next running task to the front of the list, so our
12738 * cfs_tasks list becomes MRU one.
12740 list_move(&se->group_node, &rq->cfs_tasks);
12744 for_each_sched_entity(se) {
12745 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12747 set_next_entity(cfs_rq, se);
12748 /* ensure bandwidth has been allocated on our new cfs_rq */
12749 account_cfs_rq_runtime(cfs_rq, 0);
12753 void init_cfs_rq(struct cfs_rq *cfs_rq)
12755 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12756 u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12758 raw_spin_lock_init(&cfs_rq->removed.lock);
12762 #ifdef CONFIG_FAIR_GROUP_SCHED
12763 static void task_change_group_fair(struct task_struct *p)
12766 * We couldn't detach or attach a forked task which
12767 * hasn't been woken up by wake_up_new_task().
12769 if (READ_ONCE(p->__state) == TASK_NEW)
12772 detach_task_cfs_rq(p);
12775 /* Tell se's cfs_rq has been changed -- migrated */
12776 p->se.avg.last_update_time = 0;
12778 set_task_rq(p, task_cpu(p));
12779 attach_task_cfs_rq(p);
12782 void free_fair_sched_group(struct task_group *tg)
12786 for_each_possible_cpu(i) {
12788 kfree(tg->cfs_rq[i]);
12797 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12799 struct sched_entity *se;
12800 struct cfs_rq *cfs_rq;
12803 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12806 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12810 tg->shares = NICE_0_LOAD;
12812 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12814 for_each_possible_cpu(i) {
12815 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12816 GFP_KERNEL, cpu_to_node(i));
12820 se = kzalloc_node(sizeof(struct sched_entity_stats),
12821 GFP_KERNEL, cpu_to_node(i));
12825 init_cfs_rq(cfs_rq);
12826 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12827 init_entity_runnable_average(se);
12838 void online_fair_sched_group(struct task_group *tg)
12840 struct sched_entity *se;
12841 struct rq_flags rf;
12845 for_each_possible_cpu(i) {
12848 rq_lock_irq(rq, &rf);
12849 update_rq_clock(rq);
12850 attach_entity_cfs_rq(se);
12851 sync_throttle(tg, i);
12852 rq_unlock_irq(rq, &rf);
12856 void unregister_fair_sched_group(struct task_group *tg)
12858 unsigned long flags;
12862 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12864 for_each_possible_cpu(cpu) {
12866 remove_entity_load_avg(tg->se[cpu]);
12869 * Only empty task groups can be destroyed; so we can speculatively
12870 * check on_list without danger of it being re-added.
12872 if (!tg->cfs_rq[cpu]->on_list)
12877 raw_spin_rq_lock_irqsave(rq, flags);
12878 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12879 raw_spin_rq_unlock_irqrestore(rq, flags);
12883 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12884 struct sched_entity *se, int cpu,
12885 struct sched_entity *parent)
12887 struct rq *rq = cpu_rq(cpu);
12891 init_cfs_rq_runtime(cfs_rq);
12893 tg->cfs_rq[cpu] = cfs_rq;
12896 /* se could be NULL for root_task_group */
12901 se->cfs_rq = &rq->cfs;
12904 se->cfs_rq = parent->my_q;
12905 se->depth = parent->depth + 1;
12909 /* guarantee group entities always have weight */
12910 update_load_set(&se->load, NICE_0_LOAD);
12911 se->parent = parent;
12914 static DEFINE_MUTEX(shares_mutex);
12916 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
12920 lockdep_assert_held(&shares_mutex);
12923 * We can't change the weight of the root cgroup.
12928 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
12930 if (tg->shares == shares)
12933 tg->shares = shares;
12934 for_each_possible_cpu(i) {
12935 struct rq *rq = cpu_rq(i);
12936 struct sched_entity *se = tg->se[i];
12937 struct rq_flags rf;
12939 /* Propagate contribution to hierarchy */
12940 rq_lock_irqsave(rq, &rf);
12941 update_rq_clock(rq);
12942 for_each_sched_entity(se) {
12943 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
12944 update_cfs_group(se);
12946 rq_unlock_irqrestore(rq, &rf);
12952 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
12956 mutex_lock(&shares_mutex);
12957 if (tg_is_idle(tg))
12960 ret = __sched_group_set_shares(tg, shares);
12961 mutex_unlock(&shares_mutex);
12966 int sched_group_set_idle(struct task_group *tg, long idle)
12970 if (tg == &root_task_group)
12973 if (idle < 0 || idle > 1)
12976 mutex_lock(&shares_mutex);
12978 if (tg->idle == idle) {
12979 mutex_unlock(&shares_mutex);
12985 for_each_possible_cpu(i) {
12986 struct rq *rq = cpu_rq(i);
12987 struct sched_entity *se = tg->se[i];
12988 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
12989 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
12990 long idle_task_delta;
12991 struct rq_flags rf;
12993 rq_lock_irqsave(rq, &rf);
12995 grp_cfs_rq->idle = idle;
12996 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13000 parent_cfs_rq = cfs_rq_of(se);
13001 if (cfs_rq_is_idle(grp_cfs_rq))
13002 parent_cfs_rq->idle_nr_running++;
13004 parent_cfs_rq->idle_nr_running--;
13007 idle_task_delta = grp_cfs_rq->h_nr_running -
13008 grp_cfs_rq->idle_h_nr_running;
13009 if (!cfs_rq_is_idle(grp_cfs_rq))
13010 idle_task_delta *= -1;
13012 for_each_sched_entity(se) {
13013 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13018 cfs_rq->idle_h_nr_running += idle_task_delta;
13020 /* Already accounted at parent level and above. */
13021 if (cfs_rq_is_idle(cfs_rq))
13026 rq_unlock_irqrestore(rq, &rf);
13029 /* Idle groups have minimum weight. */
13030 if (tg_is_idle(tg))
13031 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13033 __sched_group_set_shares(tg, NICE_0_LOAD);
13035 mutex_unlock(&shares_mutex);
13039 #else /* CONFIG_FAIR_GROUP_SCHED */
13041 void free_fair_sched_group(struct task_group *tg) { }
13043 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13048 void online_fair_sched_group(struct task_group *tg) { }
13050 void unregister_fair_sched_group(struct task_group *tg) { }
13052 #endif /* CONFIG_FAIR_GROUP_SCHED */
13055 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13057 struct sched_entity *se = &task->se;
13058 unsigned int rr_interval = 0;
13061 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13064 if (rq->cfs.load.weight)
13065 rr_interval = NS_TO_JIFFIES(se->slice);
13067 return rr_interval;
13071 * All the scheduling class methods:
13073 DEFINE_SCHED_CLASS(fair) = {
13075 .enqueue_task = enqueue_task_fair,
13076 .dequeue_task = dequeue_task_fair,
13077 .yield_task = yield_task_fair,
13078 .yield_to_task = yield_to_task_fair,
13080 .wakeup_preempt = check_preempt_wakeup_fair,
13082 .pick_next_task = __pick_next_task_fair,
13083 .put_prev_task = put_prev_task_fair,
13084 .set_next_task = set_next_task_fair,
13087 .balance = balance_fair,
13088 .pick_task = pick_task_fair,
13089 .select_task_rq = select_task_rq_fair,
13090 .migrate_task_rq = migrate_task_rq_fair,
13092 .rq_online = rq_online_fair,
13093 .rq_offline = rq_offline_fair,
13095 .task_dead = task_dead_fair,
13096 .set_cpus_allowed = set_cpus_allowed_common,
13099 .task_tick = task_tick_fair,
13100 .task_fork = task_fork_fair,
13102 .prio_changed = prio_changed_fair,
13103 .switched_from = switched_from_fair,
13104 .switched_to = switched_to_fair,
13106 .get_rr_interval = get_rr_interval_fair,
13108 .update_curr = update_curr_fair,
13110 #ifdef CONFIG_FAIR_GROUP_SCHED
13111 .task_change_group = task_change_group_fair,
13114 #ifdef CONFIG_SCHED_CORE
13115 .task_is_throttled = task_is_throttled_fair,
13118 #ifdef CONFIG_UCLAMP_TASK
13119 .uclamp_enabled = 1,
13123 #ifdef CONFIG_SCHED_DEBUG
13124 void print_cfs_stats(struct seq_file *m, int cpu)
13126 struct cfs_rq *cfs_rq, *pos;
13129 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13130 print_cfs_rq(m, cpu, cfs_rq);
13134 #ifdef CONFIG_NUMA_BALANCING
13135 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13138 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13139 struct numa_group *ng;
13142 ng = rcu_dereference(p->numa_group);
13143 for_each_online_node(node) {
13144 if (p->numa_faults) {
13145 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13146 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13149 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13150 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13152 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13156 #endif /* CONFIG_NUMA_BALANCING */
13157 #endif /* CONFIG_SCHED_DEBUG */
13159 __init void init_sched_fair_class(void)
13164 for_each_possible_cpu(i) {
13165 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13166 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13167 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13168 GFP_KERNEL, cpu_to_node(i));
13170 #ifdef CONFIG_CFS_BANDWIDTH
13171 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13172 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13176 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
13178 #ifdef CONFIG_NO_HZ_COMMON
13179 nohz.next_balance = jiffies;
13180 nohz.next_blocked = jiffies;
13181 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);