1 // SPDX-License-Identifier: GPL-2.0
3 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
5 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
7 * Interactivity improvements by Mike Galbraith
8 * (C) 2007 Mike Galbraith <efault@gmx.de>
10 * Various enhancements by Dmitry Adamushko.
11 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
13 * Group scheduling enhancements by Srivatsa Vaddagiri
14 * Copyright IBM Corporation, 2007
15 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
17 * Scaled math optimizations by Thomas Gleixner
18 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
23 #include <linux/energy_model.h>
24 #include <linux/mmap_lock.h>
25 #include <linux/hugetlb_inline.h>
26 #include <linux/jiffies.h>
27 #include <linux/mm_api.h>
28 #include <linux/highmem.h>
29 #include <linux/spinlock_api.h>
30 #include <linux/cpumask_api.h>
31 #include <linux/lockdep_api.h>
32 #include <linux/softirq.h>
33 #include <linux/refcount_api.h>
34 #include <linux/topology.h>
35 #include <linux/sched/clock.h>
36 #include <linux/sched/cond_resched.h>
37 #include <linux/sched/cputime.h>
38 #include <linux/sched/isolation.h>
39 #include <linux/sched/nohz.h>
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
52 #include <asm/switch_to.h>
54 #include <linux/sched/cond_resched.h>
58 #include "autogroup.h"
61 * The initial- and re-scaling of tunables is configurable
65 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
66 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
67 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
69 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
71 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
74 * Minimal preemption granularity for CPU-bound tasks:
76 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
78 unsigned int sysctl_sched_base_slice = 750000ULL;
79 static unsigned int normalized_sysctl_sched_base_slice = 750000ULL;
82 * After fork, child runs first. If set to 0 (default) then
83 * parent will (try to) run first.
85 unsigned int sysctl_sched_child_runs_first __read_mostly;
87 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
89 int sched_thermal_decay_shift;
90 static int __init setup_sched_thermal_decay_shift(char *str)
94 if (kstrtoint(str, 0, &_shift))
95 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
97 sched_thermal_decay_shift = clamp(_shift, 0, 10);
100 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
104 * For asym packing, by default the lower numbered CPU has higher priority.
106 int __weak arch_asym_cpu_priority(int cpu)
112 * The margin used when comparing utilization with CPU capacity.
116 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
119 * The margin used when comparing CPU capacities.
120 * is 'cap1' noticeably greater than 'cap2'
124 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
127 #ifdef CONFIG_CFS_BANDWIDTH
129 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
130 * each time a cfs_rq requests quota.
132 * Note: in the case that the slice exceeds the runtime remaining (either due
133 * to consumption or the quota being specified to be smaller than the slice)
134 * we will always only issue the remaining available time.
136 * (default: 5 msec, units: microseconds)
138 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
141 #ifdef CONFIG_NUMA_BALANCING
142 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
143 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
147 static struct ctl_table sched_fair_sysctls[] = {
149 .procname = "sched_child_runs_first",
150 .data = &sysctl_sched_child_runs_first,
151 .maxlen = sizeof(unsigned int),
153 .proc_handler = proc_dointvec,
155 #ifdef CONFIG_CFS_BANDWIDTH
157 .procname = "sched_cfs_bandwidth_slice_us",
158 .data = &sysctl_sched_cfs_bandwidth_slice,
159 .maxlen = sizeof(unsigned int),
161 .proc_handler = proc_dointvec_minmax,
162 .extra1 = SYSCTL_ONE,
165 #ifdef CONFIG_NUMA_BALANCING
167 .procname = "numa_balancing_promote_rate_limit_MBps",
168 .data = &sysctl_numa_balancing_promote_rate_limit,
169 .maxlen = sizeof(unsigned int),
171 .proc_handler = proc_dointvec_minmax,
172 .extra1 = SYSCTL_ZERO,
174 #endif /* CONFIG_NUMA_BALANCING */
178 static int __init sched_fair_sysctl_init(void)
180 register_sysctl_init("kernel", sched_fair_sysctls);
183 late_initcall(sched_fair_sysctl_init);
186 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
192 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
198 static inline void update_load_set(struct load_weight *lw, unsigned long w)
205 * Increase the granularity value when there are more CPUs,
206 * because with more CPUs the 'effective latency' as visible
207 * to users decreases. But the relationship is not linear,
208 * so pick a second-best guess by going with the log2 of the
211 * This idea comes from the SD scheduler of Con Kolivas:
213 static unsigned int get_update_sysctl_factor(void)
215 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
218 switch (sysctl_sched_tunable_scaling) {
219 case SCHED_TUNABLESCALING_NONE:
222 case SCHED_TUNABLESCALING_LINEAR:
225 case SCHED_TUNABLESCALING_LOG:
227 factor = 1 + ilog2(cpus);
234 static void update_sysctl(void)
236 unsigned int factor = get_update_sysctl_factor();
238 #define SET_SYSCTL(name) \
239 (sysctl_##name = (factor) * normalized_sysctl_##name)
240 SET_SYSCTL(sched_base_slice);
244 void __init sched_init_granularity(void)
249 #define WMULT_CONST (~0U)
250 #define WMULT_SHIFT 32
252 static void __update_inv_weight(struct load_weight *lw)
256 if (likely(lw->inv_weight))
259 w = scale_load_down(lw->weight);
261 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
263 else if (unlikely(!w))
264 lw->inv_weight = WMULT_CONST;
266 lw->inv_weight = WMULT_CONST / w;
270 * delta_exec * weight / lw.weight
272 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
274 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
275 * we're guaranteed shift stays positive because inv_weight is guaranteed to
276 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
278 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
279 * weight/lw.weight <= 1, and therefore our shift will also be positive.
281 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
283 u64 fact = scale_load_down(weight);
284 u32 fact_hi = (u32)(fact >> 32);
285 int shift = WMULT_SHIFT;
288 __update_inv_weight(lw);
290 if (unlikely(fact_hi)) {
296 fact = mul_u32_u32(fact, lw->inv_weight);
298 fact_hi = (u32)(fact >> 32);
305 return mul_u64_u32_shr(delta_exec, fact, shift);
311 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
313 if (unlikely(se->load.weight != NICE_0_LOAD))
314 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
319 const struct sched_class fair_sched_class;
321 /**************************************************************
322 * CFS operations on generic schedulable entities:
325 #ifdef CONFIG_FAIR_GROUP_SCHED
327 /* Walk up scheduling entities hierarchy */
328 #define for_each_sched_entity(se) \
329 for (; se; se = se->parent)
331 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
333 struct rq *rq = rq_of(cfs_rq);
334 int cpu = cpu_of(rq);
337 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
342 * Ensure we either appear before our parent (if already
343 * enqueued) or force our parent to appear after us when it is
344 * enqueued. The fact that we always enqueue bottom-up
345 * reduces this to two cases and a special case for the root
346 * cfs_rq. Furthermore, it also means that we will always reset
347 * tmp_alone_branch either when the branch is connected
348 * to a tree or when we reach the top of the tree
350 if (cfs_rq->tg->parent &&
351 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
353 * If parent is already on the list, we add the child
354 * just before. Thanks to circular linked property of
355 * the list, this means to put the child at the tail
356 * of the list that starts by parent.
358 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
359 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
361 * The branch is now connected to its tree so we can
362 * reset tmp_alone_branch to the beginning of the
365 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
369 if (!cfs_rq->tg->parent) {
371 * cfs rq without parent should be put
372 * at the tail of the list.
374 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
375 &rq->leaf_cfs_rq_list);
377 * We have reach the top of a tree so we can reset
378 * tmp_alone_branch to the beginning of the list.
380 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
385 * The parent has not already been added so we want to
386 * make sure that it will be put after us.
387 * tmp_alone_branch points to the begin of the branch
388 * where we will add parent.
390 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
392 * update tmp_alone_branch to points to the new begin
395 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
399 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
401 if (cfs_rq->on_list) {
402 struct rq *rq = rq_of(cfs_rq);
405 * With cfs_rq being unthrottled/throttled during an enqueue,
406 * it can happen the tmp_alone_branch points the a leaf that
407 * we finally want to del. In this case, tmp_alone_branch moves
408 * to the prev element but it will point to rq->leaf_cfs_rq_list
409 * at the end of the enqueue.
411 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
412 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
414 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
419 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
421 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
424 /* Iterate thr' all leaf cfs_rq's on a runqueue */
425 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
426 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
429 /* Do the two (enqueued) entities belong to the same group ? */
430 static inline struct cfs_rq *
431 is_same_group(struct sched_entity *se, struct sched_entity *pse)
433 if (se->cfs_rq == pse->cfs_rq)
439 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
445 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
447 int se_depth, pse_depth;
450 * preemption test can be made between sibling entities who are in the
451 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
452 * both tasks until we find their ancestors who are siblings of common
456 /* First walk up until both entities are at same depth */
457 se_depth = (*se)->depth;
458 pse_depth = (*pse)->depth;
460 while (se_depth > pse_depth) {
462 *se = parent_entity(*se);
465 while (pse_depth > se_depth) {
467 *pse = parent_entity(*pse);
470 while (!is_same_group(*se, *pse)) {
471 *se = parent_entity(*se);
472 *pse = parent_entity(*pse);
476 static int tg_is_idle(struct task_group *tg)
481 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
483 return cfs_rq->idle > 0;
486 static int se_is_idle(struct sched_entity *se)
488 if (entity_is_task(se))
489 return task_has_idle_policy(task_of(se));
490 return cfs_rq_is_idle(group_cfs_rq(se));
493 #else /* !CONFIG_FAIR_GROUP_SCHED */
495 #define for_each_sched_entity(se) \
496 for (; se; se = NULL)
498 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
503 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
507 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
511 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
512 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
514 static inline struct sched_entity *parent_entity(struct sched_entity *se)
520 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
524 static inline int tg_is_idle(struct task_group *tg)
529 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
534 static int se_is_idle(struct sched_entity *se)
539 #endif /* CONFIG_FAIR_GROUP_SCHED */
541 static __always_inline
542 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
544 /**************************************************************
545 * Scheduling class tree data structure manipulation methods:
548 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
550 s64 delta = (s64)(vruntime - max_vruntime);
552 max_vruntime = vruntime;
557 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
559 s64 delta = (s64)(vruntime - min_vruntime);
561 min_vruntime = vruntime;
566 static inline bool entity_before(const struct sched_entity *a,
567 const struct sched_entity *b)
569 return (s64)(a->vruntime - b->vruntime) < 0;
572 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
574 return (s64)(se->vruntime - cfs_rq->min_vruntime);
577 #define __node_2_se(node) \
578 rb_entry((node), struct sched_entity, run_node)
581 * Compute virtual time from the per-task service numbers:
583 * Fair schedulers conserve lag:
587 * Where lag_i is given by:
589 * lag_i = S - s_i = w_i * (V - v_i)
591 * Where S is the ideal service time and V is it's virtual time counterpart.
595 * \Sum w_i * (V - v_i) = 0
596 * \Sum w_i * V - w_i * v_i = 0
598 * From which we can solve an expression for V in v_i (which we have in
601 * \Sum v_i * w_i \Sum v_i * w_i
602 * V = -------------- = --------------
605 * Specifically, this is the weighted average of all entity virtual runtimes.
607 * [[ NOTE: this is only equal to the ideal scheduler under the condition
608 * that join/leave operations happen at lag_i = 0, otherwise the
609 * virtual time has non-continguous motion equivalent to:
613 * Also see the comment in place_entity() that deals with this. ]]
615 * However, since v_i is u64, and the multiplcation could easily overflow
616 * transform it into a relative form that uses smaller quantities:
618 * Substitute: v_i == (v_i - v0) + v0
620 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
621 * V = ---------------------------- = --------------------- + v0
624 * Which we track using:
626 * v0 := cfs_rq->min_vruntime
627 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
628 * \Sum w_i := cfs_rq->avg_load
630 * Since min_vruntime is a monotonic increasing variable that closely tracks
631 * the per-task service, these deltas: (v_i - v), will be in the order of the
632 * maximal (virtual) lag induced in the system due to quantisation.
634 * Also, we use scale_load_down() to reduce the size.
636 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
639 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
641 unsigned long weight = scale_load_down(se->load.weight);
642 s64 key = entity_key(cfs_rq, se);
644 cfs_rq->avg_vruntime += key * weight;
645 cfs_rq->avg_load += weight;
649 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
651 unsigned long weight = scale_load_down(se->load.weight);
652 s64 key = entity_key(cfs_rq, se);
654 cfs_rq->avg_vruntime -= key * weight;
655 cfs_rq->avg_load -= weight;
659 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
662 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
664 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
668 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
669 * For this to be so, the result of this function must have a left bias.
671 u64 avg_vruntime(struct cfs_rq *cfs_rq)
673 struct sched_entity *curr = cfs_rq->curr;
674 s64 avg = cfs_rq->avg_vruntime;
675 long load = cfs_rq->avg_load;
677 if (curr && curr->on_rq) {
678 unsigned long weight = scale_load_down(curr->load.weight);
680 avg += entity_key(cfs_rq, curr) * weight;
685 /* sign flips effective floor / ceil */
688 avg = div_s64(avg, load);
691 return cfs_rq->min_vruntime + avg;
695 * lag_i = S - s_i = w_i * (V - v_i)
697 * However, since V is approximated by the weighted average of all entities it
698 * is possible -- by addition/removal/reweight to the tree -- to move V around
699 * and end up with a larger lag than we started with.
701 * Limit this to either double the slice length with a minimum of TICK_NSEC
702 * since that is the timing granularity.
704 * EEVDF gives the following limit for a steady state system:
706 * -r_max < lag < max(r_max, q)
708 * XXX could add max_slice to the augmented data to track this.
710 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
714 SCHED_WARN_ON(!se->on_rq);
715 lag = avg_vruntime(cfs_rq) - se->vruntime;
717 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
718 se->vlag = clamp(lag, -limit, limit);
722 * Entity is eligible once it received less service than it ought to have,
725 * lag_i = S - s_i = w_i*(V - v_i)
727 * lag_i >= 0 -> V >= v_i
730 * V = ------------------ + v
733 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
735 * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
736 * to the loss in precision caused by the division.
738 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
740 struct sched_entity *curr = cfs_rq->curr;
741 s64 avg = cfs_rq->avg_vruntime;
742 long load = cfs_rq->avg_load;
744 if (curr && curr->on_rq) {
745 unsigned long weight = scale_load_down(curr->load.weight);
747 avg += entity_key(cfs_rq, curr) * weight;
751 return avg >= entity_key(cfs_rq, se) * load;
754 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
756 u64 min_vruntime = cfs_rq->min_vruntime;
758 * open coded max_vruntime() to allow updating avg_vruntime
760 s64 delta = (s64)(vruntime - min_vruntime);
762 avg_vruntime_update(cfs_rq, delta);
763 min_vruntime = vruntime;
768 static void update_min_vruntime(struct cfs_rq *cfs_rq)
770 struct sched_entity *se = __pick_first_entity(cfs_rq);
771 struct sched_entity *curr = cfs_rq->curr;
773 u64 vruntime = cfs_rq->min_vruntime;
777 vruntime = curr->vruntime;
784 vruntime = se->vruntime;
786 vruntime = min_vruntime(vruntime, se->vruntime);
789 /* ensure we never gain time by being placed backwards. */
790 u64_u32_store(cfs_rq->min_vruntime,
791 __update_min_vruntime(cfs_rq, vruntime));
794 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
796 return entity_before(__node_2_se(a), __node_2_se(b));
799 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
801 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
804 struct sched_entity *rse = __node_2_se(node);
805 if (deadline_gt(min_deadline, se, rse))
806 se->min_deadline = rse->min_deadline;
811 * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
813 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
815 u64 old_min_deadline = se->min_deadline;
816 struct rb_node *node = &se->run_node;
818 se->min_deadline = se->deadline;
819 __update_min_deadline(se, node->rb_right);
820 __update_min_deadline(se, node->rb_left);
822 return se->min_deadline == old_min_deadline;
825 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
826 run_node, min_deadline, min_deadline_update);
829 * Enqueue an entity into the rb-tree:
831 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
833 avg_vruntime_add(cfs_rq, se);
834 se->min_deadline = se->deadline;
835 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
836 __entity_less, &min_deadline_cb);
839 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
841 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
843 avg_vruntime_sub(cfs_rq, se);
846 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
848 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
853 return __node_2_se(left);
857 * Earliest Eligible Virtual Deadline First
859 * In order to provide latency guarantees for different request sizes
860 * EEVDF selects the best runnable task from two criteria:
862 * 1) the task must be eligible (must be owed service)
864 * 2) from those tasks that meet 1), we select the one
865 * with the earliest virtual deadline.
867 * We can do this in O(log n) time due to an augmented RB-tree. The
868 * tree keeps the entries sorted on service, but also functions as a
869 * heap based on the deadline by keeping:
871 * se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
873 * Which allows an EDF like search on (sub)trees.
875 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
877 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
878 struct sched_entity *curr = cfs_rq->curr;
879 struct sched_entity *best = NULL;
881 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
885 * Once selected, run a task until it either becomes non-eligible or
886 * until it gets a new slice. See the HACK in set_next_entity().
888 if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
892 struct sched_entity *se = __node_2_se(node);
895 * If this entity is not eligible, try the left subtree.
897 if (!entity_eligible(cfs_rq, se)) {
898 node = node->rb_left;
903 * If this entity has an earlier deadline than the previous
904 * best, take this one. If it also has the earliest deadline
905 * of its subtree, we're done.
907 if (!best || deadline_gt(deadline, best, se)) {
909 if (best->deadline == best->min_deadline)
914 * If the earlest deadline in this subtree is in the fully
915 * eligible left half of our space, go there.
918 __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
919 node = node->rb_left;
923 node = node->rb_right;
926 if (!best || (curr && deadline_gt(deadline, best, curr)))
929 if (unlikely(!best)) {
930 struct sched_entity *left = __pick_first_entity(cfs_rq);
932 pr_err("EEVDF scheduling fail, picking leftmost\n");
940 #ifdef CONFIG_SCHED_DEBUG
941 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
943 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
948 return __node_2_se(last);
951 /**************************************************************
952 * Scheduling class statistics methods:
955 int sched_update_scaling(void)
957 unsigned int factor = get_update_sysctl_factor();
959 #define WRT_SYSCTL(name) \
960 (normalized_sysctl_##name = sysctl_##name / (factor))
961 WRT_SYSCTL(sched_base_slice);
969 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
972 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
973 * this is probably good enough.
975 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
977 if ((s64)(se->vruntime - se->deadline) < 0)
981 * For EEVDF the virtual time slope is determined by w_i (iow.
982 * nice) while the request time r_i is determined by
983 * sysctl_sched_base_slice.
985 se->slice = sysctl_sched_base_slice;
988 * EEVDF: vd_i = ve_i + r_i / w_i
990 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
993 * The task has consumed its request, reschedule.
995 if (cfs_rq->nr_running > 1) {
996 resched_curr(rq_of(cfs_rq));
997 clear_buddies(cfs_rq, se);
1004 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1005 static unsigned long task_h_load(struct task_struct *p);
1006 static unsigned long capacity_of(int cpu);
1008 /* Give new sched_entity start runnable values to heavy its load in infant time */
1009 void init_entity_runnable_average(struct sched_entity *se)
1011 struct sched_avg *sa = &se->avg;
1013 memset(sa, 0, sizeof(*sa));
1016 * Tasks are initialized with full load to be seen as heavy tasks until
1017 * they get a chance to stabilize to their real load level.
1018 * Group entities are initialized with zero load to reflect the fact that
1019 * nothing has been attached to the task group yet.
1021 if (entity_is_task(se))
1022 sa->load_avg = scale_load_down(se->load.weight);
1024 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1028 * With new tasks being created, their initial util_avgs are extrapolated
1029 * based on the cfs_rq's current util_avg:
1031 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1033 * However, in many cases, the above util_avg does not give a desired
1034 * value. Moreover, the sum of the util_avgs may be divergent, such
1035 * as when the series is a harmonic series.
1037 * To solve this problem, we also cap the util_avg of successive tasks to
1038 * only 1/2 of the left utilization budget:
1040 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1042 * where n denotes the nth task and cpu_scale the CPU capacity.
1044 * For example, for a CPU with 1024 of capacity, a simplest series from
1045 * the beginning would be like:
1047 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1048 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1050 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1051 * if util_avg > util_avg_cap.
1053 void post_init_entity_util_avg(struct task_struct *p)
1055 struct sched_entity *se = &p->se;
1056 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1057 struct sched_avg *sa = &se->avg;
1058 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1059 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1061 if (p->sched_class != &fair_sched_class) {
1063 * For !fair tasks do:
1065 update_cfs_rq_load_avg(now, cfs_rq);
1066 attach_entity_load_avg(cfs_rq, se);
1067 switched_from_fair(rq, p);
1069 * such that the next switched_to_fair() has the
1072 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1077 if (cfs_rq->avg.util_avg != 0) {
1078 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
1079 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1081 if (sa->util_avg > cap)
1088 sa->runnable_avg = sa->util_avg;
1091 #else /* !CONFIG_SMP */
1092 void init_entity_runnable_average(struct sched_entity *se)
1095 void post_init_entity_util_avg(struct task_struct *p)
1098 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1101 #endif /* CONFIG_SMP */
1104 * Update the current task's runtime statistics.
1106 static void update_curr(struct cfs_rq *cfs_rq)
1108 struct sched_entity *curr = cfs_rq->curr;
1109 u64 now = rq_clock_task(rq_of(cfs_rq));
1112 if (unlikely(!curr))
1115 delta_exec = now - curr->exec_start;
1116 if (unlikely((s64)delta_exec <= 0))
1119 curr->exec_start = now;
1121 if (schedstat_enabled()) {
1122 struct sched_statistics *stats;
1124 stats = __schedstats_from_se(curr);
1125 __schedstat_set(stats->exec_max,
1126 max(delta_exec, stats->exec_max));
1129 curr->sum_exec_runtime += delta_exec;
1130 schedstat_add(cfs_rq->exec_clock, delta_exec);
1132 curr->vruntime += calc_delta_fair(delta_exec, curr);
1133 update_deadline(cfs_rq, curr);
1134 update_min_vruntime(cfs_rq);
1136 if (entity_is_task(curr)) {
1137 struct task_struct *curtask = task_of(curr);
1139 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1140 cgroup_account_cputime(curtask, delta_exec);
1141 account_group_exec_runtime(curtask, delta_exec);
1144 account_cfs_rq_runtime(cfs_rq, delta_exec);
1147 static void update_curr_fair(struct rq *rq)
1149 update_curr(cfs_rq_of(&rq->curr->se));
1153 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1155 struct sched_statistics *stats;
1156 struct task_struct *p = NULL;
1158 if (!schedstat_enabled())
1161 stats = __schedstats_from_se(se);
1163 if (entity_is_task(se))
1166 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1170 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1172 struct sched_statistics *stats;
1173 struct task_struct *p = NULL;
1175 if (!schedstat_enabled())
1178 stats = __schedstats_from_se(se);
1181 * When the sched_schedstat changes from 0 to 1, some sched se
1182 * maybe already in the runqueue, the se->statistics.wait_start
1183 * will be 0.So it will let the delta wrong. We need to avoid this
1186 if (unlikely(!schedstat_val(stats->wait_start)))
1189 if (entity_is_task(se))
1192 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1196 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1198 struct sched_statistics *stats;
1199 struct task_struct *tsk = NULL;
1201 if (!schedstat_enabled())
1204 stats = __schedstats_from_se(se);
1206 if (entity_is_task(se))
1209 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1213 * Task is being enqueued - update stats:
1216 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1218 if (!schedstat_enabled())
1222 * Are we enqueueing a waiting task? (for current tasks
1223 * a dequeue/enqueue event is a NOP)
1225 if (se != cfs_rq->curr)
1226 update_stats_wait_start_fair(cfs_rq, se);
1228 if (flags & ENQUEUE_WAKEUP)
1229 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1233 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1236 if (!schedstat_enabled())
1240 * Mark the end of the wait period if dequeueing a
1243 if (se != cfs_rq->curr)
1244 update_stats_wait_end_fair(cfs_rq, se);
1246 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1247 struct task_struct *tsk = task_of(se);
1250 /* XXX racy against TTWU */
1251 state = READ_ONCE(tsk->__state);
1252 if (state & TASK_INTERRUPTIBLE)
1253 __schedstat_set(tsk->stats.sleep_start,
1254 rq_clock(rq_of(cfs_rq)));
1255 if (state & TASK_UNINTERRUPTIBLE)
1256 __schedstat_set(tsk->stats.block_start,
1257 rq_clock(rq_of(cfs_rq)));
1262 * We are picking a new current task - update its stats:
1265 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1268 * We are starting a new run period:
1270 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1273 /**************************************************
1274 * Scheduling class queueing methods:
1277 static inline bool is_core_idle(int cpu)
1279 #ifdef CONFIG_SCHED_SMT
1282 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1286 if (!idle_cpu(sibling))
1295 #define NUMA_IMBALANCE_MIN 2
1298 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1301 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1302 * threshold. Above this threshold, individual tasks may be contending
1303 * for both memory bandwidth and any shared HT resources. This is an
1304 * approximation as the number of running tasks may not be related to
1305 * the number of busy CPUs due to sched_setaffinity.
1307 if (dst_running > imb_numa_nr)
1311 * Allow a small imbalance based on a simple pair of communicating
1312 * tasks that remain local when the destination is lightly loaded.
1314 if (imbalance <= NUMA_IMBALANCE_MIN)
1319 #endif /* CONFIG_NUMA */
1321 #ifdef CONFIG_NUMA_BALANCING
1323 * Approximate time to scan a full NUMA task in ms. The task scan period is
1324 * calculated based on the tasks virtual memory size and
1325 * numa_balancing_scan_size.
1327 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1328 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1330 /* Portion of address space to scan in MB */
1331 unsigned int sysctl_numa_balancing_scan_size = 256;
1333 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1334 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1336 /* The page with hint page fault latency < threshold in ms is considered hot */
1337 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1340 refcount_t refcount;
1342 spinlock_t lock; /* nr_tasks, tasks */
1347 struct rcu_head rcu;
1348 unsigned long total_faults;
1349 unsigned long max_faults_cpu;
1351 * faults[] array is split into two regions: faults_mem and faults_cpu.
1353 * Faults_cpu is used to decide whether memory should move
1354 * towards the CPU. As a consequence, these stats are weighted
1355 * more by CPU use than by memory faults.
1357 unsigned long faults[];
1361 * For functions that can be called in multiple contexts that permit reading
1362 * ->numa_group (see struct task_struct for locking rules).
1364 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1366 return rcu_dereference_check(p->numa_group, p == current ||
1367 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1370 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1372 return rcu_dereference_protected(p->numa_group, p == current);
1375 static inline unsigned long group_faults_priv(struct numa_group *ng);
1376 static inline unsigned long group_faults_shared(struct numa_group *ng);
1378 static unsigned int task_nr_scan_windows(struct task_struct *p)
1380 unsigned long rss = 0;
1381 unsigned long nr_scan_pages;
1384 * Calculations based on RSS as non-present and empty pages are skipped
1385 * by the PTE scanner and NUMA hinting faults should be trapped based
1388 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1389 rss = get_mm_rss(p->mm);
1391 rss = nr_scan_pages;
1393 rss = round_up(rss, nr_scan_pages);
1394 return rss / nr_scan_pages;
1397 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1398 #define MAX_SCAN_WINDOW 2560
1400 static unsigned int task_scan_min(struct task_struct *p)
1402 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1403 unsigned int scan, floor;
1404 unsigned int windows = 1;
1406 if (scan_size < MAX_SCAN_WINDOW)
1407 windows = MAX_SCAN_WINDOW / scan_size;
1408 floor = 1000 / windows;
1410 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1411 return max_t(unsigned int, floor, scan);
1414 static unsigned int task_scan_start(struct task_struct *p)
1416 unsigned long smin = task_scan_min(p);
1417 unsigned long period = smin;
1418 struct numa_group *ng;
1420 /* Scale the maximum scan period with the amount of shared memory. */
1422 ng = rcu_dereference(p->numa_group);
1424 unsigned long shared = group_faults_shared(ng);
1425 unsigned long private = group_faults_priv(ng);
1427 period *= refcount_read(&ng->refcount);
1428 period *= shared + 1;
1429 period /= private + shared + 1;
1433 return max(smin, period);
1436 static unsigned int task_scan_max(struct task_struct *p)
1438 unsigned long smin = task_scan_min(p);
1440 struct numa_group *ng;
1442 /* Watch for min being lower than max due to floor calculations */
1443 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1445 /* Scale the maximum scan period with the amount of shared memory. */
1446 ng = deref_curr_numa_group(p);
1448 unsigned long shared = group_faults_shared(ng);
1449 unsigned long private = group_faults_priv(ng);
1450 unsigned long period = smax;
1452 period *= refcount_read(&ng->refcount);
1453 period *= shared + 1;
1454 period /= private + shared + 1;
1456 smax = max(smax, period);
1459 return max(smin, smax);
1462 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1464 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1465 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1468 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1470 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1471 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1474 /* Shared or private faults. */
1475 #define NR_NUMA_HINT_FAULT_TYPES 2
1477 /* Memory and CPU locality */
1478 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1480 /* Averaged statistics, and temporary buffers. */
1481 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1483 pid_t task_numa_group_id(struct task_struct *p)
1485 struct numa_group *ng;
1489 ng = rcu_dereference(p->numa_group);
1498 * The averaged statistics, shared & private, memory & CPU,
1499 * occupy the first half of the array. The second half of the
1500 * array is for current counters, which are averaged into the
1501 * first set by task_numa_placement.
1503 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1505 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1508 static inline unsigned long task_faults(struct task_struct *p, int nid)
1510 if (!p->numa_faults)
1513 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1514 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1517 static inline unsigned long group_faults(struct task_struct *p, int nid)
1519 struct numa_group *ng = deref_task_numa_group(p);
1524 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1525 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1528 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1530 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1531 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1534 static inline unsigned long group_faults_priv(struct numa_group *ng)
1536 unsigned long faults = 0;
1539 for_each_online_node(node) {
1540 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1546 static inline unsigned long group_faults_shared(struct numa_group *ng)
1548 unsigned long faults = 0;
1551 for_each_online_node(node) {
1552 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1559 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1560 * considered part of a numa group's pseudo-interleaving set. Migrations
1561 * between these nodes are slowed down, to allow things to settle down.
1563 #define ACTIVE_NODE_FRACTION 3
1565 static bool numa_is_active_node(int nid, struct numa_group *ng)
1567 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1570 /* Handle placement on systems where not all nodes are directly connected. */
1571 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1572 int lim_dist, bool task)
1574 unsigned long score = 0;
1578 * All nodes are directly connected, and the same distance
1579 * from each other. No need for fancy placement algorithms.
1581 if (sched_numa_topology_type == NUMA_DIRECT)
1584 /* sched_max_numa_distance may be changed in parallel. */
1585 max_dist = READ_ONCE(sched_max_numa_distance);
1587 * This code is called for each node, introducing N^2 complexity,
1588 * which should be ok given the number of nodes rarely exceeds 8.
1590 for_each_online_node(node) {
1591 unsigned long faults;
1592 int dist = node_distance(nid, node);
1595 * The furthest away nodes in the system are not interesting
1596 * for placement; nid was already counted.
1598 if (dist >= max_dist || node == nid)
1602 * On systems with a backplane NUMA topology, compare groups
1603 * of nodes, and move tasks towards the group with the most
1604 * memory accesses. When comparing two nodes at distance
1605 * "hoplimit", only nodes closer by than "hoplimit" are part
1606 * of each group. Skip other nodes.
1608 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1611 /* Add up the faults from nearby nodes. */
1613 faults = task_faults(p, node);
1615 faults = group_faults(p, node);
1618 * On systems with a glueless mesh NUMA topology, there are
1619 * no fixed "groups of nodes". Instead, nodes that are not
1620 * directly connected bounce traffic through intermediate
1621 * nodes; a numa_group can occupy any set of nodes.
1622 * The further away a node is, the less the faults count.
1623 * This seems to result in good task placement.
1625 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1626 faults *= (max_dist - dist);
1627 faults /= (max_dist - LOCAL_DISTANCE);
1637 * These return the fraction of accesses done by a particular task, or
1638 * task group, on a particular numa node. The group weight is given a
1639 * larger multiplier, in order to group tasks together that are almost
1640 * evenly spread out between numa nodes.
1642 static inline unsigned long task_weight(struct task_struct *p, int nid,
1645 unsigned long faults, total_faults;
1647 if (!p->numa_faults)
1650 total_faults = p->total_numa_faults;
1655 faults = task_faults(p, nid);
1656 faults += score_nearby_nodes(p, nid, dist, true);
1658 return 1000 * faults / total_faults;
1661 static inline unsigned long group_weight(struct task_struct *p, int nid,
1664 struct numa_group *ng = deref_task_numa_group(p);
1665 unsigned long faults, total_faults;
1670 total_faults = ng->total_faults;
1675 faults = group_faults(p, nid);
1676 faults += score_nearby_nodes(p, nid, dist, false);
1678 return 1000 * faults / total_faults;
1682 * If memory tiering mode is enabled, cpupid of slow memory page is
1683 * used to record scan time instead of CPU and PID. When tiering mode
1684 * is disabled at run time, the scan time (in cpupid) will be
1685 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1686 * access out of array bound.
1688 static inline bool cpupid_valid(int cpupid)
1690 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1694 * For memory tiering mode, if there are enough free pages (more than
1695 * enough watermark defined here) in fast memory node, to take full
1696 * advantage of fast memory capacity, all recently accessed slow
1697 * memory pages will be migrated to fast memory node without
1698 * considering hot threshold.
1700 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1703 unsigned long enough_wmark;
1705 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1706 pgdat->node_present_pages >> 4);
1707 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1708 struct zone *zone = pgdat->node_zones + z;
1710 if (!populated_zone(zone))
1713 if (zone_watermark_ok(zone, 0,
1714 wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1722 * For memory tiering mode, when page tables are scanned, the scan
1723 * time will be recorded in struct page in addition to make page
1724 * PROT_NONE for slow memory page. So when the page is accessed, in
1725 * hint page fault handler, the hint page fault latency is calculated
1728 * hint page fault latency = hint page fault time - scan time
1730 * The smaller the hint page fault latency, the higher the possibility
1731 * for the page to be hot.
1733 static int numa_hint_fault_latency(struct page *page)
1735 int last_time, time;
1737 time = jiffies_to_msecs(jiffies);
1738 last_time = xchg_page_access_time(page, time);
1740 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1744 * For memory tiering mode, too high promotion/demotion throughput may
1745 * hurt application latency. So we provide a mechanism to rate limit
1746 * the number of pages that are tried to be promoted.
1748 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1749 unsigned long rate_limit, int nr)
1751 unsigned long nr_cand;
1752 unsigned int now, start;
1754 now = jiffies_to_msecs(jiffies);
1755 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1756 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1757 start = pgdat->nbp_rl_start;
1758 if (now - start > MSEC_PER_SEC &&
1759 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1760 pgdat->nbp_rl_nr_cand = nr_cand;
1761 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1766 #define NUMA_MIGRATION_ADJUST_STEPS 16
1768 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1769 unsigned long rate_limit,
1770 unsigned int ref_th)
1772 unsigned int now, start, th_period, unit_th, th;
1773 unsigned long nr_cand, ref_cand, diff_cand;
1775 now = jiffies_to_msecs(jiffies);
1776 th_period = sysctl_numa_balancing_scan_period_max;
1777 start = pgdat->nbp_th_start;
1778 if (now - start > th_period &&
1779 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1780 ref_cand = rate_limit *
1781 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1782 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1783 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1784 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1785 th = pgdat->nbp_threshold ? : ref_th;
1786 if (diff_cand > ref_cand * 11 / 10)
1787 th = max(th - unit_th, unit_th);
1788 else if (diff_cand < ref_cand * 9 / 10)
1789 th = min(th + unit_th, ref_th * 2);
1790 pgdat->nbp_th_nr_cand = nr_cand;
1791 pgdat->nbp_threshold = th;
1795 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1796 int src_nid, int dst_cpu)
1798 struct numa_group *ng = deref_curr_numa_group(p);
1799 int dst_nid = cpu_to_node(dst_cpu);
1800 int last_cpupid, this_cpupid;
1803 * The pages in slow memory node should be migrated according
1804 * to hot/cold instead of private/shared.
1806 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1807 !node_is_toptier(src_nid)) {
1808 struct pglist_data *pgdat;
1809 unsigned long rate_limit;
1810 unsigned int latency, th, def_th;
1812 pgdat = NODE_DATA(dst_nid);
1813 if (pgdat_free_space_enough(pgdat)) {
1814 /* workload changed, reset hot threshold */
1815 pgdat->nbp_threshold = 0;
1819 def_th = sysctl_numa_balancing_hot_threshold;
1820 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1822 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1824 th = pgdat->nbp_threshold ? : def_th;
1825 latency = numa_hint_fault_latency(page);
1829 return !numa_promotion_rate_limit(pgdat, rate_limit,
1830 thp_nr_pages(page));
1833 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1834 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1836 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1837 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1841 * Allow first faults or private faults to migrate immediately early in
1842 * the lifetime of a task. The magic number 4 is based on waiting for
1843 * two full passes of the "multi-stage node selection" test that is
1846 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1847 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1851 * Multi-stage node selection is used in conjunction with a periodic
1852 * migration fault to build a temporal task<->page relation. By using
1853 * a two-stage filter we remove short/unlikely relations.
1855 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1856 * a task's usage of a particular page (n_p) per total usage of this
1857 * page (n_t) (in a given time-span) to a probability.
1859 * Our periodic faults will sample this probability and getting the
1860 * same result twice in a row, given these samples are fully
1861 * independent, is then given by P(n)^2, provided our sample period
1862 * is sufficiently short compared to the usage pattern.
1864 * This quadric squishes small probabilities, making it less likely we
1865 * act on an unlikely task<->page relation.
1867 if (!cpupid_pid_unset(last_cpupid) &&
1868 cpupid_to_nid(last_cpupid) != dst_nid)
1871 /* Always allow migrate on private faults */
1872 if (cpupid_match_pid(p, last_cpupid))
1875 /* A shared fault, but p->numa_group has not been set up yet. */
1880 * Destination node is much more heavily used than the source
1881 * node? Allow migration.
1883 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1884 ACTIVE_NODE_FRACTION)
1888 * Distribute memory according to CPU & memory use on each node,
1889 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1891 * faults_cpu(dst) 3 faults_cpu(src)
1892 * --------------- * - > ---------------
1893 * faults_mem(dst) 4 faults_mem(src)
1895 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1896 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1900 * 'numa_type' describes the node at the moment of load balancing.
1903 /* The node has spare capacity that can be used to run more tasks. */
1906 * The node is fully used and the tasks don't compete for more CPU
1907 * cycles. Nevertheless, some tasks might wait before running.
1911 * The node is overloaded and can't provide expected CPU cycles to all
1917 /* Cached statistics for all CPUs within a node */
1920 unsigned long runnable;
1922 /* Total compute capacity of CPUs on a node */
1923 unsigned long compute_capacity;
1924 unsigned int nr_running;
1925 unsigned int weight;
1926 enum numa_type node_type;
1930 struct task_numa_env {
1931 struct task_struct *p;
1933 int src_cpu, src_nid;
1934 int dst_cpu, dst_nid;
1937 struct numa_stats src_stats, dst_stats;
1942 struct task_struct *best_task;
1947 static unsigned long cpu_load(struct rq *rq);
1948 static unsigned long cpu_runnable(struct rq *rq);
1951 numa_type numa_classify(unsigned int imbalance_pct,
1952 struct numa_stats *ns)
1954 if ((ns->nr_running > ns->weight) &&
1955 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
1956 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
1957 return node_overloaded;
1959 if ((ns->nr_running < ns->weight) ||
1960 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
1961 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
1962 return node_has_spare;
1964 return node_fully_busy;
1967 #ifdef CONFIG_SCHED_SMT
1968 /* Forward declarations of select_idle_sibling helpers */
1969 static inline bool test_idle_cores(int cpu);
1970 static inline int numa_idle_core(int idle_core, int cpu)
1972 if (!static_branch_likely(&sched_smt_present) ||
1973 idle_core >= 0 || !test_idle_cores(cpu))
1977 * Prefer cores instead of packing HT siblings
1978 * and triggering future load balancing.
1980 if (is_core_idle(cpu))
1986 static inline int numa_idle_core(int idle_core, int cpu)
1993 * Gather all necessary information to make NUMA balancing placement
1994 * decisions that are compatible with standard load balancer. This
1995 * borrows code and logic from update_sg_lb_stats but sharing a
1996 * common implementation is impractical.
1998 static void update_numa_stats(struct task_numa_env *env,
1999 struct numa_stats *ns, int nid,
2002 int cpu, idle_core = -1;
2004 memset(ns, 0, sizeof(*ns));
2008 for_each_cpu(cpu, cpumask_of_node(nid)) {
2009 struct rq *rq = cpu_rq(cpu);
2011 ns->load += cpu_load(rq);
2012 ns->runnable += cpu_runnable(rq);
2013 ns->util += cpu_util_cfs(cpu);
2014 ns->nr_running += rq->cfs.h_nr_running;
2015 ns->compute_capacity += capacity_of(cpu);
2017 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2018 if (READ_ONCE(rq->numa_migrate_on) ||
2019 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2022 if (ns->idle_cpu == -1)
2025 idle_core = numa_idle_core(idle_core, cpu);
2030 ns->weight = cpumask_weight(cpumask_of_node(nid));
2032 ns->node_type = numa_classify(env->imbalance_pct, ns);
2035 ns->idle_cpu = idle_core;
2038 static void task_numa_assign(struct task_numa_env *env,
2039 struct task_struct *p, long imp)
2041 struct rq *rq = cpu_rq(env->dst_cpu);
2043 /* Check if run-queue part of active NUMA balance. */
2044 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2046 int start = env->dst_cpu;
2048 /* Find alternative idle CPU. */
2049 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2050 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2051 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2056 rq = cpu_rq(env->dst_cpu);
2057 if (!xchg(&rq->numa_migrate_on, 1))
2061 /* Failed to find an alternative idle CPU */
2067 * Clear previous best_cpu/rq numa-migrate flag, since task now
2068 * found a better CPU to move/swap.
2070 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2071 rq = cpu_rq(env->best_cpu);
2072 WRITE_ONCE(rq->numa_migrate_on, 0);
2076 put_task_struct(env->best_task);
2081 env->best_imp = imp;
2082 env->best_cpu = env->dst_cpu;
2085 static bool load_too_imbalanced(long src_load, long dst_load,
2086 struct task_numa_env *env)
2089 long orig_src_load, orig_dst_load;
2090 long src_capacity, dst_capacity;
2093 * The load is corrected for the CPU capacity available on each node.
2096 * ------------ vs ---------
2097 * src_capacity dst_capacity
2099 src_capacity = env->src_stats.compute_capacity;
2100 dst_capacity = env->dst_stats.compute_capacity;
2102 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2104 orig_src_load = env->src_stats.load;
2105 orig_dst_load = env->dst_stats.load;
2107 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2109 /* Would this change make things worse? */
2110 return (imb > old_imb);
2114 * Maximum NUMA importance can be 1998 (2*999);
2115 * SMALLIMP @ 30 would be close to 1998/64.
2116 * Used to deter task migration.
2121 * This checks if the overall compute and NUMA accesses of the system would
2122 * be improved if the source tasks was migrated to the target dst_cpu taking
2123 * into account that it might be best if task running on the dst_cpu should
2124 * be exchanged with the source task
2126 static bool task_numa_compare(struct task_numa_env *env,
2127 long taskimp, long groupimp, bool maymove)
2129 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2130 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2131 long imp = p_ng ? groupimp : taskimp;
2132 struct task_struct *cur;
2133 long src_load, dst_load;
2134 int dist = env->dist;
2137 bool stopsearch = false;
2139 if (READ_ONCE(dst_rq->numa_migrate_on))
2143 cur = rcu_dereference(dst_rq->curr);
2144 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2148 * Because we have preemption enabled we can get migrated around and
2149 * end try selecting ourselves (current == env->p) as a swap candidate.
2151 if (cur == env->p) {
2157 if (maymove && moveimp >= env->best_imp)
2163 /* Skip this swap candidate if cannot move to the source cpu. */
2164 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2168 * Skip this swap candidate if it is not moving to its preferred
2169 * node and the best task is.
2171 if (env->best_task &&
2172 env->best_task->numa_preferred_nid == env->src_nid &&
2173 cur->numa_preferred_nid != env->src_nid) {
2178 * "imp" is the fault differential for the source task between the
2179 * source and destination node. Calculate the total differential for
2180 * the source task and potential destination task. The more negative
2181 * the value is, the more remote accesses that would be expected to
2182 * be incurred if the tasks were swapped.
2184 * If dst and source tasks are in the same NUMA group, or not
2185 * in any group then look only at task weights.
2187 cur_ng = rcu_dereference(cur->numa_group);
2188 if (cur_ng == p_ng) {
2190 * Do not swap within a group or between tasks that have
2191 * no group if there is spare capacity. Swapping does
2192 * not address the load imbalance and helps one task at
2193 * the cost of punishing another.
2195 if (env->dst_stats.node_type == node_has_spare)
2198 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2199 task_weight(cur, env->dst_nid, dist);
2201 * Add some hysteresis to prevent swapping the
2202 * tasks within a group over tiny differences.
2208 * Compare the group weights. If a task is all by itself
2209 * (not part of a group), use the task weight instead.
2212 imp += group_weight(cur, env->src_nid, dist) -
2213 group_weight(cur, env->dst_nid, dist);
2215 imp += task_weight(cur, env->src_nid, dist) -
2216 task_weight(cur, env->dst_nid, dist);
2219 /* Discourage picking a task already on its preferred node */
2220 if (cur->numa_preferred_nid == env->dst_nid)
2224 * Encourage picking a task that moves to its preferred node.
2225 * This potentially makes imp larger than it's maximum of
2226 * 1998 (see SMALLIMP and task_weight for why) but in this
2227 * case, it does not matter.
2229 if (cur->numa_preferred_nid == env->src_nid)
2232 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2239 * Prefer swapping with a task moving to its preferred node over a
2242 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2243 env->best_task->numa_preferred_nid != env->src_nid) {
2248 * If the NUMA importance is less than SMALLIMP,
2249 * task migration might only result in ping pong
2250 * of tasks and also hurt performance due to cache
2253 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2257 * In the overloaded case, try and keep the load balanced.
2259 load = task_h_load(env->p) - task_h_load(cur);
2263 dst_load = env->dst_stats.load + load;
2264 src_load = env->src_stats.load - load;
2266 if (load_too_imbalanced(src_load, dst_load, env))
2270 /* Evaluate an idle CPU for a task numa move. */
2272 int cpu = env->dst_stats.idle_cpu;
2274 /* Nothing cached so current CPU went idle since the search. */
2279 * If the CPU is no longer truly idle and the previous best CPU
2280 * is, keep using it.
2282 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2283 idle_cpu(env->best_cpu)) {
2284 cpu = env->best_cpu;
2290 task_numa_assign(env, cur, imp);
2293 * If a move to idle is allowed because there is capacity or load
2294 * balance improves then stop the search. While a better swap
2295 * candidate may exist, a search is not free.
2297 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2301 * If a swap candidate must be identified and the current best task
2302 * moves its preferred node then stop the search.
2304 if (!maymove && env->best_task &&
2305 env->best_task->numa_preferred_nid == env->src_nid) {
2314 static void task_numa_find_cpu(struct task_numa_env *env,
2315 long taskimp, long groupimp)
2317 bool maymove = false;
2321 * If dst node has spare capacity, then check if there is an
2322 * imbalance that would be overruled by the load balancer.
2324 if (env->dst_stats.node_type == node_has_spare) {
2325 unsigned int imbalance;
2326 int src_running, dst_running;
2329 * Would movement cause an imbalance? Note that if src has
2330 * more running tasks that the imbalance is ignored as the
2331 * move improves the imbalance from the perspective of the
2332 * CPU load balancer.
2334 src_running = env->src_stats.nr_running - 1;
2335 dst_running = env->dst_stats.nr_running + 1;
2336 imbalance = max(0, dst_running - src_running);
2337 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2340 /* Use idle CPU if there is no imbalance */
2343 if (env->dst_stats.idle_cpu >= 0) {
2344 env->dst_cpu = env->dst_stats.idle_cpu;
2345 task_numa_assign(env, NULL, 0);
2350 long src_load, dst_load, load;
2352 * If the improvement from just moving env->p direction is better
2353 * than swapping tasks around, check if a move is possible.
2355 load = task_h_load(env->p);
2356 dst_load = env->dst_stats.load + load;
2357 src_load = env->src_stats.load - load;
2358 maymove = !load_too_imbalanced(src_load, dst_load, env);
2361 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2362 /* Skip this CPU if the source task cannot migrate */
2363 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2367 if (task_numa_compare(env, taskimp, groupimp, maymove))
2372 static int task_numa_migrate(struct task_struct *p)
2374 struct task_numa_env env = {
2377 .src_cpu = task_cpu(p),
2378 .src_nid = task_node(p),
2380 .imbalance_pct = 112,
2386 unsigned long taskweight, groupweight;
2387 struct sched_domain *sd;
2388 long taskimp, groupimp;
2389 struct numa_group *ng;
2394 * Pick the lowest SD_NUMA domain, as that would have the smallest
2395 * imbalance and would be the first to start moving tasks about.
2397 * And we want to avoid any moving of tasks about, as that would create
2398 * random movement of tasks -- counter the numa conditions we're trying
2402 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2404 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2405 env.imb_numa_nr = sd->imb_numa_nr;
2410 * Cpusets can break the scheduler domain tree into smaller
2411 * balance domains, some of which do not cross NUMA boundaries.
2412 * Tasks that are "trapped" in such domains cannot be migrated
2413 * elsewhere, so there is no point in (re)trying.
2415 if (unlikely(!sd)) {
2416 sched_setnuma(p, task_node(p));
2420 env.dst_nid = p->numa_preferred_nid;
2421 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2422 taskweight = task_weight(p, env.src_nid, dist);
2423 groupweight = group_weight(p, env.src_nid, dist);
2424 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2425 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2426 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2427 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2429 /* Try to find a spot on the preferred nid. */
2430 task_numa_find_cpu(&env, taskimp, groupimp);
2433 * Look at other nodes in these cases:
2434 * - there is no space available on the preferred_nid
2435 * - the task is part of a numa_group that is interleaved across
2436 * multiple NUMA nodes; in order to better consolidate the group,
2437 * we need to check other locations.
2439 ng = deref_curr_numa_group(p);
2440 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2441 for_each_node_state(nid, N_CPU) {
2442 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2445 dist = node_distance(env.src_nid, env.dst_nid);
2446 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2448 taskweight = task_weight(p, env.src_nid, dist);
2449 groupweight = group_weight(p, env.src_nid, dist);
2452 /* Only consider nodes where both task and groups benefit */
2453 taskimp = task_weight(p, nid, dist) - taskweight;
2454 groupimp = group_weight(p, nid, dist) - groupweight;
2455 if (taskimp < 0 && groupimp < 0)
2460 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2461 task_numa_find_cpu(&env, taskimp, groupimp);
2466 * If the task is part of a workload that spans multiple NUMA nodes,
2467 * and is migrating into one of the workload's active nodes, remember
2468 * this node as the task's preferred numa node, so the workload can
2470 * A task that migrated to a second choice node will be better off
2471 * trying for a better one later. Do not set the preferred node here.
2474 if (env.best_cpu == -1)
2477 nid = cpu_to_node(env.best_cpu);
2479 if (nid != p->numa_preferred_nid)
2480 sched_setnuma(p, nid);
2483 /* No better CPU than the current one was found. */
2484 if (env.best_cpu == -1) {
2485 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2489 best_rq = cpu_rq(env.best_cpu);
2490 if (env.best_task == NULL) {
2491 ret = migrate_task_to(p, env.best_cpu);
2492 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2494 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2498 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2499 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2502 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2503 put_task_struct(env.best_task);
2507 /* Attempt to migrate a task to a CPU on the preferred node. */
2508 static void numa_migrate_preferred(struct task_struct *p)
2510 unsigned long interval = HZ;
2512 /* This task has no NUMA fault statistics yet */
2513 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2516 /* Periodically retry migrating the task to the preferred node */
2517 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2518 p->numa_migrate_retry = jiffies + interval;
2520 /* Success if task is already running on preferred CPU */
2521 if (task_node(p) == p->numa_preferred_nid)
2524 /* Otherwise, try migrate to a CPU on the preferred node */
2525 task_numa_migrate(p);
2529 * Find out how many nodes the workload is actively running on. Do this by
2530 * tracking the nodes from which NUMA hinting faults are triggered. This can
2531 * be different from the set of nodes where the workload's memory is currently
2534 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2536 unsigned long faults, max_faults = 0;
2537 int nid, active_nodes = 0;
2539 for_each_node_state(nid, N_CPU) {
2540 faults = group_faults_cpu(numa_group, nid);
2541 if (faults > max_faults)
2542 max_faults = faults;
2545 for_each_node_state(nid, N_CPU) {
2546 faults = group_faults_cpu(numa_group, nid);
2547 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2551 numa_group->max_faults_cpu = max_faults;
2552 numa_group->active_nodes = active_nodes;
2556 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2557 * increments. The more local the fault statistics are, the higher the scan
2558 * period will be for the next scan window. If local/(local+remote) ratio is
2559 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2560 * the scan period will decrease. Aim for 70% local accesses.
2562 #define NUMA_PERIOD_SLOTS 10
2563 #define NUMA_PERIOD_THRESHOLD 7
2566 * Increase the scan period (slow down scanning) if the majority of
2567 * our memory is already on our local node, or if the majority of
2568 * the page accesses are shared with other processes.
2569 * Otherwise, decrease the scan period.
2571 static void update_task_scan_period(struct task_struct *p,
2572 unsigned long shared, unsigned long private)
2574 unsigned int period_slot;
2575 int lr_ratio, ps_ratio;
2578 unsigned long remote = p->numa_faults_locality[0];
2579 unsigned long local = p->numa_faults_locality[1];
2582 * If there were no record hinting faults then either the task is
2583 * completely idle or all activity is in areas that are not of interest
2584 * to automatic numa balancing. Related to that, if there were failed
2585 * migration then it implies we are migrating too quickly or the local
2586 * node is overloaded. In either case, scan slower
2588 if (local + shared == 0 || p->numa_faults_locality[2]) {
2589 p->numa_scan_period = min(p->numa_scan_period_max,
2590 p->numa_scan_period << 1);
2592 p->mm->numa_next_scan = jiffies +
2593 msecs_to_jiffies(p->numa_scan_period);
2599 * Prepare to scale scan period relative to the current period.
2600 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2601 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2602 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2604 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2605 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2606 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2608 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2610 * Most memory accesses are local. There is no need to
2611 * do fast NUMA scanning, since memory is already local.
2613 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2616 diff = slot * period_slot;
2617 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2619 * Most memory accesses are shared with other tasks.
2620 * There is no point in continuing fast NUMA scanning,
2621 * since other tasks may just move the memory elsewhere.
2623 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2626 diff = slot * period_slot;
2629 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2630 * yet they are not on the local NUMA node. Speed up
2631 * NUMA scanning to get the memory moved over.
2633 int ratio = max(lr_ratio, ps_ratio);
2634 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2637 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2638 task_scan_min(p), task_scan_max(p));
2639 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2643 * Get the fraction of time the task has been running since the last
2644 * NUMA placement cycle. The scheduler keeps similar statistics, but
2645 * decays those on a 32ms period, which is orders of magnitude off
2646 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2647 * stats only if the task is so new there are no NUMA statistics yet.
2649 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2651 u64 runtime, delta, now;
2652 /* Use the start of this time slice to avoid calculations. */
2653 now = p->se.exec_start;
2654 runtime = p->se.sum_exec_runtime;
2656 if (p->last_task_numa_placement) {
2657 delta = runtime - p->last_sum_exec_runtime;
2658 *period = now - p->last_task_numa_placement;
2660 /* Avoid time going backwards, prevent potential divide error: */
2661 if (unlikely((s64)*period < 0))
2664 delta = p->se.avg.load_sum;
2665 *period = LOAD_AVG_MAX;
2668 p->last_sum_exec_runtime = runtime;
2669 p->last_task_numa_placement = now;
2675 * Determine the preferred nid for a task in a numa_group. This needs to
2676 * be done in a way that produces consistent results with group_weight,
2677 * otherwise workloads might not converge.
2679 static int preferred_group_nid(struct task_struct *p, int nid)
2684 /* Direct connections between all NUMA nodes. */
2685 if (sched_numa_topology_type == NUMA_DIRECT)
2689 * On a system with glueless mesh NUMA topology, group_weight
2690 * scores nodes according to the number of NUMA hinting faults on
2691 * both the node itself, and on nearby nodes.
2693 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2694 unsigned long score, max_score = 0;
2695 int node, max_node = nid;
2697 dist = sched_max_numa_distance;
2699 for_each_node_state(node, N_CPU) {
2700 score = group_weight(p, node, dist);
2701 if (score > max_score) {
2710 * Finding the preferred nid in a system with NUMA backplane
2711 * interconnect topology is more involved. The goal is to locate
2712 * tasks from numa_groups near each other in the system, and
2713 * untangle workloads from different sides of the system. This requires
2714 * searching down the hierarchy of node groups, recursively searching
2715 * inside the highest scoring group of nodes. The nodemask tricks
2716 * keep the complexity of the search down.
2718 nodes = node_states[N_CPU];
2719 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2720 unsigned long max_faults = 0;
2721 nodemask_t max_group = NODE_MASK_NONE;
2724 /* Are there nodes at this distance from each other? */
2725 if (!find_numa_distance(dist))
2728 for_each_node_mask(a, nodes) {
2729 unsigned long faults = 0;
2730 nodemask_t this_group;
2731 nodes_clear(this_group);
2733 /* Sum group's NUMA faults; includes a==b case. */
2734 for_each_node_mask(b, nodes) {
2735 if (node_distance(a, b) < dist) {
2736 faults += group_faults(p, b);
2737 node_set(b, this_group);
2738 node_clear(b, nodes);
2742 /* Remember the top group. */
2743 if (faults > max_faults) {
2744 max_faults = faults;
2745 max_group = this_group;
2747 * subtle: at the smallest distance there is
2748 * just one node left in each "group", the
2749 * winner is the preferred nid.
2754 /* Next round, evaluate the nodes within max_group. */
2762 static void task_numa_placement(struct task_struct *p)
2764 int seq, nid, max_nid = NUMA_NO_NODE;
2765 unsigned long max_faults = 0;
2766 unsigned long fault_types[2] = { 0, 0 };
2767 unsigned long total_faults;
2768 u64 runtime, period;
2769 spinlock_t *group_lock = NULL;
2770 struct numa_group *ng;
2773 * The p->mm->numa_scan_seq field gets updated without
2774 * exclusive access. Use READ_ONCE() here to ensure
2775 * that the field is read in a single access:
2777 seq = READ_ONCE(p->mm->numa_scan_seq);
2778 if (p->numa_scan_seq == seq)
2780 p->numa_scan_seq = seq;
2781 p->numa_scan_period_max = task_scan_max(p);
2783 total_faults = p->numa_faults_locality[0] +
2784 p->numa_faults_locality[1];
2785 runtime = numa_get_avg_runtime(p, &period);
2787 /* If the task is part of a group prevent parallel updates to group stats */
2788 ng = deref_curr_numa_group(p);
2790 group_lock = &ng->lock;
2791 spin_lock_irq(group_lock);
2794 /* Find the node with the highest number of faults */
2795 for_each_online_node(nid) {
2796 /* Keep track of the offsets in numa_faults array */
2797 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2798 unsigned long faults = 0, group_faults = 0;
2801 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2802 long diff, f_diff, f_weight;
2804 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2805 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2806 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2807 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2809 /* Decay existing window, copy faults since last scan */
2810 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2811 fault_types[priv] += p->numa_faults[membuf_idx];
2812 p->numa_faults[membuf_idx] = 0;
2815 * Normalize the faults_from, so all tasks in a group
2816 * count according to CPU use, instead of by the raw
2817 * number of faults. Tasks with little runtime have
2818 * little over-all impact on throughput, and thus their
2819 * faults are less important.
2821 f_weight = div64_u64(runtime << 16, period + 1);
2822 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2824 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2825 p->numa_faults[cpubuf_idx] = 0;
2827 p->numa_faults[mem_idx] += diff;
2828 p->numa_faults[cpu_idx] += f_diff;
2829 faults += p->numa_faults[mem_idx];
2830 p->total_numa_faults += diff;
2833 * safe because we can only change our own group
2835 * mem_idx represents the offset for a given
2836 * nid and priv in a specific region because it
2837 * is at the beginning of the numa_faults array.
2839 ng->faults[mem_idx] += diff;
2840 ng->faults[cpu_idx] += f_diff;
2841 ng->total_faults += diff;
2842 group_faults += ng->faults[mem_idx];
2847 if (faults > max_faults) {
2848 max_faults = faults;
2851 } else if (group_faults > max_faults) {
2852 max_faults = group_faults;
2857 /* Cannot migrate task to CPU-less node */
2858 if (max_nid != NUMA_NO_NODE && !node_state(max_nid, N_CPU)) {
2859 int near_nid = max_nid;
2860 int distance, near_distance = INT_MAX;
2862 for_each_node_state(nid, N_CPU) {
2863 distance = node_distance(max_nid, nid);
2864 if (distance < near_distance) {
2866 near_distance = distance;
2873 numa_group_count_active_nodes(ng);
2874 spin_unlock_irq(group_lock);
2875 max_nid = preferred_group_nid(p, max_nid);
2879 /* Set the new preferred node */
2880 if (max_nid != p->numa_preferred_nid)
2881 sched_setnuma(p, max_nid);
2884 update_task_scan_period(p, fault_types[0], fault_types[1]);
2887 static inline int get_numa_group(struct numa_group *grp)
2889 return refcount_inc_not_zero(&grp->refcount);
2892 static inline void put_numa_group(struct numa_group *grp)
2894 if (refcount_dec_and_test(&grp->refcount))
2895 kfree_rcu(grp, rcu);
2898 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2901 struct numa_group *grp, *my_grp;
2902 struct task_struct *tsk;
2904 int cpu = cpupid_to_cpu(cpupid);
2907 if (unlikely(!deref_curr_numa_group(p))) {
2908 unsigned int size = sizeof(struct numa_group) +
2909 NR_NUMA_HINT_FAULT_STATS *
2910 nr_node_ids * sizeof(unsigned long);
2912 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2916 refcount_set(&grp->refcount, 1);
2917 grp->active_nodes = 1;
2918 grp->max_faults_cpu = 0;
2919 spin_lock_init(&grp->lock);
2922 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2923 grp->faults[i] = p->numa_faults[i];
2925 grp->total_faults = p->total_numa_faults;
2928 rcu_assign_pointer(p->numa_group, grp);
2932 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2934 if (!cpupid_match_pid(tsk, cpupid))
2937 grp = rcu_dereference(tsk->numa_group);
2941 my_grp = deref_curr_numa_group(p);
2946 * Only join the other group if its bigger; if we're the bigger group,
2947 * the other task will join us.
2949 if (my_grp->nr_tasks > grp->nr_tasks)
2953 * Tie-break on the grp address.
2955 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2958 /* Always join threads in the same process. */
2959 if (tsk->mm == current->mm)
2962 /* Simple filter to avoid false positives due to PID collisions */
2963 if (flags & TNF_SHARED)
2966 /* Update priv based on whether false sharing was detected */
2969 if (join && !get_numa_group(grp))
2977 WARN_ON_ONCE(irqs_disabled());
2978 double_lock_irq(&my_grp->lock, &grp->lock);
2980 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2981 my_grp->faults[i] -= p->numa_faults[i];
2982 grp->faults[i] += p->numa_faults[i];
2984 my_grp->total_faults -= p->total_numa_faults;
2985 grp->total_faults += p->total_numa_faults;
2990 spin_unlock(&my_grp->lock);
2991 spin_unlock_irq(&grp->lock);
2993 rcu_assign_pointer(p->numa_group, grp);
2995 put_numa_group(my_grp);
3004 * Get rid of NUMA statistics associated with a task (either current or dead).
3005 * If @final is set, the task is dead and has reached refcount zero, so we can
3006 * safely free all relevant data structures. Otherwise, there might be
3007 * concurrent reads from places like load balancing and procfs, and we should
3008 * reset the data back to default state without freeing ->numa_faults.
3010 void task_numa_free(struct task_struct *p, bool final)
3012 /* safe: p either is current or is being freed by current */
3013 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3014 unsigned long *numa_faults = p->numa_faults;
3015 unsigned long flags;
3022 spin_lock_irqsave(&grp->lock, flags);
3023 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3024 grp->faults[i] -= p->numa_faults[i];
3025 grp->total_faults -= p->total_numa_faults;
3028 spin_unlock_irqrestore(&grp->lock, flags);
3029 RCU_INIT_POINTER(p->numa_group, NULL);
3030 put_numa_group(grp);
3034 p->numa_faults = NULL;
3037 p->total_numa_faults = 0;
3038 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3044 * Got a PROT_NONE fault for a page on @node.
3046 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3048 struct task_struct *p = current;
3049 bool migrated = flags & TNF_MIGRATED;
3050 int cpu_node = task_node(current);
3051 int local = !!(flags & TNF_FAULT_LOCAL);
3052 struct numa_group *ng;
3055 if (!static_branch_likely(&sched_numa_balancing))
3058 /* for example, ksmd faulting in a user's mm */
3063 * NUMA faults statistics are unnecessary for the slow memory
3064 * node for memory tiering mode.
3066 if (!node_is_toptier(mem_node) &&
3067 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3068 !cpupid_valid(last_cpupid)))
3071 /* Allocate buffer to track faults on a per-node basis */
3072 if (unlikely(!p->numa_faults)) {
3073 int size = sizeof(*p->numa_faults) *
3074 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3076 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3077 if (!p->numa_faults)
3080 p->total_numa_faults = 0;
3081 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3085 * First accesses are treated as private, otherwise consider accesses
3086 * to be private if the accessing pid has not changed
3088 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3091 priv = cpupid_match_pid(p, last_cpupid);
3092 if (!priv && !(flags & TNF_NO_GROUP))
3093 task_numa_group(p, last_cpupid, flags, &priv);
3097 * If a workload spans multiple NUMA nodes, a shared fault that
3098 * occurs wholly within the set of nodes that the workload is
3099 * actively using should be counted as local. This allows the
3100 * scan rate to slow down when a workload has settled down.
3102 ng = deref_curr_numa_group(p);
3103 if (!priv && !local && ng && ng->active_nodes > 1 &&
3104 numa_is_active_node(cpu_node, ng) &&
3105 numa_is_active_node(mem_node, ng))
3109 * Retry to migrate task to preferred node periodically, in case it
3110 * previously failed, or the scheduler moved us.
3112 if (time_after(jiffies, p->numa_migrate_retry)) {
3113 task_numa_placement(p);
3114 numa_migrate_preferred(p);
3118 p->numa_pages_migrated += pages;
3119 if (flags & TNF_MIGRATE_FAIL)
3120 p->numa_faults_locality[2] += pages;
3122 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3123 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3124 p->numa_faults_locality[local] += pages;
3127 static void reset_ptenuma_scan(struct task_struct *p)
3130 * We only did a read acquisition of the mmap sem, so
3131 * p->mm->numa_scan_seq is written to without exclusive access
3132 * and the update is not guaranteed to be atomic. That's not
3133 * much of an issue though, since this is just used for
3134 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3135 * expensive, to avoid any form of compiler optimizations:
3137 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3138 p->mm->numa_scan_offset = 0;
3141 static bool vma_is_accessed(struct vm_area_struct *vma)
3145 * Allow unconditional access first two times, so that all the (pages)
3146 * of VMAs get prot_none fault introduced irrespective of accesses.
3147 * This is also done to avoid any side effect of task scanning
3148 * amplifying the unfairness of disjoint set of VMAs' access.
3150 if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3153 pids = vma->numab_state->access_pids[0] | vma->numab_state->access_pids[1];
3154 return test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids);
3157 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3160 * The expensive part of numa migration is done from task_work context.
3161 * Triggered from task_tick_numa().
3163 static void task_numa_work(struct callback_head *work)
3165 unsigned long migrate, next_scan, now = jiffies;
3166 struct task_struct *p = current;
3167 struct mm_struct *mm = p->mm;
3168 u64 runtime = p->se.sum_exec_runtime;
3169 struct vm_area_struct *vma;
3170 unsigned long start, end;
3171 unsigned long nr_pte_updates = 0;
3172 long pages, virtpages;
3173 struct vma_iterator vmi;
3175 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3179 * Who cares about NUMA placement when they're dying.
3181 * NOTE: make sure not to dereference p->mm before this check,
3182 * exit_task_work() happens _after_ exit_mm() so we could be called
3183 * without p->mm even though we still had it when we enqueued this
3186 if (p->flags & PF_EXITING)
3189 if (!mm->numa_next_scan) {
3190 mm->numa_next_scan = now +
3191 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3195 * Enforce maximal scan/migration frequency..
3197 migrate = mm->numa_next_scan;
3198 if (time_before(now, migrate))
3201 if (p->numa_scan_period == 0) {
3202 p->numa_scan_period_max = task_scan_max(p);
3203 p->numa_scan_period = task_scan_start(p);
3206 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3207 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3211 * Delay this task enough that another task of this mm will likely win
3212 * the next time around.
3214 p->node_stamp += 2 * TICK_NSEC;
3216 start = mm->numa_scan_offset;
3217 pages = sysctl_numa_balancing_scan_size;
3218 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3219 virtpages = pages * 8; /* Scan up to this much virtual space */
3224 if (!mmap_read_trylock(mm))
3226 vma_iter_init(&vmi, mm, start);
3227 vma = vma_next(&vmi);
3229 reset_ptenuma_scan(p);
3231 vma_iter_set(&vmi, start);
3232 vma = vma_next(&vmi);
3236 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3237 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3242 * Shared library pages mapped by multiple processes are not
3243 * migrated as it is expected they are cache replicated. Avoid
3244 * hinting faults in read-only file-backed mappings or the vdso
3245 * as migrating the pages will be of marginal benefit.
3248 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
3252 * Skip inaccessible VMAs to avoid any confusion between
3253 * PROT_NONE and NUMA hinting ptes
3255 if (!vma_is_accessible(vma))
3258 /* Initialise new per-VMA NUMAB state. */
3259 if (!vma->numab_state) {
3260 vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3262 if (!vma->numab_state)
3265 vma->numab_state->next_scan = now +
3266 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3268 /* Reset happens after 4 times scan delay of scan start */
3269 vma->numab_state->next_pid_reset = vma->numab_state->next_scan +
3270 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3274 * Scanning the VMA's of short lived tasks add more overhead. So
3275 * delay the scan for new VMAs.
3277 if (mm->numa_scan_seq && time_before(jiffies,
3278 vma->numab_state->next_scan))
3281 /* Do not scan the VMA if task has not accessed */
3282 if (!vma_is_accessed(vma))
3286 * RESET access PIDs regularly for old VMAs. Resetting after checking
3287 * vma for recent access to avoid clearing PID info before access..
3289 if (mm->numa_scan_seq &&
3290 time_after(jiffies, vma->numab_state->next_pid_reset)) {
3291 vma->numab_state->next_pid_reset = vma->numab_state->next_pid_reset +
3292 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3293 vma->numab_state->access_pids[0] = READ_ONCE(vma->numab_state->access_pids[1]);
3294 vma->numab_state->access_pids[1] = 0;
3298 start = max(start, vma->vm_start);
3299 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3300 end = min(end, vma->vm_end);
3301 nr_pte_updates = change_prot_numa(vma, start, end);
3304 * Try to scan sysctl_numa_balancing_size worth of
3305 * hpages that have at least one present PTE that
3306 * is not already pte-numa. If the VMA contains
3307 * areas that are unused or already full of prot_numa
3308 * PTEs, scan up to virtpages, to skip through those
3312 pages -= (end - start) >> PAGE_SHIFT;
3313 virtpages -= (end - start) >> PAGE_SHIFT;
3316 if (pages <= 0 || virtpages <= 0)
3320 } while (end != vma->vm_end);
3321 } for_each_vma(vmi, vma);
3325 * It is possible to reach the end of the VMA list but the last few
3326 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3327 * would find the !migratable VMA on the next scan but not reset the
3328 * scanner to the start so check it now.
3331 mm->numa_scan_offset = start;
3333 reset_ptenuma_scan(p);
3334 mmap_read_unlock(mm);
3337 * Make sure tasks use at least 32x as much time to run other code
3338 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3339 * Usually update_task_scan_period slows down scanning enough; on an
3340 * overloaded system we need to limit overhead on a per task basis.
3342 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3343 u64 diff = p->se.sum_exec_runtime - runtime;
3344 p->node_stamp += 32 * diff;
3348 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3351 struct mm_struct *mm = p->mm;
3354 mm_users = atomic_read(&mm->mm_users);
3355 if (mm_users == 1) {
3356 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3357 mm->numa_scan_seq = 0;
3361 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3362 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3363 p->numa_migrate_retry = 0;
3364 /* Protect against double add, see task_tick_numa and task_numa_work */
3365 p->numa_work.next = &p->numa_work;
3366 p->numa_faults = NULL;
3367 p->numa_pages_migrated = 0;
3368 p->total_numa_faults = 0;
3369 RCU_INIT_POINTER(p->numa_group, NULL);
3370 p->last_task_numa_placement = 0;
3371 p->last_sum_exec_runtime = 0;
3373 init_task_work(&p->numa_work, task_numa_work);
3375 /* New address space, reset the preferred nid */
3376 if (!(clone_flags & CLONE_VM)) {
3377 p->numa_preferred_nid = NUMA_NO_NODE;
3382 * New thread, keep existing numa_preferred_nid which should be copied
3383 * already by arch_dup_task_struct but stagger when scans start.
3388 delay = min_t(unsigned int, task_scan_max(current),
3389 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3390 delay += 2 * TICK_NSEC;
3391 p->node_stamp = delay;
3396 * Drive the periodic memory faults..
3398 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3400 struct callback_head *work = &curr->numa_work;
3404 * We don't care about NUMA placement if we don't have memory.
3406 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3410 * Using runtime rather than walltime has the dual advantage that
3411 * we (mostly) drive the selection from busy threads and that the
3412 * task needs to have done some actual work before we bother with
3415 now = curr->se.sum_exec_runtime;
3416 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3418 if (now > curr->node_stamp + period) {
3419 if (!curr->node_stamp)
3420 curr->numa_scan_period = task_scan_start(curr);
3421 curr->node_stamp += period;
3423 if (!time_before(jiffies, curr->mm->numa_next_scan))
3424 task_work_add(curr, work, TWA_RESUME);
3428 static void update_scan_period(struct task_struct *p, int new_cpu)
3430 int src_nid = cpu_to_node(task_cpu(p));
3431 int dst_nid = cpu_to_node(new_cpu);
3433 if (!static_branch_likely(&sched_numa_balancing))
3436 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3439 if (src_nid == dst_nid)
3443 * Allow resets if faults have been trapped before one scan
3444 * has completed. This is most likely due to a new task that
3445 * is pulled cross-node due to wakeups or load balancing.
3447 if (p->numa_scan_seq) {
3449 * Avoid scan adjustments if moving to the preferred
3450 * node or if the task was not previously running on
3451 * the preferred node.
3453 if (dst_nid == p->numa_preferred_nid ||
3454 (p->numa_preferred_nid != NUMA_NO_NODE &&
3455 src_nid != p->numa_preferred_nid))
3459 p->numa_scan_period = task_scan_start(p);
3463 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3467 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3471 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3475 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3479 #endif /* CONFIG_NUMA_BALANCING */
3482 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3484 update_load_add(&cfs_rq->load, se->load.weight);
3486 if (entity_is_task(se)) {
3487 struct rq *rq = rq_of(cfs_rq);
3489 account_numa_enqueue(rq, task_of(se));
3490 list_add(&se->group_node, &rq->cfs_tasks);
3493 cfs_rq->nr_running++;
3495 cfs_rq->idle_nr_running++;
3499 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3501 update_load_sub(&cfs_rq->load, se->load.weight);
3503 if (entity_is_task(se)) {
3504 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3505 list_del_init(&se->group_node);
3508 cfs_rq->nr_running--;
3510 cfs_rq->idle_nr_running--;
3514 * Signed add and clamp on underflow.
3516 * Explicitly do a load-store to ensure the intermediate value never hits
3517 * memory. This allows lockless observations without ever seeing the negative
3520 #define add_positive(_ptr, _val) do { \
3521 typeof(_ptr) ptr = (_ptr); \
3522 typeof(_val) val = (_val); \
3523 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3527 if (val < 0 && res > var) \
3530 WRITE_ONCE(*ptr, res); \
3534 * Unsigned subtract and clamp on underflow.
3536 * Explicitly do a load-store to ensure the intermediate value never hits
3537 * memory. This allows lockless observations without ever seeing the negative
3540 #define sub_positive(_ptr, _val) do { \
3541 typeof(_ptr) ptr = (_ptr); \
3542 typeof(*ptr) val = (_val); \
3543 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3547 WRITE_ONCE(*ptr, res); \
3551 * Remove and clamp on negative, from a local variable.
3553 * A variant of sub_positive(), which does not use explicit load-store
3554 * and is thus optimized for local variable updates.
3556 #define lsub_positive(_ptr, _val) do { \
3557 typeof(_ptr) ptr = (_ptr); \
3558 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3563 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3565 cfs_rq->avg.load_avg += se->avg.load_avg;
3566 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3570 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3572 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3573 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3574 /* See update_cfs_rq_load_avg() */
3575 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3576 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3580 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3582 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3585 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3586 unsigned long weight)
3588 unsigned long old_weight = se->load.weight;
3591 /* commit outstanding execution time */
3592 if (cfs_rq->curr == se)
3593 update_curr(cfs_rq);
3595 avg_vruntime_sub(cfs_rq, se);
3596 update_load_sub(&cfs_rq->load, se->load.weight);
3598 dequeue_load_avg(cfs_rq, se);
3600 update_load_set(&se->load, weight);
3604 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3605 * we need to scale se->vlag when w_i changes.
3607 se->vlag = div_s64(se->vlag * old_weight, weight);
3609 s64 deadline = se->deadline - se->vruntime;
3611 * When the weight changes, the virtual time slope changes and
3612 * we should adjust the relative virtual deadline accordingly.
3614 deadline = div_s64(deadline * old_weight, weight);
3615 se->deadline = se->vruntime + deadline;
3620 u32 divider = get_pelt_divider(&se->avg);
3622 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3626 enqueue_load_avg(cfs_rq, se);
3628 update_load_add(&cfs_rq->load, se->load.weight);
3629 if (cfs_rq->curr != se)
3630 avg_vruntime_add(cfs_rq, se);
3634 void reweight_task(struct task_struct *p, int prio)
3636 struct sched_entity *se = &p->se;
3637 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3638 struct load_weight *load = &se->load;
3639 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3641 reweight_entity(cfs_rq, se, weight);
3642 load->inv_weight = sched_prio_to_wmult[prio];
3645 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3647 #ifdef CONFIG_FAIR_GROUP_SCHED
3650 * All this does is approximate the hierarchical proportion which includes that
3651 * global sum we all love to hate.
3653 * That is, the weight of a group entity, is the proportional share of the
3654 * group weight based on the group runqueue weights. That is:
3656 * tg->weight * grq->load.weight
3657 * ge->load.weight = ----------------------------- (1)
3658 * \Sum grq->load.weight
3660 * Now, because computing that sum is prohibitively expensive to compute (been
3661 * there, done that) we approximate it with this average stuff. The average
3662 * moves slower and therefore the approximation is cheaper and more stable.
3664 * So instead of the above, we substitute:
3666 * grq->load.weight -> grq->avg.load_avg (2)
3668 * which yields the following:
3670 * tg->weight * grq->avg.load_avg
3671 * ge->load.weight = ------------------------------ (3)
3674 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3676 * That is shares_avg, and it is right (given the approximation (2)).
3678 * The problem with it is that because the average is slow -- it was designed
3679 * to be exactly that of course -- this leads to transients in boundary
3680 * conditions. In specific, the case where the group was idle and we start the
3681 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3682 * yielding bad latency etc..
3684 * Now, in that special case (1) reduces to:
3686 * tg->weight * grq->load.weight
3687 * ge->load.weight = ----------------------------- = tg->weight (4)
3690 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3692 * So what we do is modify our approximation (3) to approach (4) in the (near)
3697 * tg->weight * grq->load.weight
3698 * --------------------------------------------------- (5)
3699 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3701 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3702 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3705 * tg->weight * grq->load.weight
3706 * ge->load.weight = ----------------------------- (6)
3711 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3712 * max(grq->load.weight, grq->avg.load_avg)
3714 * And that is shares_weight and is icky. In the (near) UP case it approaches
3715 * (4) while in the normal case it approaches (3). It consistently
3716 * overestimates the ge->load.weight and therefore:
3718 * \Sum ge->load.weight >= tg->weight
3722 static long calc_group_shares(struct cfs_rq *cfs_rq)
3724 long tg_weight, tg_shares, load, shares;
3725 struct task_group *tg = cfs_rq->tg;
3727 tg_shares = READ_ONCE(tg->shares);
3729 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3731 tg_weight = atomic_long_read(&tg->load_avg);
3733 /* Ensure tg_weight >= load */
3734 tg_weight -= cfs_rq->tg_load_avg_contrib;
3737 shares = (tg_shares * load);
3739 shares /= tg_weight;
3742 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3743 * of a group with small tg->shares value. It is a floor value which is
3744 * assigned as a minimum load.weight to the sched_entity representing
3745 * the group on a CPU.
3747 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3748 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3749 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3750 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3753 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3755 #endif /* CONFIG_SMP */
3758 * Recomputes the group entity based on the current state of its group
3761 static void update_cfs_group(struct sched_entity *se)
3763 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3769 if (throttled_hierarchy(gcfs_rq))
3773 shares = READ_ONCE(gcfs_rq->tg->shares);
3775 if (likely(se->load.weight == shares))
3778 shares = calc_group_shares(gcfs_rq);
3781 reweight_entity(cfs_rq_of(se), se, shares);
3784 #else /* CONFIG_FAIR_GROUP_SCHED */
3785 static inline void update_cfs_group(struct sched_entity *se)
3788 #endif /* CONFIG_FAIR_GROUP_SCHED */
3790 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3792 struct rq *rq = rq_of(cfs_rq);
3794 if (&rq->cfs == cfs_rq) {
3796 * There are a few boundary cases this might miss but it should
3797 * get called often enough that that should (hopefully) not be
3800 * It will not get called when we go idle, because the idle
3801 * thread is a different class (!fair), nor will the utilization
3802 * number include things like RT tasks.
3804 * As is, the util number is not freq-invariant (we'd have to
3805 * implement arch_scale_freq_capacity() for that).
3807 * See cpu_util_cfs().
3809 cpufreq_update_util(rq, flags);
3814 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3822 if (sa->runnable_sum)
3826 * _avg must be null when _sum are null because _avg = _sum / divider
3827 * Make sure that rounding and/or propagation of PELT values never
3830 SCHED_WARN_ON(sa->load_avg ||
3837 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3839 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3840 cfs_rq->last_update_time_copy);
3842 #ifdef CONFIG_FAIR_GROUP_SCHED
3844 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
3845 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
3846 * bottom-up, we only have to test whether the cfs_rq before us on the list
3848 * If cfs_rq is not on the list, test whether a child needs its to be added to
3849 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
3851 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
3853 struct cfs_rq *prev_cfs_rq;
3854 struct list_head *prev;
3856 if (cfs_rq->on_list) {
3857 prev = cfs_rq->leaf_cfs_rq_list.prev;
3859 struct rq *rq = rq_of(cfs_rq);
3861 prev = rq->tmp_alone_branch;
3864 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
3866 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
3869 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
3871 if (cfs_rq->load.weight)
3874 if (!load_avg_is_decayed(&cfs_rq->avg))
3877 if (child_cfs_rq_on_list(cfs_rq))
3884 * update_tg_load_avg - update the tg's load avg
3885 * @cfs_rq: the cfs_rq whose avg changed
3887 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3888 * However, because tg->load_avg is a global value there are performance
3891 * In order to avoid having to look at the other cfs_rq's, we use a
3892 * differential update where we store the last value we propagated. This in
3893 * turn allows skipping updates if the differential is 'small'.
3895 * Updating tg's load_avg is necessary before update_cfs_share().
3897 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
3899 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3902 * No need to update load_avg for root_task_group as it is not used.
3904 if (cfs_rq->tg == &root_task_group)
3907 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3908 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3909 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3914 * Called within set_task_rq() right before setting a task's CPU. The
3915 * caller only guarantees p->pi_lock is held; no other assumptions,
3916 * including the state of rq->lock, should be made.
3918 void set_task_rq_fair(struct sched_entity *se,
3919 struct cfs_rq *prev, struct cfs_rq *next)
3921 u64 p_last_update_time;
3922 u64 n_last_update_time;
3924 if (!sched_feat(ATTACH_AGE_LOAD))
3928 * We are supposed to update the task to "current" time, then its up to
3929 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3930 * getting what current time is, so simply throw away the out-of-date
3931 * time. This will result in the wakee task is less decayed, but giving
3932 * the wakee more load sounds not bad.
3934 if (!(se->avg.last_update_time && prev))
3937 p_last_update_time = cfs_rq_last_update_time(prev);
3938 n_last_update_time = cfs_rq_last_update_time(next);
3940 __update_load_avg_blocked_se(p_last_update_time, se);
3941 se->avg.last_update_time = n_last_update_time;
3945 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3946 * propagate its contribution. The key to this propagation is the invariant
3947 * that for each group:
3949 * ge->avg == grq->avg (1)
3951 * _IFF_ we look at the pure running and runnable sums. Because they
3952 * represent the very same entity, just at different points in the hierarchy.
3954 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
3955 * and simply copies the running/runnable sum over (but still wrong, because
3956 * the group entity and group rq do not have their PELT windows aligned).
3958 * However, update_tg_cfs_load() is more complex. So we have:
3960 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
3962 * And since, like util, the runnable part should be directly transferable,
3963 * the following would _appear_ to be the straight forward approach:
3965 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
3967 * And per (1) we have:
3969 * ge->avg.runnable_avg == grq->avg.runnable_avg
3973 * ge->load.weight * grq->avg.load_avg
3974 * ge->avg.load_avg = ----------------------------------- (4)
3977 * Except that is wrong!
3979 * Because while for entities historical weight is not important and we
3980 * really only care about our future and therefore can consider a pure
3981 * runnable sum, runqueues can NOT do this.
3983 * We specifically want runqueues to have a load_avg that includes
3984 * historical weights. Those represent the blocked load, the load we expect
3985 * to (shortly) return to us. This only works by keeping the weights as
3986 * integral part of the sum. We therefore cannot decompose as per (3).
3988 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
3989 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
3990 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
3991 * runnable section of these tasks overlap (or not). If they were to perfectly
3992 * align the rq as a whole would be runnable 2/3 of the time. If however we
3993 * always have at least 1 runnable task, the rq as a whole is always runnable.
3995 * So we'll have to approximate.. :/
3997 * Given the constraint:
3999 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4001 * We can construct a rule that adds runnable to a rq by assuming minimal
4004 * On removal, we'll assume each task is equally runnable; which yields:
4006 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4008 * XXX: only do this for the part of runnable > running ?
4012 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4014 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4015 u32 new_sum, divider;
4017 /* Nothing to update */
4022 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4023 * See ___update_load_avg() for details.
4025 divider = get_pelt_divider(&cfs_rq->avg);
4028 /* Set new sched_entity's utilization */
4029 se->avg.util_avg = gcfs_rq->avg.util_avg;
4030 new_sum = se->avg.util_avg * divider;
4031 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4032 se->avg.util_sum = new_sum;
4034 /* Update parent cfs_rq utilization */
4035 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4036 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4038 /* See update_cfs_rq_load_avg() */
4039 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4040 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4044 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4046 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4047 u32 new_sum, divider;
4049 /* Nothing to update */
4054 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4055 * See ___update_load_avg() for details.
4057 divider = get_pelt_divider(&cfs_rq->avg);
4059 /* Set new sched_entity's runnable */
4060 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4061 new_sum = se->avg.runnable_avg * divider;
4062 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4063 se->avg.runnable_sum = new_sum;
4065 /* Update parent cfs_rq runnable */
4066 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4067 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4068 /* See update_cfs_rq_load_avg() */
4069 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4070 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4074 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4076 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4077 unsigned long load_avg;
4085 gcfs_rq->prop_runnable_sum = 0;
4088 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4089 * See ___update_load_avg() for details.
4091 divider = get_pelt_divider(&cfs_rq->avg);
4093 if (runnable_sum >= 0) {
4095 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4096 * the CPU is saturated running == runnable.
4098 runnable_sum += se->avg.load_sum;
4099 runnable_sum = min_t(long, runnable_sum, divider);
4102 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4103 * assuming all tasks are equally runnable.
4105 if (scale_load_down(gcfs_rq->load.weight)) {
4106 load_sum = div_u64(gcfs_rq->avg.load_sum,
4107 scale_load_down(gcfs_rq->load.weight));
4110 /* But make sure to not inflate se's runnable */
4111 runnable_sum = min(se->avg.load_sum, load_sum);
4115 * runnable_sum can't be lower than running_sum
4116 * Rescale running sum to be in the same range as runnable sum
4117 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4118 * runnable_sum is in [0 : LOAD_AVG_MAX]
4120 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4121 runnable_sum = max(runnable_sum, running_sum);
4123 load_sum = se_weight(se) * runnable_sum;
4124 load_avg = div_u64(load_sum, divider);
4126 delta_avg = load_avg - se->avg.load_avg;
4130 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4132 se->avg.load_sum = runnable_sum;
4133 se->avg.load_avg = load_avg;
4134 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4135 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4136 /* See update_cfs_rq_load_avg() */
4137 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4138 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4141 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4143 cfs_rq->propagate = 1;
4144 cfs_rq->prop_runnable_sum += runnable_sum;
4147 /* Update task and its cfs_rq load average */
4148 static inline int propagate_entity_load_avg(struct sched_entity *se)
4150 struct cfs_rq *cfs_rq, *gcfs_rq;
4152 if (entity_is_task(se))
4155 gcfs_rq = group_cfs_rq(se);
4156 if (!gcfs_rq->propagate)
4159 gcfs_rq->propagate = 0;
4161 cfs_rq = cfs_rq_of(se);
4163 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4165 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4166 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4167 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4169 trace_pelt_cfs_tp(cfs_rq);
4170 trace_pelt_se_tp(se);
4176 * Check if we need to update the load and the utilization of a blocked
4179 static inline bool skip_blocked_update(struct sched_entity *se)
4181 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4184 * If sched_entity still have not zero load or utilization, we have to
4187 if (se->avg.load_avg || se->avg.util_avg)
4191 * If there is a pending propagation, we have to update the load and
4192 * the utilization of the sched_entity:
4194 if (gcfs_rq->propagate)
4198 * Otherwise, the load and the utilization of the sched_entity is
4199 * already zero and there is no pending propagation, so it will be a
4200 * waste of time to try to decay it:
4205 #else /* CONFIG_FAIR_GROUP_SCHED */
4207 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4209 static inline int propagate_entity_load_avg(struct sched_entity *se)
4214 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4216 #endif /* CONFIG_FAIR_GROUP_SCHED */
4218 #ifdef CONFIG_NO_HZ_COMMON
4219 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4221 u64 throttled = 0, now, lut;
4222 struct cfs_rq *cfs_rq;
4226 if (load_avg_is_decayed(&se->avg))
4229 cfs_rq = cfs_rq_of(se);
4233 is_idle = is_idle_task(rcu_dereference(rq->curr));
4237 * The lag estimation comes with a cost we don't want to pay all the
4238 * time. Hence, limiting to the case where the source CPU is idle and
4239 * we know we are at the greatest risk to have an outdated clock.
4245 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4247 * last_update_time (the cfs_rq's last_update_time)
4248 * = cfs_rq_clock_pelt()@cfs_rq_idle
4249 * = rq_clock_pelt()@cfs_rq_idle
4250 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4252 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4253 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4255 * rq_idle_lag (delta between now and rq's update)
4256 * = sched_clock_cpu() - rq_clock()@rq_idle
4258 * We can then write:
4260 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4261 * sched_clock_cpu() - rq_clock()@rq_idle
4263 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4264 * rq_clock()@rq_idle is rq->clock_idle
4265 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4266 * is cfs_rq->throttled_pelt_idle
4269 #ifdef CONFIG_CFS_BANDWIDTH
4270 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4271 /* The clock has been stopped for throttling */
4272 if (throttled == U64_MAX)
4275 now = u64_u32_load(rq->clock_pelt_idle);
4277 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4278 * is observed the old clock_pelt_idle value and the new clock_idle,
4279 * which lead to an underestimation. The opposite would lead to an
4283 lut = cfs_rq_last_update_time(cfs_rq);
4288 * cfs_rq->avg.last_update_time is more recent than our
4289 * estimation, let's use it.
4293 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4295 __update_load_avg_blocked_se(now, se);
4298 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4302 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4303 * @now: current time, as per cfs_rq_clock_pelt()
4304 * @cfs_rq: cfs_rq to update
4306 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4307 * avg. The immediate corollary is that all (fair) tasks must be attached.
4309 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4311 * Return: true if the load decayed or we removed load.
4313 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4314 * call update_tg_load_avg() when this function returns true.
4317 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4319 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4320 struct sched_avg *sa = &cfs_rq->avg;
4323 if (cfs_rq->removed.nr) {
4325 u32 divider = get_pelt_divider(&cfs_rq->avg);
4327 raw_spin_lock(&cfs_rq->removed.lock);
4328 swap(cfs_rq->removed.util_avg, removed_util);
4329 swap(cfs_rq->removed.load_avg, removed_load);
4330 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4331 cfs_rq->removed.nr = 0;
4332 raw_spin_unlock(&cfs_rq->removed.lock);
4335 sub_positive(&sa->load_avg, r);
4336 sub_positive(&sa->load_sum, r * divider);
4337 /* See sa->util_sum below */
4338 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4341 sub_positive(&sa->util_avg, r);
4342 sub_positive(&sa->util_sum, r * divider);
4344 * Because of rounding, se->util_sum might ends up being +1 more than
4345 * cfs->util_sum. Although this is not a problem by itself, detaching
4346 * a lot of tasks with the rounding problem between 2 updates of
4347 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4348 * cfs_util_avg is not.
4349 * Check that util_sum is still above its lower bound for the new
4350 * util_avg. Given that period_contrib might have moved since the last
4351 * sync, we are only sure that util_sum must be above or equal to
4352 * util_avg * minimum possible divider
4354 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4356 r = removed_runnable;
4357 sub_positive(&sa->runnable_avg, r);
4358 sub_positive(&sa->runnable_sum, r * divider);
4359 /* See sa->util_sum above */
4360 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4361 sa->runnable_avg * PELT_MIN_DIVIDER);
4364 * removed_runnable is the unweighted version of removed_load so we
4365 * can use it to estimate removed_load_sum.
4367 add_tg_cfs_propagate(cfs_rq,
4368 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4373 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4374 u64_u32_store_copy(sa->last_update_time,
4375 cfs_rq->last_update_time_copy,
4376 sa->last_update_time);
4381 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4382 * @cfs_rq: cfs_rq to attach to
4383 * @se: sched_entity to attach
4385 * Must call update_cfs_rq_load_avg() before this, since we rely on
4386 * cfs_rq->avg.last_update_time being current.
4388 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4391 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4392 * See ___update_load_avg() for details.
4394 u32 divider = get_pelt_divider(&cfs_rq->avg);
4397 * When we attach the @se to the @cfs_rq, we must align the decay
4398 * window because without that, really weird and wonderful things can
4403 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4404 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4407 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4408 * period_contrib. This isn't strictly correct, but since we're
4409 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4412 se->avg.util_sum = se->avg.util_avg * divider;
4414 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4416 se->avg.load_sum = se->avg.load_avg * divider;
4417 if (se_weight(se) < se->avg.load_sum)
4418 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4420 se->avg.load_sum = 1;
4422 enqueue_load_avg(cfs_rq, se);
4423 cfs_rq->avg.util_avg += se->avg.util_avg;
4424 cfs_rq->avg.util_sum += se->avg.util_sum;
4425 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4426 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4428 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4430 cfs_rq_util_change(cfs_rq, 0);
4432 trace_pelt_cfs_tp(cfs_rq);
4436 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4437 * @cfs_rq: cfs_rq to detach from
4438 * @se: sched_entity to detach
4440 * Must call update_cfs_rq_load_avg() before this, since we rely on
4441 * cfs_rq->avg.last_update_time being current.
4443 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4445 dequeue_load_avg(cfs_rq, se);
4446 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4447 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4448 /* See update_cfs_rq_load_avg() */
4449 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4450 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4452 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4453 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4454 /* See update_cfs_rq_load_avg() */
4455 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4456 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4458 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4460 cfs_rq_util_change(cfs_rq, 0);
4462 trace_pelt_cfs_tp(cfs_rq);
4466 * Optional action to be done while updating the load average
4468 #define UPDATE_TG 0x1
4469 #define SKIP_AGE_LOAD 0x2
4470 #define DO_ATTACH 0x4
4471 #define DO_DETACH 0x8
4473 /* Update task and its cfs_rq load average */
4474 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4476 u64 now = cfs_rq_clock_pelt(cfs_rq);
4480 * Track task load average for carrying it to new CPU after migrated, and
4481 * track group sched_entity load average for task_h_load calc in migration
4483 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4484 __update_load_avg_se(now, cfs_rq, se);
4486 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4487 decayed |= propagate_entity_load_avg(se);
4489 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4492 * DO_ATTACH means we're here from enqueue_entity().
4493 * !last_update_time means we've passed through
4494 * migrate_task_rq_fair() indicating we migrated.
4496 * IOW we're enqueueing a task on a new CPU.
4498 attach_entity_load_avg(cfs_rq, se);
4499 update_tg_load_avg(cfs_rq);
4501 } else if (flags & DO_DETACH) {
4503 * DO_DETACH means we're here from dequeue_entity()
4504 * and we are migrating task out of the CPU.
4506 detach_entity_load_avg(cfs_rq, se);
4507 update_tg_load_avg(cfs_rq);
4508 } else if (decayed) {
4509 cfs_rq_util_change(cfs_rq, 0);
4511 if (flags & UPDATE_TG)
4512 update_tg_load_avg(cfs_rq);
4517 * Synchronize entity load avg of dequeued entity without locking
4520 static void sync_entity_load_avg(struct sched_entity *se)
4522 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4523 u64 last_update_time;
4525 last_update_time = cfs_rq_last_update_time(cfs_rq);
4526 __update_load_avg_blocked_se(last_update_time, se);
4530 * Task first catches up with cfs_rq, and then subtract
4531 * itself from the cfs_rq (task must be off the queue now).
4533 static void remove_entity_load_avg(struct sched_entity *se)
4535 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4536 unsigned long flags;
4539 * tasks cannot exit without having gone through wake_up_new_task() ->
4540 * enqueue_task_fair() which will have added things to the cfs_rq,
4541 * so we can remove unconditionally.
4544 sync_entity_load_avg(se);
4546 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4547 ++cfs_rq->removed.nr;
4548 cfs_rq->removed.util_avg += se->avg.util_avg;
4549 cfs_rq->removed.load_avg += se->avg.load_avg;
4550 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4551 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4554 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4556 return cfs_rq->avg.runnable_avg;
4559 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4561 return cfs_rq->avg.load_avg;
4564 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4566 static inline unsigned long task_util(struct task_struct *p)
4568 return READ_ONCE(p->se.avg.util_avg);
4571 static inline unsigned long _task_util_est(struct task_struct *p)
4573 struct util_est ue = READ_ONCE(p->se.avg.util_est);
4575 return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4578 static inline unsigned long task_util_est(struct task_struct *p)
4580 return max(task_util(p), _task_util_est(p));
4583 #ifdef CONFIG_UCLAMP_TASK
4584 static inline unsigned long uclamp_task_util(struct task_struct *p,
4585 unsigned long uclamp_min,
4586 unsigned long uclamp_max)
4588 return clamp(task_util_est(p), uclamp_min, uclamp_max);
4591 static inline unsigned long uclamp_task_util(struct task_struct *p,
4592 unsigned long uclamp_min,
4593 unsigned long uclamp_max)
4595 return task_util_est(p);
4599 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4600 struct task_struct *p)
4602 unsigned int enqueued;
4604 if (!sched_feat(UTIL_EST))
4607 /* Update root cfs_rq's estimated utilization */
4608 enqueued = cfs_rq->avg.util_est.enqueued;
4609 enqueued += _task_util_est(p);
4610 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4612 trace_sched_util_est_cfs_tp(cfs_rq);
4615 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4616 struct task_struct *p)
4618 unsigned int enqueued;
4620 if (!sched_feat(UTIL_EST))
4623 /* Update root cfs_rq's estimated utilization */
4624 enqueued = cfs_rq->avg.util_est.enqueued;
4625 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4626 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4628 trace_sched_util_est_cfs_tp(cfs_rq);
4631 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4634 * Check if a (signed) value is within a specified (unsigned) margin,
4635 * based on the observation that:
4637 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4639 * NOTE: this only works when value + margin < INT_MAX.
4641 static inline bool within_margin(int value, int margin)
4643 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4646 static inline void util_est_update(struct cfs_rq *cfs_rq,
4647 struct task_struct *p,
4650 long last_ewma_diff, last_enqueued_diff;
4653 if (!sched_feat(UTIL_EST))
4657 * Skip update of task's estimated utilization when the task has not
4658 * yet completed an activation, e.g. being migrated.
4664 * If the PELT values haven't changed since enqueue time,
4665 * skip the util_est update.
4667 ue = p->se.avg.util_est;
4668 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4671 last_enqueued_diff = ue.enqueued;
4674 * Reset EWMA on utilization increases, the moving average is used only
4675 * to smooth utilization decreases.
4677 ue.enqueued = task_util(p);
4678 if (sched_feat(UTIL_EST_FASTUP)) {
4679 if (ue.ewma < ue.enqueued) {
4680 ue.ewma = ue.enqueued;
4686 * Skip update of task's estimated utilization when its members are
4687 * already ~1% close to its last activation value.
4689 last_ewma_diff = ue.enqueued - ue.ewma;
4690 last_enqueued_diff -= ue.enqueued;
4691 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4692 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4699 * To avoid overestimation of actual task utilization, skip updates if
4700 * we cannot grant there is idle time in this CPU.
4702 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4706 * Update Task's estimated utilization
4708 * When *p completes an activation we can consolidate another sample
4709 * of the task size. This is done by storing the current PELT value
4710 * as ue.enqueued and by using this value to update the Exponential
4711 * Weighted Moving Average (EWMA):
4713 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4714 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4715 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4716 * = w * ( last_ewma_diff ) + ewma(t-1)
4717 * = w * (last_ewma_diff + ewma(t-1) / w)
4719 * Where 'w' is the weight of new samples, which is configured to be
4720 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4722 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4723 ue.ewma += last_ewma_diff;
4724 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4726 ue.enqueued |= UTIL_AVG_UNCHANGED;
4727 WRITE_ONCE(p->se.avg.util_est, ue);
4729 trace_sched_util_est_se_tp(&p->se);
4732 static inline int util_fits_cpu(unsigned long util,
4733 unsigned long uclamp_min,
4734 unsigned long uclamp_max,
4737 unsigned long capacity_orig, capacity_orig_thermal;
4738 unsigned long capacity = capacity_of(cpu);
4739 bool fits, uclamp_max_fits;
4742 * Check if the real util fits without any uclamp boost/cap applied.
4744 fits = fits_capacity(util, capacity);
4746 if (!uclamp_is_used())
4750 * We must use capacity_orig_of() for comparing against uclamp_min and
4751 * uclamp_max. We only care about capacity pressure (by using
4752 * capacity_of()) for comparing against the real util.
4754 * If a task is boosted to 1024 for example, we don't want a tiny
4755 * pressure to skew the check whether it fits a CPU or not.
4757 * Similarly if a task is capped to capacity_orig_of(little_cpu), it
4758 * should fit a little cpu even if there's some pressure.
4760 * Only exception is for thermal pressure since it has a direct impact
4761 * on available OPP of the system.
4763 * We honour it for uclamp_min only as a drop in performance level
4764 * could result in not getting the requested minimum performance level.
4766 * For uclamp_max, we can tolerate a drop in performance level as the
4767 * goal is to cap the task. So it's okay if it's getting less.
4769 capacity_orig = capacity_orig_of(cpu);
4770 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4773 * We want to force a task to fit a cpu as implied by uclamp_max.
4774 * But we do have some corner cases to cater for..
4780 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4783 * | | | | | | | (util somewhere in this region)
4786 * +----------------------------------------
4789 * In the above example if a task is capped to a specific performance
4790 * point, y, then when:
4792 * * util = 80% of x then it does not fit on cpu0 and should migrate
4794 * * util = 80% of y then it is forced to fit on cpu1 to honour
4795 * uclamp_max request.
4797 * which is what we're enforcing here. A task always fits if
4798 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4799 * the normal upmigration rules should withhold still.
4801 * Only exception is when we are on max capacity, then we need to be
4802 * careful not to block overutilized state. This is so because:
4804 * 1. There's no concept of capping at max_capacity! We can't go
4805 * beyond this performance level anyway.
4806 * 2. The system is being saturated when we're operating near
4807 * max capacity, it doesn't make sense to block overutilized.
4809 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4810 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4811 fits = fits || uclamp_max_fits;
4816 * | ___ (region a, capped, util >= uclamp_max)
4818 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4820 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
4821 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4823 * | | | | | | | (region c, boosted, util < uclamp_min)
4824 * +----------------------------------------
4827 * a) If util > uclamp_max, then we're capped, we don't care about
4828 * actual fitness value here. We only care if uclamp_max fits
4829 * capacity without taking margin/pressure into account.
4830 * See comment above.
4832 * b) If uclamp_min <= util <= uclamp_max, then the normal
4833 * fits_capacity() rules apply. Except we need to ensure that we
4834 * enforce we remain within uclamp_max, see comment above.
4836 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
4837 * need to take into account the boosted value fits the CPU without
4838 * taking margin/pressure into account.
4840 * Cases (a) and (b) are handled in the 'fits' variable already. We
4841 * just need to consider an extra check for case (c) after ensuring we
4842 * handle the case uclamp_min > uclamp_max.
4844 uclamp_min = min(uclamp_min, uclamp_max);
4845 if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
4851 static inline int task_fits_cpu(struct task_struct *p, int cpu)
4853 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
4854 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
4855 unsigned long util = task_util_est(p);
4857 * Return true only if the cpu fully fits the task requirements, which
4858 * include the utilization but also the performance hints.
4860 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
4863 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4865 if (!sched_asym_cpucap_active())
4868 if (!p || p->nr_cpus_allowed == 1) {
4869 rq->misfit_task_load = 0;
4873 if (task_fits_cpu(p, cpu_of(rq))) {
4874 rq->misfit_task_load = 0;
4879 * Make sure that misfit_task_load will not be null even if
4880 * task_h_load() returns 0.
4882 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4885 #else /* CONFIG_SMP */
4887 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4892 #define UPDATE_TG 0x0
4893 #define SKIP_AGE_LOAD 0x0
4894 #define DO_ATTACH 0x0
4895 #define DO_DETACH 0x0
4897 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4899 cfs_rq_util_change(cfs_rq, 0);
4902 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4905 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4907 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4909 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4915 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4918 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4921 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4923 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4925 #endif /* CONFIG_SMP */
4928 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4930 u64 vslice, vruntime = avg_vruntime(cfs_rq);
4933 se->slice = sysctl_sched_base_slice;
4934 vslice = calc_delta_fair(se->slice, se);
4937 * Due to how V is constructed as the weighted average of entities,
4938 * adding tasks with positive lag, or removing tasks with negative lag
4939 * will move 'time' backwards, this can screw around with the lag of
4942 * EEVDF: placement strategy #1 / #2
4944 if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
4945 struct sched_entity *curr = cfs_rq->curr;
4951 * If we want to place a task and preserve lag, we have to
4952 * consider the effect of the new entity on the weighted
4953 * average and compensate for this, otherwise lag can quickly
4956 * Lag is defined as:
4958 * lag_i = S - s_i = w_i * (V - v_i)
4960 * To avoid the 'w_i' term all over the place, we only track
4963 * vl_i = V - v_i <=> v_i = V - vl_i
4965 * And we take V to be the weighted average of all v:
4967 * V = (\Sum w_j*v_j) / W
4969 * Where W is: \Sum w_j
4971 * Then, the weighted average after adding an entity with lag
4974 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
4975 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
4976 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
4977 * = (V*(W + w_i) - w_i*l) / (W + w_i)
4978 * = V - w_i*vl_i / (W + w_i)
4980 * And the actual lag after adding an entity with vl_i is:
4983 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
4984 * = vl_i - w_i*vl_i / (W + w_i)
4986 * Which is strictly less than vl_i. So in order to preserve lag
4987 * we should inflate the lag before placement such that the
4988 * effective lag after placement comes out right.
4990 * As such, invert the above relation for vl'_i to get the vl_i
4991 * we need to use such that the lag after placement is the lag
4992 * we computed before dequeue.
4994 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
4995 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
4997 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5000 * vl_i = (W + w_i)*vl'_i / W
5002 load = cfs_rq->avg_load;
5003 if (curr && curr->on_rq)
5004 load += scale_load_down(curr->load.weight);
5006 lag *= load + scale_load_down(se->load.weight);
5007 if (WARN_ON_ONCE(!load))
5009 lag = div_s64(lag, load);
5012 se->vruntime = vruntime - lag;
5015 * When joining the competition; the exisiting tasks will be,
5016 * on average, halfway through their slice, as such start tasks
5017 * off with half a slice to ease into the competition.
5019 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5023 * EEVDF: vd_i = ve_i + r_i/w_i
5025 se->deadline = se->vruntime + vslice;
5028 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5029 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5031 static inline bool cfs_bandwidth_used(void);
5034 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5036 bool curr = cfs_rq->curr == se;
5039 * If we're the current task, we must renormalise before calling
5043 place_entity(cfs_rq, se, flags);
5045 update_curr(cfs_rq);
5048 * When enqueuing a sched_entity, we must:
5049 * - Update loads to have both entity and cfs_rq synced with now.
5050 * - For group_entity, update its runnable_weight to reflect the new
5051 * h_nr_running of its group cfs_rq.
5052 * - For group_entity, update its weight to reflect the new share of
5054 * - Add its new weight to cfs_rq->load.weight
5056 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5057 se_update_runnable(se);
5059 * XXX update_load_avg() above will have attached us to the pelt sum;
5060 * but update_cfs_group() here will re-adjust the weight and have to
5061 * undo/redo all that. Seems wasteful.
5063 update_cfs_group(se);
5066 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5067 * we can place the entity.
5070 place_entity(cfs_rq, se, flags);
5072 account_entity_enqueue(cfs_rq, se);
5074 /* Entity has migrated, no longer consider this task hot */
5075 if (flags & ENQUEUE_MIGRATED)
5078 check_schedstat_required();
5079 update_stats_enqueue_fair(cfs_rq, se, flags);
5081 __enqueue_entity(cfs_rq, se);
5084 if (cfs_rq->nr_running == 1) {
5085 check_enqueue_throttle(cfs_rq);
5086 if (!throttled_hierarchy(cfs_rq)) {
5087 list_add_leaf_cfs_rq(cfs_rq);
5089 #ifdef CONFIG_CFS_BANDWIDTH
5090 struct rq *rq = rq_of(cfs_rq);
5092 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5093 cfs_rq->throttled_clock = rq_clock(rq);
5094 if (!cfs_rq->throttled_clock_self)
5095 cfs_rq->throttled_clock_self = rq_clock(rq);
5101 static void __clear_buddies_next(struct sched_entity *se)
5103 for_each_sched_entity(se) {
5104 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5105 if (cfs_rq->next != se)
5108 cfs_rq->next = NULL;
5112 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5114 if (cfs_rq->next == se)
5115 __clear_buddies_next(se);
5118 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5121 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5123 int action = UPDATE_TG;
5125 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5126 action |= DO_DETACH;
5129 * Update run-time statistics of the 'current'.
5131 update_curr(cfs_rq);
5134 * When dequeuing a sched_entity, we must:
5135 * - Update loads to have both entity and cfs_rq synced with now.
5136 * - For group_entity, update its runnable_weight to reflect the new
5137 * h_nr_running of its group cfs_rq.
5138 * - Subtract its previous weight from cfs_rq->load.weight.
5139 * - For group entity, update its weight to reflect the new share
5140 * of its group cfs_rq.
5142 update_load_avg(cfs_rq, se, action);
5143 se_update_runnable(se);
5145 update_stats_dequeue_fair(cfs_rq, se, flags);
5147 clear_buddies(cfs_rq, se);
5149 update_entity_lag(cfs_rq, se);
5150 if (se != cfs_rq->curr)
5151 __dequeue_entity(cfs_rq, se);
5153 account_entity_dequeue(cfs_rq, se);
5155 /* return excess runtime on last dequeue */
5156 return_cfs_rq_runtime(cfs_rq);
5158 update_cfs_group(se);
5161 * Now advance min_vruntime if @se was the entity holding it back,
5162 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5163 * put back on, and if we advance min_vruntime, we'll be placed back
5164 * further than we started -- ie. we'll be penalized.
5166 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5167 update_min_vruntime(cfs_rq);
5169 if (cfs_rq->nr_running == 0)
5170 update_idle_cfs_rq_clock_pelt(cfs_rq);
5174 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5176 clear_buddies(cfs_rq, se);
5178 /* 'current' is not kept within the tree. */
5181 * Any task has to be enqueued before it get to execute on
5182 * a CPU. So account for the time it spent waiting on the
5185 update_stats_wait_end_fair(cfs_rq, se);
5186 __dequeue_entity(cfs_rq, se);
5187 update_load_avg(cfs_rq, se, UPDATE_TG);
5189 * HACK, stash a copy of deadline at the point of pick in vlag,
5190 * which isn't used until dequeue.
5192 se->vlag = se->deadline;
5195 update_stats_curr_start(cfs_rq, se);
5199 * Track our maximum slice length, if the CPU's load is at
5200 * least twice that of our own weight (i.e. dont track it
5201 * when there are only lesser-weight tasks around):
5203 if (schedstat_enabled() &&
5204 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5205 struct sched_statistics *stats;
5207 stats = __schedstats_from_se(se);
5208 __schedstat_set(stats->slice_max,
5209 max((u64)stats->slice_max,
5210 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5213 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5217 * Pick the next process, keeping these things in mind, in this order:
5218 * 1) keep things fair between processes/task groups
5219 * 2) pick the "next" process, since someone really wants that to run
5220 * 3) pick the "last" process, for cache locality
5221 * 4) do not run the "skip" process, if something else is available
5223 static struct sched_entity *
5224 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5227 * Enabling NEXT_BUDDY will affect latency but not fairness.
5229 if (sched_feat(NEXT_BUDDY) &&
5230 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5231 return cfs_rq->next;
5233 return pick_eevdf(cfs_rq);
5236 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5238 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5241 * If still on the runqueue then deactivate_task()
5242 * was not called and update_curr() has to be done:
5245 update_curr(cfs_rq);
5247 /* throttle cfs_rqs exceeding runtime */
5248 check_cfs_rq_runtime(cfs_rq);
5251 update_stats_wait_start_fair(cfs_rq, prev);
5252 /* Put 'current' back into the tree. */
5253 __enqueue_entity(cfs_rq, prev);
5254 /* in !on_rq case, update occurred at dequeue */
5255 update_load_avg(cfs_rq, prev, 0);
5257 cfs_rq->curr = NULL;
5261 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5264 * Update run-time statistics of the 'current'.
5266 update_curr(cfs_rq);
5269 * Ensure that runnable average is periodically updated.
5271 update_load_avg(cfs_rq, curr, UPDATE_TG);
5272 update_cfs_group(curr);
5274 #ifdef CONFIG_SCHED_HRTICK
5276 * queued ticks are scheduled to match the slice, so don't bother
5277 * validating it and just reschedule.
5280 resched_curr(rq_of(cfs_rq));
5284 * don't let the period tick interfere with the hrtick preemption
5286 if (!sched_feat(DOUBLE_TICK) &&
5287 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5293 /**************************************************
5294 * CFS bandwidth control machinery
5297 #ifdef CONFIG_CFS_BANDWIDTH
5299 #ifdef CONFIG_JUMP_LABEL
5300 static struct static_key __cfs_bandwidth_used;
5302 static inline bool cfs_bandwidth_used(void)
5304 return static_key_false(&__cfs_bandwidth_used);
5307 void cfs_bandwidth_usage_inc(void)
5309 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5312 void cfs_bandwidth_usage_dec(void)
5314 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5316 #else /* CONFIG_JUMP_LABEL */
5317 static bool cfs_bandwidth_used(void)
5322 void cfs_bandwidth_usage_inc(void) {}
5323 void cfs_bandwidth_usage_dec(void) {}
5324 #endif /* CONFIG_JUMP_LABEL */
5327 * default period for cfs group bandwidth.
5328 * default: 0.1s, units: nanoseconds
5330 static inline u64 default_cfs_period(void)
5332 return 100000000ULL;
5335 static inline u64 sched_cfs_bandwidth_slice(void)
5337 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5341 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5342 * directly instead of rq->clock to avoid adding additional synchronization
5345 * requires cfs_b->lock
5347 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5351 if (unlikely(cfs_b->quota == RUNTIME_INF))
5354 cfs_b->runtime += cfs_b->quota;
5355 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5357 cfs_b->burst_time += runtime;
5361 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5362 cfs_b->runtime_snap = cfs_b->runtime;
5365 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5367 return &tg->cfs_bandwidth;
5370 /* returns 0 on failure to allocate runtime */
5371 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5372 struct cfs_rq *cfs_rq, u64 target_runtime)
5374 u64 min_amount, amount = 0;
5376 lockdep_assert_held(&cfs_b->lock);
5378 /* note: this is a positive sum as runtime_remaining <= 0 */
5379 min_amount = target_runtime - cfs_rq->runtime_remaining;
5381 if (cfs_b->quota == RUNTIME_INF)
5382 amount = min_amount;
5384 start_cfs_bandwidth(cfs_b);
5386 if (cfs_b->runtime > 0) {
5387 amount = min(cfs_b->runtime, min_amount);
5388 cfs_b->runtime -= amount;
5393 cfs_rq->runtime_remaining += amount;
5395 return cfs_rq->runtime_remaining > 0;
5398 /* returns 0 on failure to allocate runtime */
5399 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5401 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5404 raw_spin_lock(&cfs_b->lock);
5405 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5406 raw_spin_unlock(&cfs_b->lock);
5411 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5413 /* dock delta_exec before expiring quota (as it could span periods) */
5414 cfs_rq->runtime_remaining -= delta_exec;
5416 if (likely(cfs_rq->runtime_remaining > 0))
5419 if (cfs_rq->throttled)
5422 * if we're unable to extend our runtime we resched so that the active
5423 * hierarchy can be throttled
5425 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5426 resched_curr(rq_of(cfs_rq));
5429 static __always_inline
5430 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5432 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5435 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5438 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5440 return cfs_bandwidth_used() && cfs_rq->throttled;
5443 /* check whether cfs_rq, or any parent, is throttled */
5444 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5446 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5450 * Ensure that neither of the group entities corresponding to src_cpu or
5451 * dest_cpu are members of a throttled hierarchy when performing group
5452 * load-balance operations.
5454 static inline int throttled_lb_pair(struct task_group *tg,
5455 int src_cpu, int dest_cpu)
5457 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5459 src_cfs_rq = tg->cfs_rq[src_cpu];
5460 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5462 return throttled_hierarchy(src_cfs_rq) ||
5463 throttled_hierarchy(dest_cfs_rq);
5466 static int tg_unthrottle_up(struct task_group *tg, void *data)
5468 struct rq *rq = data;
5469 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5471 cfs_rq->throttle_count--;
5472 if (!cfs_rq->throttle_count) {
5473 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5474 cfs_rq->throttled_clock_pelt;
5476 /* Add cfs_rq with load or one or more already running entities to the list */
5477 if (!cfs_rq_is_decayed(cfs_rq))
5478 list_add_leaf_cfs_rq(cfs_rq);
5480 if (cfs_rq->throttled_clock_self) {
5481 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5483 cfs_rq->throttled_clock_self = 0;
5485 if (SCHED_WARN_ON((s64)delta < 0))
5488 cfs_rq->throttled_clock_self_time += delta;
5495 static int tg_throttle_down(struct task_group *tg, void *data)
5497 struct rq *rq = data;
5498 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5500 /* group is entering throttled state, stop time */
5501 if (!cfs_rq->throttle_count) {
5502 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5503 list_del_leaf_cfs_rq(cfs_rq);
5505 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5506 if (cfs_rq->nr_running)
5507 cfs_rq->throttled_clock_self = rq_clock(rq);
5509 cfs_rq->throttle_count++;
5514 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5516 struct rq *rq = rq_of(cfs_rq);
5517 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5518 struct sched_entity *se;
5519 long task_delta, idle_task_delta, dequeue = 1;
5521 raw_spin_lock(&cfs_b->lock);
5522 /* This will start the period timer if necessary */
5523 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5525 * We have raced with bandwidth becoming available, and if we
5526 * actually throttled the timer might not unthrottle us for an
5527 * entire period. We additionally needed to make sure that any
5528 * subsequent check_cfs_rq_runtime calls agree not to throttle
5529 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5530 * for 1ns of runtime rather than just check cfs_b.
5534 list_add_tail_rcu(&cfs_rq->throttled_list,
5535 &cfs_b->throttled_cfs_rq);
5537 raw_spin_unlock(&cfs_b->lock);
5540 return false; /* Throttle no longer required. */
5542 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5544 /* freeze hierarchy runnable averages while throttled */
5546 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5549 task_delta = cfs_rq->h_nr_running;
5550 idle_task_delta = cfs_rq->idle_h_nr_running;
5551 for_each_sched_entity(se) {
5552 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5553 /* throttled entity or throttle-on-deactivate */
5557 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5559 if (cfs_rq_is_idle(group_cfs_rq(se)))
5560 idle_task_delta = cfs_rq->h_nr_running;
5562 qcfs_rq->h_nr_running -= task_delta;
5563 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5565 if (qcfs_rq->load.weight) {
5566 /* Avoid re-evaluating load for this entity: */
5567 se = parent_entity(se);
5572 for_each_sched_entity(se) {
5573 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5574 /* throttled entity or throttle-on-deactivate */
5578 update_load_avg(qcfs_rq, se, 0);
5579 se_update_runnable(se);
5581 if (cfs_rq_is_idle(group_cfs_rq(se)))
5582 idle_task_delta = cfs_rq->h_nr_running;
5584 qcfs_rq->h_nr_running -= task_delta;
5585 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5588 /* At this point se is NULL and we are at root level*/
5589 sub_nr_running(rq, task_delta);
5593 * Note: distribution will already see us throttled via the
5594 * throttled-list. rq->lock protects completion.
5596 cfs_rq->throttled = 1;
5597 SCHED_WARN_ON(cfs_rq->throttled_clock);
5598 if (cfs_rq->nr_running)
5599 cfs_rq->throttled_clock = rq_clock(rq);
5603 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5605 struct rq *rq = rq_of(cfs_rq);
5606 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5607 struct sched_entity *se;
5608 long task_delta, idle_task_delta;
5610 se = cfs_rq->tg->se[cpu_of(rq)];
5612 cfs_rq->throttled = 0;
5614 update_rq_clock(rq);
5616 raw_spin_lock(&cfs_b->lock);
5617 if (cfs_rq->throttled_clock) {
5618 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5619 cfs_rq->throttled_clock = 0;
5621 list_del_rcu(&cfs_rq->throttled_list);
5622 raw_spin_unlock(&cfs_b->lock);
5624 /* update hierarchical throttle state */
5625 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5627 if (!cfs_rq->load.weight) {
5628 if (!cfs_rq->on_list)
5631 * Nothing to run but something to decay (on_list)?
5632 * Complete the branch.
5634 for_each_sched_entity(se) {
5635 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5638 goto unthrottle_throttle;
5641 task_delta = cfs_rq->h_nr_running;
5642 idle_task_delta = cfs_rq->idle_h_nr_running;
5643 for_each_sched_entity(se) {
5644 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5648 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5650 if (cfs_rq_is_idle(group_cfs_rq(se)))
5651 idle_task_delta = cfs_rq->h_nr_running;
5653 qcfs_rq->h_nr_running += task_delta;
5654 qcfs_rq->idle_h_nr_running += idle_task_delta;
5656 /* end evaluation on encountering a throttled cfs_rq */
5657 if (cfs_rq_throttled(qcfs_rq))
5658 goto unthrottle_throttle;
5661 for_each_sched_entity(se) {
5662 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5664 update_load_avg(qcfs_rq, se, UPDATE_TG);
5665 se_update_runnable(se);
5667 if (cfs_rq_is_idle(group_cfs_rq(se)))
5668 idle_task_delta = cfs_rq->h_nr_running;
5670 qcfs_rq->h_nr_running += task_delta;
5671 qcfs_rq->idle_h_nr_running += idle_task_delta;
5673 /* end evaluation on encountering a throttled cfs_rq */
5674 if (cfs_rq_throttled(qcfs_rq))
5675 goto unthrottle_throttle;
5678 /* At this point se is NULL and we are at root level*/
5679 add_nr_running(rq, task_delta);
5681 unthrottle_throttle:
5682 assert_list_leaf_cfs_rq(rq);
5684 /* Determine whether we need to wake up potentially idle CPU: */
5685 if (rq->curr == rq->idle && rq->cfs.nr_running)
5690 static void __cfsb_csd_unthrottle(void *arg)
5692 struct cfs_rq *cursor, *tmp;
5693 struct rq *rq = arg;
5699 * Iterating over the list can trigger several call to
5700 * update_rq_clock() in unthrottle_cfs_rq().
5701 * Do it once and skip the potential next ones.
5703 update_rq_clock(rq);
5704 rq_clock_start_loop_update(rq);
5707 * Since we hold rq lock we're safe from concurrent manipulation of
5708 * the CSD list. However, this RCU critical section annotates the
5709 * fact that we pair with sched_free_group_rcu(), so that we cannot
5710 * race with group being freed in the window between removing it
5711 * from the list and advancing to the next entry in the list.
5715 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5716 throttled_csd_list) {
5717 list_del_init(&cursor->throttled_csd_list);
5719 if (cfs_rq_throttled(cursor))
5720 unthrottle_cfs_rq(cursor);
5725 rq_clock_stop_loop_update(rq);
5729 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5731 struct rq *rq = rq_of(cfs_rq);
5734 if (rq == this_rq()) {
5735 unthrottle_cfs_rq(cfs_rq);
5739 /* Already enqueued */
5740 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5743 first = list_empty(&rq->cfsb_csd_list);
5744 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5746 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5749 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5751 unthrottle_cfs_rq(cfs_rq);
5755 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5757 lockdep_assert_rq_held(rq_of(cfs_rq));
5759 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5760 cfs_rq->runtime_remaining <= 0))
5763 __unthrottle_cfs_rq_async(cfs_rq);
5766 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5768 struct cfs_rq *local_unthrottle = NULL;
5769 int this_cpu = smp_processor_id();
5770 u64 runtime, remaining = 1;
5771 bool throttled = false;
5772 struct cfs_rq *cfs_rq;
5777 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5786 rq_lock_irqsave(rq, &rf);
5787 if (!cfs_rq_throttled(cfs_rq))
5791 /* Already queued for async unthrottle */
5792 if (!list_empty(&cfs_rq->throttled_csd_list))
5796 /* By the above checks, this should never be true */
5797 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5799 raw_spin_lock(&cfs_b->lock);
5800 runtime = -cfs_rq->runtime_remaining + 1;
5801 if (runtime > cfs_b->runtime)
5802 runtime = cfs_b->runtime;
5803 cfs_b->runtime -= runtime;
5804 remaining = cfs_b->runtime;
5805 raw_spin_unlock(&cfs_b->lock);
5807 cfs_rq->runtime_remaining += runtime;
5809 /* we check whether we're throttled above */
5810 if (cfs_rq->runtime_remaining > 0) {
5811 if (cpu_of(rq) != this_cpu ||
5812 SCHED_WARN_ON(local_unthrottle))
5813 unthrottle_cfs_rq_async(cfs_rq);
5815 local_unthrottle = cfs_rq;
5821 rq_unlock_irqrestore(rq, &rf);
5825 if (local_unthrottle) {
5826 rq = cpu_rq(this_cpu);
5827 rq_lock_irqsave(rq, &rf);
5828 if (cfs_rq_throttled(local_unthrottle))
5829 unthrottle_cfs_rq(local_unthrottle);
5830 rq_unlock_irqrestore(rq, &rf);
5837 * Responsible for refilling a task_group's bandwidth and unthrottling its
5838 * cfs_rqs as appropriate. If there has been no activity within the last
5839 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5840 * used to track this state.
5842 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5846 /* no need to continue the timer with no bandwidth constraint */
5847 if (cfs_b->quota == RUNTIME_INF)
5848 goto out_deactivate;
5850 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5851 cfs_b->nr_periods += overrun;
5853 /* Refill extra burst quota even if cfs_b->idle */
5854 __refill_cfs_bandwidth_runtime(cfs_b);
5857 * idle depends on !throttled (for the case of a large deficit), and if
5858 * we're going inactive then everything else can be deferred
5860 if (cfs_b->idle && !throttled)
5861 goto out_deactivate;
5864 /* mark as potentially idle for the upcoming period */
5869 /* account preceding periods in which throttling occurred */
5870 cfs_b->nr_throttled += overrun;
5873 * This check is repeated as we release cfs_b->lock while we unthrottle.
5875 while (throttled && cfs_b->runtime > 0) {
5876 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5877 /* we can't nest cfs_b->lock while distributing bandwidth */
5878 throttled = distribute_cfs_runtime(cfs_b);
5879 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5883 * While we are ensured activity in the period following an
5884 * unthrottle, this also covers the case in which the new bandwidth is
5885 * insufficient to cover the existing bandwidth deficit. (Forcing the
5886 * timer to remain active while there are any throttled entities.)
5896 /* a cfs_rq won't donate quota below this amount */
5897 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5898 /* minimum remaining period time to redistribute slack quota */
5899 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5900 /* how long we wait to gather additional slack before distributing */
5901 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5904 * Are we near the end of the current quota period?
5906 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5907 * hrtimer base being cleared by hrtimer_start. In the case of
5908 * migrate_hrtimers, base is never cleared, so we are fine.
5910 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5912 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5915 /* if the call-back is running a quota refresh is already occurring */
5916 if (hrtimer_callback_running(refresh_timer))
5919 /* is a quota refresh about to occur? */
5920 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5921 if (remaining < (s64)min_expire)
5927 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5929 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5931 /* if there's a quota refresh soon don't bother with slack */
5932 if (runtime_refresh_within(cfs_b, min_left))
5935 /* don't push forwards an existing deferred unthrottle */
5936 if (cfs_b->slack_started)
5938 cfs_b->slack_started = true;
5940 hrtimer_start(&cfs_b->slack_timer,
5941 ns_to_ktime(cfs_bandwidth_slack_period),
5945 /* we know any runtime found here is valid as update_curr() precedes return */
5946 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5948 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5949 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5951 if (slack_runtime <= 0)
5954 raw_spin_lock(&cfs_b->lock);
5955 if (cfs_b->quota != RUNTIME_INF) {
5956 cfs_b->runtime += slack_runtime;
5958 /* we are under rq->lock, defer unthrottling using a timer */
5959 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5960 !list_empty(&cfs_b->throttled_cfs_rq))
5961 start_cfs_slack_bandwidth(cfs_b);
5963 raw_spin_unlock(&cfs_b->lock);
5965 /* even if it's not valid for return we don't want to try again */
5966 cfs_rq->runtime_remaining -= slack_runtime;
5969 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5971 if (!cfs_bandwidth_used())
5974 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
5977 __return_cfs_rq_runtime(cfs_rq);
5981 * This is done with a timer (instead of inline with bandwidth return) since
5982 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5984 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5986 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
5987 unsigned long flags;
5989 /* confirm we're still not at a refresh boundary */
5990 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5991 cfs_b->slack_started = false;
5993 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
5994 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5998 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
5999 runtime = cfs_b->runtime;
6001 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6006 distribute_cfs_runtime(cfs_b);
6010 * When a group wakes up we want to make sure that its quota is not already
6011 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6012 * runtime as update_curr() throttling can not trigger until it's on-rq.
6014 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6016 if (!cfs_bandwidth_used())
6019 /* an active group must be handled by the update_curr()->put() path */
6020 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6023 /* ensure the group is not already throttled */
6024 if (cfs_rq_throttled(cfs_rq))
6027 /* update runtime allocation */
6028 account_cfs_rq_runtime(cfs_rq, 0);
6029 if (cfs_rq->runtime_remaining <= 0)
6030 throttle_cfs_rq(cfs_rq);
6033 static void sync_throttle(struct task_group *tg, int cpu)
6035 struct cfs_rq *pcfs_rq, *cfs_rq;
6037 if (!cfs_bandwidth_used())
6043 cfs_rq = tg->cfs_rq[cpu];
6044 pcfs_rq = tg->parent->cfs_rq[cpu];
6046 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6047 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6050 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6051 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6053 if (!cfs_bandwidth_used())
6056 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6060 * it's possible for a throttled entity to be forced into a running
6061 * state (e.g. set_curr_task), in this case we're finished.
6063 if (cfs_rq_throttled(cfs_rq))
6066 return throttle_cfs_rq(cfs_rq);
6069 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6071 struct cfs_bandwidth *cfs_b =
6072 container_of(timer, struct cfs_bandwidth, slack_timer);
6074 do_sched_cfs_slack_timer(cfs_b);
6076 return HRTIMER_NORESTART;
6079 extern const u64 max_cfs_quota_period;
6081 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6083 struct cfs_bandwidth *cfs_b =
6084 container_of(timer, struct cfs_bandwidth, period_timer);
6085 unsigned long flags;
6090 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6092 overrun = hrtimer_forward_now(timer, cfs_b->period);
6096 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6099 u64 new, old = ktime_to_ns(cfs_b->period);
6102 * Grow period by a factor of 2 to avoid losing precision.
6103 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6107 if (new < max_cfs_quota_period) {
6108 cfs_b->period = ns_to_ktime(new);
6112 pr_warn_ratelimited(
6113 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6115 div_u64(new, NSEC_PER_USEC),
6116 div_u64(cfs_b->quota, NSEC_PER_USEC));
6118 pr_warn_ratelimited(
6119 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6121 div_u64(old, NSEC_PER_USEC),
6122 div_u64(cfs_b->quota, NSEC_PER_USEC));
6125 /* reset count so we don't come right back in here */
6130 cfs_b->period_active = 0;
6131 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6133 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6136 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6138 raw_spin_lock_init(&cfs_b->lock);
6140 cfs_b->quota = RUNTIME_INF;
6141 cfs_b->period = ns_to_ktime(default_cfs_period());
6143 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6145 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6146 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6147 cfs_b->period_timer.function = sched_cfs_period_timer;
6149 /* Add a random offset so that timers interleave */
6150 hrtimer_set_expires(&cfs_b->period_timer,
6151 get_random_u32_below(cfs_b->period));
6152 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6153 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6154 cfs_b->slack_started = false;
6157 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6159 cfs_rq->runtime_enabled = 0;
6160 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6162 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6166 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6168 lockdep_assert_held(&cfs_b->lock);
6170 if (cfs_b->period_active)
6173 cfs_b->period_active = 1;
6174 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6175 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6178 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6180 int __maybe_unused i;
6182 /* init_cfs_bandwidth() was not called */
6183 if (!cfs_b->throttled_cfs_rq.next)
6186 hrtimer_cancel(&cfs_b->period_timer);
6187 hrtimer_cancel(&cfs_b->slack_timer);
6190 * It is possible that we still have some cfs_rq's pending on a CSD
6191 * list, though this race is very rare. In order for this to occur, we
6192 * must have raced with the last task leaving the group while there
6193 * exist throttled cfs_rq(s), and the period_timer must have queued the
6194 * CSD item but the remote cpu has not yet processed it. To handle this,
6195 * we can simply flush all pending CSD work inline here. We're
6196 * guaranteed at this point that no additional cfs_rq of this group can
6200 for_each_possible_cpu(i) {
6201 struct rq *rq = cpu_rq(i);
6202 unsigned long flags;
6204 if (list_empty(&rq->cfsb_csd_list))
6207 local_irq_save(flags);
6208 __cfsb_csd_unthrottle(rq);
6209 local_irq_restore(flags);
6215 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6217 * The race is harmless, since modifying bandwidth settings of unhooked group
6218 * bits doesn't do much.
6221 /* cpu online callback */
6222 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6224 struct task_group *tg;
6226 lockdep_assert_rq_held(rq);
6229 list_for_each_entry_rcu(tg, &task_groups, list) {
6230 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6231 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6233 raw_spin_lock(&cfs_b->lock);
6234 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6235 raw_spin_unlock(&cfs_b->lock);
6240 /* cpu offline callback */
6241 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6243 struct task_group *tg;
6245 lockdep_assert_rq_held(rq);
6248 * The rq clock has already been updated in the
6249 * set_rq_offline(), so we should skip updating
6250 * the rq clock again in unthrottle_cfs_rq().
6252 rq_clock_start_loop_update(rq);
6255 list_for_each_entry_rcu(tg, &task_groups, list) {
6256 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6258 if (!cfs_rq->runtime_enabled)
6262 * clock_task is not advancing so we just need to make sure
6263 * there's some valid quota amount
6265 cfs_rq->runtime_remaining = 1;
6267 * Offline rq is schedulable till CPU is completely disabled
6268 * in take_cpu_down(), so we prevent new cfs throttling here.
6270 cfs_rq->runtime_enabled = 0;
6272 if (cfs_rq_throttled(cfs_rq))
6273 unthrottle_cfs_rq(cfs_rq);
6277 rq_clock_stop_loop_update(rq);
6280 bool cfs_task_bw_constrained(struct task_struct *p)
6282 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6284 if (!cfs_bandwidth_used())
6287 if (cfs_rq->runtime_enabled ||
6288 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6294 #ifdef CONFIG_NO_HZ_FULL
6295 /* called from pick_next_task_fair() */
6296 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6298 int cpu = cpu_of(rq);
6300 if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6303 if (!tick_nohz_full_cpu(cpu))
6306 if (rq->nr_running != 1)
6310 * We know there is only one task runnable and we've just picked it. The
6311 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6312 * be otherwise able to stop the tick. Just need to check if we are using
6313 * bandwidth control.
6315 if (cfs_task_bw_constrained(p))
6316 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6320 #else /* CONFIG_CFS_BANDWIDTH */
6322 static inline bool cfs_bandwidth_used(void)
6327 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6328 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6329 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6330 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6331 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6333 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6338 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6343 static inline int throttled_lb_pair(struct task_group *tg,
6344 int src_cpu, int dest_cpu)
6349 #ifdef CONFIG_FAIR_GROUP_SCHED
6350 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6351 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6354 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6358 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6359 static inline void update_runtime_enabled(struct rq *rq) {}
6360 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6361 #ifdef CONFIG_CGROUP_SCHED
6362 bool cfs_task_bw_constrained(struct task_struct *p)
6367 #endif /* CONFIG_CFS_BANDWIDTH */
6369 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6370 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6373 /**************************************************
6374 * CFS operations on tasks:
6377 #ifdef CONFIG_SCHED_HRTICK
6378 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6380 struct sched_entity *se = &p->se;
6382 SCHED_WARN_ON(task_rq(p) != rq);
6384 if (rq->cfs.h_nr_running > 1) {
6385 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6386 u64 slice = se->slice;
6387 s64 delta = slice - ran;
6390 if (task_current(rq, p))
6394 hrtick_start(rq, delta);
6399 * called from enqueue/dequeue and updates the hrtick when the
6400 * current task is from our class and nr_running is low enough
6403 static void hrtick_update(struct rq *rq)
6405 struct task_struct *curr = rq->curr;
6407 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6410 hrtick_start_fair(rq, curr);
6412 #else /* !CONFIG_SCHED_HRTICK */
6414 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6418 static inline void hrtick_update(struct rq *rq)
6424 static inline bool cpu_overutilized(int cpu)
6426 unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6427 unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6429 /* Return true only if the utilization doesn't fit CPU's capacity */
6430 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6433 static inline void update_overutilized_status(struct rq *rq)
6435 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6436 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6437 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6441 static inline void update_overutilized_status(struct rq *rq) { }
6444 /* Runqueue only has SCHED_IDLE tasks enqueued */
6445 static int sched_idle_rq(struct rq *rq)
6447 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6452 static int sched_idle_cpu(int cpu)
6454 return sched_idle_rq(cpu_rq(cpu));
6459 * The enqueue_task method is called before nr_running is
6460 * increased. Here we update the fair scheduling stats and
6461 * then put the task into the rbtree:
6464 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6466 struct cfs_rq *cfs_rq;
6467 struct sched_entity *se = &p->se;
6468 int idle_h_nr_running = task_has_idle_policy(p);
6469 int task_new = !(flags & ENQUEUE_WAKEUP);
6472 * The code below (indirectly) updates schedutil which looks at
6473 * the cfs_rq utilization to select a frequency.
6474 * Let's add the task's estimated utilization to the cfs_rq's
6475 * estimated utilization, before we update schedutil.
6477 util_est_enqueue(&rq->cfs, p);
6480 * If in_iowait is set, the code below may not trigger any cpufreq
6481 * utilization updates, so do it here explicitly with the IOWAIT flag
6485 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6487 for_each_sched_entity(se) {
6490 cfs_rq = cfs_rq_of(se);
6491 enqueue_entity(cfs_rq, se, flags);
6493 cfs_rq->h_nr_running++;
6494 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6496 if (cfs_rq_is_idle(cfs_rq))
6497 idle_h_nr_running = 1;
6499 /* end evaluation on encountering a throttled cfs_rq */
6500 if (cfs_rq_throttled(cfs_rq))
6501 goto enqueue_throttle;
6503 flags = ENQUEUE_WAKEUP;
6506 for_each_sched_entity(se) {
6507 cfs_rq = cfs_rq_of(se);
6509 update_load_avg(cfs_rq, se, UPDATE_TG);
6510 se_update_runnable(se);
6511 update_cfs_group(se);
6513 cfs_rq->h_nr_running++;
6514 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6516 if (cfs_rq_is_idle(cfs_rq))
6517 idle_h_nr_running = 1;
6519 /* end evaluation on encountering a throttled cfs_rq */
6520 if (cfs_rq_throttled(cfs_rq))
6521 goto enqueue_throttle;
6524 /* At this point se is NULL and we are at root level*/
6525 add_nr_running(rq, 1);
6528 * Since new tasks are assigned an initial util_avg equal to
6529 * half of the spare capacity of their CPU, tiny tasks have the
6530 * ability to cross the overutilized threshold, which will
6531 * result in the load balancer ruining all the task placement
6532 * done by EAS. As a way to mitigate that effect, do not account
6533 * for the first enqueue operation of new tasks during the
6534 * overutilized flag detection.
6536 * A better way of solving this problem would be to wait for
6537 * the PELT signals of tasks to converge before taking them
6538 * into account, but that is not straightforward to implement,
6539 * and the following generally works well enough in practice.
6542 update_overutilized_status(rq);
6545 assert_list_leaf_cfs_rq(rq);
6550 static void set_next_buddy(struct sched_entity *se);
6553 * The dequeue_task method is called before nr_running is
6554 * decreased. We remove the task from the rbtree and
6555 * update the fair scheduling stats:
6557 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6559 struct cfs_rq *cfs_rq;
6560 struct sched_entity *se = &p->se;
6561 int task_sleep = flags & DEQUEUE_SLEEP;
6562 int idle_h_nr_running = task_has_idle_policy(p);
6563 bool was_sched_idle = sched_idle_rq(rq);
6565 util_est_dequeue(&rq->cfs, p);
6567 for_each_sched_entity(se) {
6568 cfs_rq = cfs_rq_of(se);
6569 dequeue_entity(cfs_rq, se, flags);
6571 cfs_rq->h_nr_running--;
6572 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6574 if (cfs_rq_is_idle(cfs_rq))
6575 idle_h_nr_running = 1;
6577 /* end evaluation on encountering a throttled cfs_rq */
6578 if (cfs_rq_throttled(cfs_rq))
6579 goto dequeue_throttle;
6581 /* Don't dequeue parent if it has other entities besides us */
6582 if (cfs_rq->load.weight) {
6583 /* Avoid re-evaluating load for this entity: */
6584 se = parent_entity(se);
6586 * Bias pick_next to pick a task from this cfs_rq, as
6587 * p is sleeping when it is within its sched_slice.
6589 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6593 flags |= DEQUEUE_SLEEP;
6596 for_each_sched_entity(se) {
6597 cfs_rq = cfs_rq_of(se);
6599 update_load_avg(cfs_rq, se, UPDATE_TG);
6600 se_update_runnable(se);
6601 update_cfs_group(se);
6603 cfs_rq->h_nr_running--;
6604 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6606 if (cfs_rq_is_idle(cfs_rq))
6607 idle_h_nr_running = 1;
6609 /* end evaluation on encountering a throttled cfs_rq */
6610 if (cfs_rq_throttled(cfs_rq))
6611 goto dequeue_throttle;
6615 /* At this point se is NULL and we are at root level*/
6616 sub_nr_running(rq, 1);
6618 /* balance early to pull high priority tasks */
6619 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6620 rq->next_balance = jiffies;
6623 util_est_update(&rq->cfs, p, task_sleep);
6629 /* Working cpumask for: load_balance, load_balance_newidle. */
6630 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6631 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6632 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6634 #ifdef CONFIG_NO_HZ_COMMON
6637 cpumask_var_t idle_cpus_mask;
6639 int has_blocked; /* Idle CPUS has blocked load */
6640 int needs_update; /* Newly idle CPUs need their next_balance collated */
6641 unsigned long next_balance; /* in jiffy units */
6642 unsigned long next_blocked; /* Next update of blocked load in jiffies */
6643 } nohz ____cacheline_aligned;
6645 #endif /* CONFIG_NO_HZ_COMMON */
6647 static unsigned long cpu_load(struct rq *rq)
6649 return cfs_rq_load_avg(&rq->cfs);
6653 * cpu_load_without - compute CPU load without any contributions from *p
6654 * @cpu: the CPU which load is requested
6655 * @p: the task which load should be discounted
6657 * The load of a CPU is defined by the load of tasks currently enqueued on that
6658 * CPU as well as tasks which are currently sleeping after an execution on that
6661 * This method returns the load of the specified CPU by discounting the load of
6662 * the specified task, whenever the task is currently contributing to the CPU
6665 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6667 struct cfs_rq *cfs_rq;
6670 /* Task has no contribution or is new */
6671 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6672 return cpu_load(rq);
6675 load = READ_ONCE(cfs_rq->avg.load_avg);
6677 /* Discount task's util from CPU's util */
6678 lsub_positive(&load, task_h_load(p));
6683 static unsigned long cpu_runnable(struct rq *rq)
6685 return cfs_rq_runnable_avg(&rq->cfs);
6688 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6690 struct cfs_rq *cfs_rq;
6691 unsigned int runnable;
6693 /* Task has no contribution or is new */
6694 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6695 return cpu_runnable(rq);
6698 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6700 /* Discount task's runnable from CPU's runnable */
6701 lsub_positive(&runnable, p->se.avg.runnable_avg);
6706 static unsigned long capacity_of(int cpu)
6708 return cpu_rq(cpu)->cpu_capacity;
6711 static void record_wakee(struct task_struct *p)
6714 * Only decay a single time; tasks that have less then 1 wakeup per
6715 * jiffy will not have built up many flips.
6717 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6718 current->wakee_flips >>= 1;
6719 current->wakee_flip_decay_ts = jiffies;
6722 if (current->last_wakee != p) {
6723 current->last_wakee = p;
6724 current->wakee_flips++;
6729 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6731 * A waker of many should wake a different task than the one last awakened
6732 * at a frequency roughly N times higher than one of its wakees.
6734 * In order to determine whether we should let the load spread vs consolidating
6735 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6736 * partner, and a factor of lls_size higher frequency in the other.
6738 * With both conditions met, we can be relatively sure that the relationship is
6739 * non-monogamous, with partner count exceeding socket size.
6741 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6742 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6745 static int wake_wide(struct task_struct *p)
6747 unsigned int master = current->wakee_flips;
6748 unsigned int slave = p->wakee_flips;
6749 int factor = __this_cpu_read(sd_llc_size);
6752 swap(master, slave);
6753 if (slave < factor || master < slave * factor)
6759 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6760 * soonest. For the purpose of speed we only consider the waking and previous
6763 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6764 * cache-affine and is (or will be) idle.
6766 * wake_affine_weight() - considers the weight to reflect the average
6767 * scheduling latency of the CPUs. This seems to work
6768 * for the overloaded case.
6771 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6774 * If this_cpu is idle, it implies the wakeup is from interrupt
6775 * context. Only allow the move if cache is shared. Otherwise an
6776 * interrupt intensive workload could force all tasks onto one
6777 * node depending on the IO topology or IRQ affinity settings.
6779 * If the prev_cpu is idle and cache affine then avoid a migration.
6780 * There is no guarantee that the cache hot data from an interrupt
6781 * is more important than cache hot data on the prev_cpu and from
6782 * a cpufreq perspective, it's better to have higher utilisation
6785 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6786 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6788 if (sync && cpu_rq(this_cpu)->nr_running == 1)
6791 if (available_idle_cpu(prev_cpu))
6794 return nr_cpumask_bits;
6798 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6799 int this_cpu, int prev_cpu, int sync)
6801 s64 this_eff_load, prev_eff_load;
6802 unsigned long task_load;
6804 this_eff_load = cpu_load(cpu_rq(this_cpu));
6807 unsigned long current_load = task_h_load(current);
6809 if (current_load > this_eff_load)
6812 this_eff_load -= current_load;
6815 task_load = task_h_load(p);
6817 this_eff_load += task_load;
6818 if (sched_feat(WA_BIAS))
6819 this_eff_load *= 100;
6820 this_eff_load *= capacity_of(prev_cpu);
6822 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
6823 prev_eff_load -= task_load;
6824 if (sched_feat(WA_BIAS))
6825 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
6826 prev_eff_load *= capacity_of(this_cpu);
6829 * If sync, adjust the weight of prev_eff_load such that if
6830 * prev_eff == this_eff that select_idle_sibling() will consider
6831 * stacking the wakee on top of the waker if no other CPU is
6837 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6840 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6841 int this_cpu, int prev_cpu, int sync)
6843 int target = nr_cpumask_bits;
6845 if (sched_feat(WA_IDLE))
6846 target = wake_affine_idle(this_cpu, prev_cpu, sync);
6848 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6849 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6851 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
6852 if (target != this_cpu)
6855 schedstat_inc(sd->ttwu_move_affine);
6856 schedstat_inc(p->stats.nr_wakeups_affine);
6860 static struct sched_group *
6861 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6864 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6867 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6869 unsigned long load, min_load = ULONG_MAX;
6870 unsigned int min_exit_latency = UINT_MAX;
6871 u64 latest_idle_timestamp = 0;
6872 int least_loaded_cpu = this_cpu;
6873 int shallowest_idle_cpu = -1;
6876 /* Check if we have any choice: */
6877 if (group->group_weight == 1)
6878 return cpumask_first(sched_group_span(group));
6880 /* Traverse only the allowed CPUs */
6881 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6882 struct rq *rq = cpu_rq(i);
6884 if (!sched_core_cookie_match(rq, p))
6887 if (sched_idle_cpu(i))
6890 if (available_idle_cpu(i)) {
6891 struct cpuidle_state *idle = idle_get_state(rq);
6892 if (idle && idle->exit_latency < min_exit_latency) {
6894 * We give priority to a CPU whose idle state
6895 * has the smallest exit latency irrespective
6896 * of any idle timestamp.
6898 min_exit_latency = idle->exit_latency;
6899 latest_idle_timestamp = rq->idle_stamp;
6900 shallowest_idle_cpu = i;
6901 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6902 rq->idle_stamp > latest_idle_timestamp) {
6904 * If equal or no active idle state, then
6905 * the most recently idled CPU might have
6908 latest_idle_timestamp = rq->idle_stamp;
6909 shallowest_idle_cpu = i;
6911 } else if (shallowest_idle_cpu == -1) {
6912 load = cpu_load(cpu_rq(i));
6913 if (load < min_load) {
6915 least_loaded_cpu = i;
6920 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6923 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6924 int cpu, int prev_cpu, int sd_flag)
6928 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6932 * We need task's util for cpu_util_without, sync it up to
6933 * prev_cpu's last_update_time.
6935 if (!(sd_flag & SD_BALANCE_FORK))
6936 sync_entity_load_avg(&p->se);
6939 struct sched_group *group;
6940 struct sched_domain *tmp;
6943 if (!(sd->flags & sd_flag)) {
6948 group = find_idlest_group(sd, p, cpu);
6954 new_cpu = find_idlest_group_cpu(group, p, cpu);
6955 if (new_cpu == cpu) {
6956 /* Now try balancing at a lower domain level of 'cpu': */
6961 /* Now try balancing at a lower domain level of 'new_cpu': */
6963 weight = sd->span_weight;
6965 for_each_domain(cpu, tmp) {
6966 if (weight <= tmp->span_weight)
6968 if (tmp->flags & sd_flag)
6976 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
6978 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
6979 sched_cpu_cookie_match(cpu_rq(cpu), p))
6985 #ifdef CONFIG_SCHED_SMT
6986 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6987 EXPORT_SYMBOL_GPL(sched_smt_present);
6989 static inline void set_idle_cores(int cpu, int val)
6991 struct sched_domain_shared *sds;
6993 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6995 WRITE_ONCE(sds->has_idle_cores, val);
6998 static inline bool test_idle_cores(int cpu)
7000 struct sched_domain_shared *sds;
7002 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7004 return READ_ONCE(sds->has_idle_cores);
7010 * Scans the local SMT mask to see if the entire core is idle, and records this
7011 * information in sd_llc_shared->has_idle_cores.
7013 * Since SMT siblings share all cache levels, inspecting this limited remote
7014 * state should be fairly cheap.
7016 void __update_idle_core(struct rq *rq)
7018 int core = cpu_of(rq);
7022 if (test_idle_cores(core))
7025 for_each_cpu(cpu, cpu_smt_mask(core)) {
7029 if (!available_idle_cpu(cpu))
7033 set_idle_cores(core, 1);
7039 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7040 * there are no idle cores left in the system; tracked through
7041 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7043 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7048 for_each_cpu(cpu, cpu_smt_mask(core)) {
7049 if (!available_idle_cpu(cpu)) {
7051 if (*idle_cpu == -1) {
7052 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
7060 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
7067 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7072 * Scan the local SMT mask for idle CPUs.
7074 static int select_idle_smt(struct task_struct *p, int target)
7078 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7081 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7088 #else /* CONFIG_SCHED_SMT */
7090 static inline void set_idle_cores(int cpu, int val)
7094 static inline bool test_idle_cores(int cpu)
7099 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7101 return __select_idle_cpu(core, p);
7104 static inline int select_idle_smt(struct task_struct *p, int target)
7109 #endif /* CONFIG_SCHED_SMT */
7112 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7113 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7114 * average idle time for this rq (as found in rq->avg_idle).
7116 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7118 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7119 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7120 struct sched_domain_shared *sd_share;
7121 struct rq *this_rq = this_rq();
7122 int this = smp_processor_id();
7123 struct sched_domain *this_sd = NULL;
7126 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7128 if (sched_feat(SIS_PROP) && !has_idle_core) {
7129 u64 avg_cost, avg_idle, span_avg;
7130 unsigned long now = jiffies;
7132 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7137 * If we're busy, the assumption that the last idle period
7138 * predicts the future is flawed; age away the remaining
7139 * predicted idle time.
7141 if (unlikely(this_rq->wake_stamp < now)) {
7142 while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7143 this_rq->wake_stamp++;
7144 this_rq->wake_avg_idle >>= 1;
7148 avg_idle = this_rq->wake_avg_idle;
7149 avg_cost = this_sd->avg_scan_cost + 1;
7151 span_avg = sd->span_weight * avg_idle;
7152 if (span_avg > 4*avg_cost)
7153 nr = div_u64(span_avg, avg_cost);
7157 time = cpu_clock(this);
7160 if (sched_feat(SIS_UTIL)) {
7161 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7163 /* because !--nr is the condition to stop scan */
7164 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7165 /* overloaded LLC is unlikely to have idle cpu/core */
7171 for_each_cpu_wrap(cpu, cpus, target + 1) {
7172 if (has_idle_core) {
7173 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7174 if ((unsigned int)i < nr_cpumask_bits)
7180 idle_cpu = __select_idle_cpu(cpu, p);
7181 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7187 set_idle_cores(target, false);
7189 if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7190 time = cpu_clock(this) - time;
7193 * Account for the scan cost of wakeups against the average
7196 this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7198 update_avg(&this_sd->avg_scan_cost, time);
7205 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7206 * the task fits. If no CPU is big enough, but there are idle ones, try to
7207 * maximize capacity.
7210 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7212 unsigned long task_util, util_min, util_max, best_cap = 0;
7213 int fits, best_fits = 0;
7214 int cpu, best_cpu = -1;
7215 struct cpumask *cpus;
7217 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7218 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7220 task_util = task_util_est(p);
7221 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7222 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7224 for_each_cpu_wrap(cpu, cpus, target) {
7225 unsigned long cpu_cap = capacity_of(cpu);
7227 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7230 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7232 /* This CPU fits with all requirements */
7236 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7237 * Look for the CPU with best capacity.
7240 cpu_cap = capacity_orig_of(cpu) - thermal_load_avg(cpu_rq(cpu));
7243 * First, select CPU which fits better (-1 being better than 0).
7244 * Then, select the one with best capacity at same level.
7246 if ((fits < best_fits) ||
7247 ((fits == best_fits) && (cpu_cap > best_cap))) {
7257 static inline bool asym_fits_cpu(unsigned long util,
7258 unsigned long util_min,
7259 unsigned long util_max,
7262 if (sched_asym_cpucap_active())
7264 * Return true only if the cpu fully fits the task requirements
7265 * which include the utilization and the performance hints.
7267 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7273 * Try and locate an idle core/thread in the LLC cache domain.
7275 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7277 bool has_idle_core = false;
7278 struct sched_domain *sd;
7279 unsigned long task_util, util_min, util_max;
7280 int i, recent_used_cpu;
7283 * On asymmetric system, update task utilization because we will check
7284 * that the task fits with cpu's capacity.
7286 if (sched_asym_cpucap_active()) {
7287 sync_entity_load_avg(&p->se);
7288 task_util = task_util_est(p);
7289 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7290 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7294 * per-cpu select_rq_mask usage
7296 lockdep_assert_irqs_disabled();
7298 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7299 asym_fits_cpu(task_util, util_min, util_max, target))
7303 * If the previous CPU is cache affine and idle, don't be stupid:
7305 if (prev != target && cpus_share_cache(prev, target) &&
7306 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7307 asym_fits_cpu(task_util, util_min, util_max, prev))
7311 * Allow a per-cpu kthread to stack with the wakee if the
7312 * kworker thread and the tasks previous CPUs are the same.
7313 * The assumption is that the wakee queued work for the
7314 * per-cpu kthread that is now complete and the wakeup is
7315 * essentially a sync wakeup. An obvious example of this
7316 * pattern is IO completions.
7318 if (is_per_cpu_kthread(current) &&
7320 prev == smp_processor_id() &&
7321 this_rq()->nr_running <= 1 &&
7322 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7326 /* Check a recently used CPU as a potential idle candidate: */
7327 recent_used_cpu = p->recent_used_cpu;
7328 p->recent_used_cpu = prev;
7329 if (recent_used_cpu != prev &&
7330 recent_used_cpu != target &&
7331 cpus_share_cache(recent_used_cpu, target) &&
7332 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7333 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7334 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7335 return recent_used_cpu;
7339 * For asymmetric CPU capacity systems, our domain of interest is
7340 * sd_asym_cpucapacity rather than sd_llc.
7342 if (sched_asym_cpucap_active()) {
7343 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7345 * On an asymmetric CPU capacity system where an exclusive
7346 * cpuset defines a symmetric island (i.e. one unique
7347 * capacity_orig value through the cpuset), the key will be set
7348 * but the CPUs within that cpuset will not have a domain with
7349 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7353 i = select_idle_capacity(p, sd, target);
7354 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7358 sd = rcu_dereference(per_cpu(sd_llc, target));
7362 if (sched_smt_active()) {
7363 has_idle_core = test_idle_cores(target);
7365 if (!has_idle_core && cpus_share_cache(prev, target)) {
7366 i = select_idle_smt(p, prev);
7367 if ((unsigned int)i < nr_cpumask_bits)
7372 i = select_idle_cpu(p, sd, has_idle_core, target);
7373 if ((unsigned)i < nr_cpumask_bits)
7380 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7381 * @cpu: the CPU to get the utilization for
7382 * @p: task for which the CPU utilization should be predicted or NULL
7383 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7384 * @boost: 1 to enable boosting, otherwise 0
7386 * The unit of the return value must be the same as the one of CPU capacity
7387 * so that CPU utilization can be compared with CPU capacity.
7389 * CPU utilization is the sum of running time of runnable tasks plus the
7390 * recent utilization of currently non-runnable tasks on that CPU.
7391 * It represents the amount of CPU capacity currently used by CFS tasks in
7392 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7393 * capacity at f_max.
7395 * The estimated CPU utilization is defined as the maximum between CPU
7396 * utilization and sum of the estimated utilization of the currently
7397 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7398 * previously-executed tasks, which helps better deduce how busy a CPU will
7399 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7400 * of such a task would be significantly decayed at this point of time.
7402 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7403 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7404 * utilization. Boosting is implemented in cpu_util() so that internal
7405 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7406 * latter via cpu_util_cfs_boost().
7408 * CPU utilization can be higher than the current CPU capacity
7409 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7410 * of rounding errors as well as task migrations or wakeups of new tasks.
7411 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7412 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7413 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7414 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7415 * though since this is useful for predicting the CPU capacity required
7416 * after task migrations (scheduler-driven DVFS).
7418 * Return: (Boosted) (estimated) utilization for the specified CPU.
7420 static unsigned long
7421 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7423 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7424 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7425 unsigned long runnable;
7428 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7429 util = max(util, runnable);
7433 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7434 * contribution. If @p migrates from another CPU to @cpu add its
7435 * contribution. In all the other cases @cpu is not impacted by the
7436 * migration so its util_avg is already correct.
7438 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7439 lsub_positive(&util, task_util(p));
7440 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7441 util += task_util(p);
7443 if (sched_feat(UTIL_EST)) {
7444 unsigned long util_est;
7446 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7449 * During wake-up @p isn't enqueued yet and doesn't contribute
7450 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7451 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7452 * has been enqueued.
7454 * During exec (@dst_cpu = -1) @p is enqueued and does
7455 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7456 * Remove it to "simulate" cpu_util without @p's contribution.
7458 * Despite the task_on_rq_queued(@p) check there is still a
7459 * small window for a possible race when an exec
7460 * select_task_rq_fair() races with LB's detach_task().
7464 * p->on_rq = TASK_ON_RQ_MIGRATING;
7465 * -------------------------------- A
7467 * dequeue_task_fair() + Race Time
7468 * util_est_dequeue() /
7469 * -------------------------------- B
7471 * The additional check "current == p" is required to further
7472 * reduce the race window.
7475 util_est += _task_util_est(p);
7476 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7477 lsub_positive(&util_est, _task_util_est(p));
7479 util = max(util, util_est);
7482 return min(util, capacity_orig_of(cpu));
7485 unsigned long cpu_util_cfs(int cpu)
7487 return cpu_util(cpu, NULL, -1, 0);
7490 unsigned long cpu_util_cfs_boost(int cpu)
7492 return cpu_util(cpu, NULL, -1, 1);
7496 * cpu_util_without: compute cpu utilization without any contributions from *p
7497 * @cpu: the CPU which utilization is requested
7498 * @p: the task which utilization should be discounted
7500 * The utilization of a CPU is defined by the utilization of tasks currently
7501 * enqueued on that CPU as well as tasks which are currently sleeping after an
7502 * execution on that CPU.
7504 * This method returns the utilization of the specified CPU by discounting the
7505 * utilization of the specified task, whenever the task is currently
7506 * contributing to the CPU utilization.
7508 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7510 /* Task has no contribution or is new */
7511 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7514 return cpu_util(cpu, p, -1, 0);
7518 * energy_env - Utilization landscape for energy estimation.
7519 * @task_busy_time: Utilization contribution by the task for which we test the
7520 * placement. Given by eenv_task_busy_time().
7521 * @pd_busy_time: Utilization of the whole perf domain without the task
7522 * contribution. Given by eenv_pd_busy_time().
7523 * @cpu_cap: Maximum CPU capacity for the perf domain.
7524 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7527 unsigned long task_busy_time;
7528 unsigned long pd_busy_time;
7529 unsigned long cpu_cap;
7530 unsigned long pd_cap;
7534 * Compute the task busy time for compute_energy(). This time cannot be
7535 * injected directly into effective_cpu_util() because of the IRQ scaling.
7536 * The latter only makes sense with the most recent CPUs where the task has
7539 static inline void eenv_task_busy_time(struct energy_env *eenv,
7540 struct task_struct *p, int prev_cpu)
7542 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7543 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7545 if (unlikely(irq >= max_cap))
7546 busy_time = max_cap;
7548 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7550 eenv->task_busy_time = busy_time;
7554 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7555 * utilization for each @pd_cpus, it however doesn't take into account
7556 * clamping since the ratio (utilization / cpu_capacity) is already enough to
7557 * scale the EM reported power consumption at the (eventually clamped)
7560 * The contribution of the task @p for which we want to estimate the
7561 * energy cost is removed (by cpu_util()) and must be calculated
7562 * separately (see eenv_task_busy_time). This ensures:
7564 * - A stable PD utilization, no matter which CPU of that PD we want to place
7567 * - A fair comparison between CPUs as the task contribution (task_util())
7568 * will always be the same no matter which CPU utilization we rely on
7569 * (util_avg or util_est).
7571 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7572 * exceed @eenv->pd_cap.
7574 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7575 struct cpumask *pd_cpus,
7576 struct task_struct *p)
7578 unsigned long busy_time = 0;
7581 for_each_cpu(cpu, pd_cpus) {
7582 unsigned long util = cpu_util(cpu, p, -1, 0);
7584 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7587 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7591 * Compute the maximum utilization for compute_energy() when the task @p
7592 * is placed on the cpu @dst_cpu.
7594 * Returns the maximum utilization among @eenv->cpus. This utilization can't
7595 * exceed @eenv->cpu_cap.
7597 static inline unsigned long
7598 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7599 struct task_struct *p, int dst_cpu)
7601 unsigned long max_util = 0;
7604 for_each_cpu(cpu, pd_cpus) {
7605 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7606 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7607 unsigned long eff_util;
7610 * Performance domain frequency: utilization clamping
7611 * must be considered since it affects the selection
7612 * of the performance domain frequency.
7613 * NOTE: in case RT tasks are running, by default the
7614 * FREQUENCY_UTIL's utilization can be max OPP.
7616 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7617 max_util = max(max_util, eff_util);
7620 return min(max_util, eenv->cpu_cap);
7624 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7625 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7626 * contribution is ignored.
7628 static inline unsigned long
7629 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7630 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7632 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7633 unsigned long busy_time = eenv->pd_busy_time;
7636 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7638 return em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7642 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7643 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7644 * spare capacity in each performance domain and uses it as a potential
7645 * candidate to execute the task. Then, it uses the Energy Model to figure
7646 * out which of the CPU candidates is the most energy-efficient.
7648 * The rationale for this heuristic is as follows. In a performance domain,
7649 * all the most energy efficient CPU candidates (according to the Energy
7650 * Model) are those for which we'll request a low frequency. When there are
7651 * several CPUs for which the frequency request will be the same, we don't
7652 * have enough data to break the tie between them, because the Energy Model
7653 * only includes active power costs. With this model, if we assume that
7654 * frequency requests follow utilization (e.g. using schedutil), the CPU with
7655 * the maximum spare capacity in a performance domain is guaranteed to be among
7656 * the best candidates of the performance domain.
7658 * In practice, it could be preferable from an energy standpoint to pack
7659 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7660 * but that could also hurt our chances to go cluster idle, and we have no
7661 * ways to tell with the current Energy Model if this is actually a good
7662 * idea or not. So, find_energy_efficient_cpu() basically favors
7663 * cluster-packing, and spreading inside a cluster. That should at least be
7664 * a good thing for latency, and this is consistent with the idea that most
7665 * of the energy savings of EAS come from the asymmetry of the system, and
7666 * not so much from breaking the tie between identical CPUs. That's also the
7667 * reason why EAS is enabled in the topology code only for systems where
7668 * SD_ASYM_CPUCAPACITY is set.
7670 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7671 * they don't have any useful utilization data yet and it's not possible to
7672 * forecast their impact on energy consumption. Consequently, they will be
7673 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7674 * to be energy-inefficient in some use-cases. The alternative would be to
7675 * bias new tasks towards specific types of CPUs first, or to try to infer
7676 * their util_avg from the parent task, but those heuristics could hurt
7677 * other use-cases too. So, until someone finds a better way to solve this,
7678 * let's keep things simple by re-using the existing slow path.
7680 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7682 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7683 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7684 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7685 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7686 struct root_domain *rd = this_rq()->rd;
7687 int cpu, best_energy_cpu, target = -1;
7688 int prev_fits = -1, best_fits = -1;
7689 unsigned long best_thermal_cap = 0;
7690 unsigned long prev_thermal_cap = 0;
7691 struct sched_domain *sd;
7692 struct perf_domain *pd;
7693 struct energy_env eenv;
7696 pd = rcu_dereference(rd->pd);
7697 if (!pd || READ_ONCE(rd->overutilized))
7701 * Energy-aware wake-up happens on the lowest sched_domain starting
7702 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7704 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7705 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7712 sync_entity_load_avg(&p->se);
7713 if (!uclamp_task_util(p, p_util_min, p_util_max))
7716 eenv_task_busy_time(&eenv, p, prev_cpu);
7718 for (; pd; pd = pd->next) {
7719 unsigned long util_min = p_util_min, util_max = p_util_max;
7720 unsigned long cpu_cap, cpu_thermal_cap, util;
7721 unsigned long cur_delta, max_spare_cap = 0;
7722 unsigned long rq_util_min, rq_util_max;
7723 unsigned long prev_spare_cap = 0;
7724 int max_spare_cap_cpu = -1;
7725 unsigned long base_energy;
7726 int fits, max_fits = -1;
7728 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7730 if (cpumask_empty(cpus))
7733 /* Account thermal pressure for the energy estimation */
7734 cpu = cpumask_first(cpus);
7735 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7736 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7738 eenv.cpu_cap = cpu_thermal_cap;
7741 for_each_cpu(cpu, cpus) {
7742 struct rq *rq = cpu_rq(cpu);
7744 eenv.pd_cap += cpu_thermal_cap;
7746 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7749 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7752 util = cpu_util(cpu, p, cpu, 0);
7753 cpu_cap = capacity_of(cpu);
7756 * Skip CPUs that cannot satisfy the capacity request.
7757 * IOW, placing the task there would make the CPU
7758 * overutilized. Take uclamp into account to see how
7759 * much capacity we can get out of the CPU; this is
7760 * aligned with sched_cpu_util().
7762 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7764 * Open code uclamp_rq_util_with() except for
7765 * the clamp() part. Ie: apply max aggregation
7766 * only. util_fits_cpu() logic requires to
7767 * operate on non clamped util but must use the
7768 * max-aggregated uclamp_{min, max}.
7770 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7771 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7773 util_min = max(rq_util_min, p_util_min);
7774 util_max = max(rq_util_max, p_util_max);
7777 fits = util_fits_cpu(util, util_min, util_max, cpu);
7781 lsub_positive(&cpu_cap, util);
7783 if (cpu == prev_cpu) {
7784 /* Always use prev_cpu as a candidate. */
7785 prev_spare_cap = cpu_cap;
7787 } else if ((fits > max_fits) ||
7788 ((fits == max_fits) && (cpu_cap > max_spare_cap))) {
7790 * Find the CPU with the maximum spare capacity
7791 * among the remaining CPUs in the performance
7794 max_spare_cap = cpu_cap;
7795 max_spare_cap_cpu = cpu;
7800 if (max_spare_cap_cpu < 0 && prev_spare_cap == 0)
7803 eenv_pd_busy_time(&eenv, cpus, p);
7804 /* Compute the 'base' energy of the pd, without @p */
7805 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
7807 /* Evaluate the energy impact of using prev_cpu. */
7808 if (prev_spare_cap > 0) {
7809 prev_delta = compute_energy(&eenv, pd, cpus, p,
7811 /* CPU utilization has changed */
7812 if (prev_delta < base_energy)
7814 prev_delta -= base_energy;
7815 prev_thermal_cap = cpu_thermal_cap;
7816 best_delta = min(best_delta, prev_delta);
7819 /* Evaluate the energy impact of using max_spare_cap_cpu. */
7820 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
7821 /* Current best energy cpu fits better */
7822 if (max_fits < best_fits)
7826 * Both don't fit performance hint (i.e. uclamp_min)
7827 * but best energy cpu has better capacity.
7829 if ((max_fits < 0) &&
7830 (cpu_thermal_cap <= best_thermal_cap))
7833 cur_delta = compute_energy(&eenv, pd, cpus, p,
7835 /* CPU utilization has changed */
7836 if (cur_delta < base_energy)
7838 cur_delta -= base_energy;
7841 * Both fit for the task but best energy cpu has lower
7844 if ((max_fits > 0) && (best_fits > 0) &&
7845 (cur_delta >= best_delta))
7848 best_delta = cur_delta;
7849 best_energy_cpu = max_spare_cap_cpu;
7850 best_fits = max_fits;
7851 best_thermal_cap = cpu_thermal_cap;
7856 if ((best_fits > prev_fits) ||
7857 ((best_fits > 0) && (best_delta < prev_delta)) ||
7858 ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
7859 target = best_energy_cpu;
7870 * select_task_rq_fair: Select target runqueue for the waking task in domains
7871 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
7872 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7874 * Balances load by selecting the idlest CPU in the idlest group, or under
7875 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
7877 * Returns the target CPU number.
7880 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
7882 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
7883 struct sched_domain *tmp, *sd = NULL;
7884 int cpu = smp_processor_id();
7885 int new_cpu = prev_cpu;
7886 int want_affine = 0;
7887 /* SD_flags and WF_flags share the first nibble */
7888 int sd_flag = wake_flags & 0xF;
7891 * required for stable ->cpus_allowed
7893 lockdep_assert_held(&p->pi_lock);
7894 if (wake_flags & WF_TTWU) {
7897 if ((wake_flags & WF_CURRENT_CPU) &&
7898 cpumask_test_cpu(cpu, p->cpus_ptr))
7901 if (sched_energy_enabled()) {
7902 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
7908 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
7912 for_each_domain(cpu, tmp) {
7914 * If both 'cpu' and 'prev_cpu' are part of this domain,
7915 * cpu is a valid SD_WAKE_AFFINE target.
7917 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
7918 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
7919 if (cpu != prev_cpu)
7920 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
7922 sd = NULL; /* Prefer wake_affine over balance flags */
7927 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
7928 * usually do not have SD_BALANCE_WAKE set. That means wakeup
7929 * will usually go to the fast path.
7931 if (tmp->flags & sd_flag)
7933 else if (!want_affine)
7939 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
7940 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
7942 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
7950 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
7951 * cfs_rq_of(p) references at time of call are still valid and identify the
7952 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7954 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
7956 struct sched_entity *se = &p->se;
7958 if (!task_on_rq_migrating(p)) {
7959 remove_entity_load_avg(se);
7962 * Here, the task's PELT values have been updated according to
7963 * the current rq's clock. But if that clock hasn't been
7964 * updated in a while, a substantial idle time will be missed,
7965 * leading to an inflation after wake-up on the new rq.
7967 * Estimate the missing time from the cfs_rq last_update_time
7968 * and update sched_avg to improve the PELT continuity after
7971 migrate_se_pelt_lag(se);
7974 /* Tell new CPU we are migrated */
7975 se->avg.last_update_time = 0;
7977 update_scan_period(p, new_cpu);
7980 static void task_dead_fair(struct task_struct *p)
7982 remove_entity_load_avg(&p->se);
7986 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7991 return newidle_balance(rq, rf) != 0;
7993 #endif /* CONFIG_SMP */
7995 static void set_next_buddy(struct sched_entity *se)
7997 for_each_sched_entity(se) {
7998 if (SCHED_WARN_ON(!se->on_rq))
8002 cfs_rq_of(se)->next = se;
8007 * Preempt the current task with a newly woken task if needed:
8009 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
8011 struct task_struct *curr = rq->curr;
8012 struct sched_entity *se = &curr->se, *pse = &p->se;
8013 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8014 int next_buddy_marked = 0;
8015 int cse_is_idle, pse_is_idle;
8017 if (unlikely(se == pse))
8021 * This is possible from callers such as attach_tasks(), in which we
8022 * unconditionally check_preempt_curr() after an enqueue (which may have
8023 * lead to a throttle). This both saves work and prevents false
8024 * next-buddy nomination below.
8026 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8029 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8030 set_next_buddy(pse);
8031 next_buddy_marked = 1;
8035 * We can come here with TIF_NEED_RESCHED already set from new task
8038 * Note: this also catches the edge-case of curr being in a throttled
8039 * group (e.g. via set_curr_task), since update_curr() (in the
8040 * enqueue of curr) will have resulted in resched being set. This
8041 * prevents us from potentially nominating it as a false LAST_BUDDY
8044 if (test_tsk_need_resched(curr))
8047 /* Idle tasks are by definition preempted by non-idle tasks. */
8048 if (unlikely(task_has_idle_policy(curr)) &&
8049 likely(!task_has_idle_policy(p)))
8053 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8054 * is driven by the tick):
8056 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8059 find_matching_se(&se, &pse);
8062 cse_is_idle = se_is_idle(se);
8063 pse_is_idle = se_is_idle(pse);
8066 * Preempt an idle group in favor of a non-idle group (and don't preempt
8067 * in the inverse case).
8069 if (cse_is_idle && !pse_is_idle)
8071 if (cse_is_idle != pse_is_idle)
8074 cfs_rq = cfs_rq_of(se);
8075 update_curr(cfs_rq);
8078 * XXX pick_eevdf(cfs_rq) != se ?
8080 if (pick_eevdf(cfs_rq) == pse)
8090 static struct task_struct *pick_task_fair(struct rq *rq)
8092 struct sched_entity *se;
8093 struct cfs_rq *cfs_rq;
8097 if (!cfs_rq->nr_running)
8101 struct sched_entity *curr = cfs_rq->curr;
8103 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8106 update_curr(cfs_rq);
8110 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8114 se = pick_next_entity(cfs_rq, curr);
8115 cfs_rq = group_cfs_rq(se);
8122 struct task_struct *
8123 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8125 struct cfs_rq *cfs_rq = &rq->cfs;
8126 struct sched_entity *se;
8127 struct task_struct *p;
8131 if (!sched_fair_runnable(rq))
8134 #ifdef CONFIG_FAIR_GROUP_SCHED
8135 if (!prev || prev->sched_class != &fair_sched_class)
8139 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8140 * likely that a next task is from the same cgroup as the current.
8142 * Therefore attempt to avoid putting and setting the entire cgroup
8143 * hierarchy, only change the part that actually changes.
8147 struct sched_entity *curr = cfs_rq->curr;
8150 * Since we got here without doing put_prev_entity() we also
8151 * have to consider cfs_rq->curr. If it is still a runnable
8152 * entity, update_curr() will update its vruntime, otherwise
8153 * forget we've ever seen it.
8157 update_curr(cfs_rq);
8162 * This call to check_cfs_rq_runtime() will do the
8163 * throttle and dequeue its entity in the parent(s).
8164 * Therefore the nr_running test will indeed
8167 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8170 if (!cfs_rq->nr_running)
8177 se = pick_next_entity(cfs_rq, curr);
8178 cfs_rq = group_cfs_rq(se);
8184 * Since we haven't yet done put_prev_entity and if the selected task
8185 * is a different task than we started out with, try and touch the
8186 * least amount of cfs_rqs.
8189 struct sched_entity *pse = &prev->se;
8191 while (!(cfs_rq = is_same_group(se, pse))) {
8192 int se_depth = se->depth;
8193 int pse_depth = pse->depth;
8195 if (se_depth <= pse_depth) {
8196 put_prev_entity(cfs_rq_of(pse), pse);
8197 pse = parent_entity(pse);
8199 if (se_depth >= pse_depth) {
8200 set_next_entity(cfs_rq_of(se), se);
8201 se = parent_entity(se);
8205 put_prev_entity(cfs_rq, pse);
8206 set_next_entity(cfs_rq, se);
8213 put_prev_task(rq, prev);
8216 se = pick_next_entity(cfs_rq, NULL);
8217 set_next_entity(cfs_rq, se);
8218 cfs_rq = group_cfs_rq(se);
8223 done: __maybe_unused;
8226 * Move the next running task to the front of
8227 * the list, so our cfs_tasks list becomes MRU
8230 list_move(&p->se.group_node, &rq->cfs_tasks);
8233 if (hrtick_enabled_fair(rq))
8234 hrtick_start_fair(rq, p);
8236 update_misfit_status(p, rq);
8237 sched_fair_update_stop_tick(rq, p);
8245 new_tasks = newidle_balance(rq, rf);
8248 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8249 * possible for any higher priority task to appear. In that case we
8250 * must re-start the pick_next_entity() loop.
8259 * rq is about to be idle, check if we need to update the
8260 * lost_idle_time of clock_pelt
8262 update_idle_rq_clock_pelt(rq);
8267 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8269 return pick_next_task_fair(rq, NULL, NULL);
8273 * Account for a descheduled task:
8275 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8277 struct sched_entity *se = &prev->se;
8278 struct cfs_rq *cfs_rq;
8280 for_each_sched_entity(se) {
8281 cfs_rq = cfs_rq_of(se);
8282 put_prev_entity(cfs_rq, se);
8287 * sched_yield() is very simple
8289 static void yield_task_fair(struct rq *rq)
8291 struct task_struct *curr = rq->curr;
8292 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8293 struct sched_entity *se = &curr->se;
8296 * Are we the only task in the tree?
8298 if (unlikely(rq->nr_running == 1))
8301 clear_buddies(cfs_rq, se);
8303 update_rq_clock(rq);
8305 * Update run-time statistics of the 'current'.
8307 update_curr(cfs_rq);
8309 * Tell update_rq_clock() that we've just updated,
8310 * so we don't do microscopic update in schedule()
8311 * and double the fastpath cost.
8313 rq_clock_skip_update(rq);
8315 se->deadline += calc_delta_fair(se->slice, se);
8318 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8320 struct sched_entity *se = &p->se;
8322 /* throttled hierarchies are not runnable */
8323 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8326 /* Tell the scheduler that we'd really like pse to run next. */
8329 yield_task_fair(rq);
8335 /**************************************************
8336 * Fair scheduling class load-balancing methods.
8340 * The purpose of load-balancing is to achieve the same basic fairness the
8341 * per-CPU scheduler provides, namely provide a proportional amount of compute
8342 * time to each task. This is expressed in the following equation:
8344 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8346 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8347 * W_i,0 is defined as:
8349 * W_i,0 = \Sum_j w_i,j (2)
8351 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8352 * is derived from the nice value as per sched_prio_to_weight[].
8354 * The weight average is an exponential decay average of the instantaneous
8357 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8359 * C_i is the compute capacity of CPU i, typically it is the
8360 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8361 * can also include other factors [XXX].
8363 * To achieve this balance we define a measure of imbalance which follows
8364 * directly from (1):
8366 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8368 * We them move tasks around to minimize the imbalance. In the continuous
8369 * function space it is obvious this converges, in the discrete case we get
8370 * a few fun cases generally called infeasible weight scenarios.
8373 * - infeasible weights;
8374 * - local vs global optima in the discrete case. ]
8379 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8380 * for all i,j solution, we create a tree of CPUs that follows the hardware
8381 * topology where each level pairs two lower groups (or better). This results
8382 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8383 * tree to only the first of the previous level and we decrease the frequency
8384 * of load-balance at each level inv. proportional to the number of CPUs in
8390 * \Sum { --- * --- * 2^i } = O(n) (5)
8392 * `- size of each group
8393 * | | `- number of CPUs doing load-balance
8395 * `- sum over all levels
8397 * Coupled with a limit on how many tasks we can migrate every balance pass,
8398 * this makes (5) the runtime complexity of the balancer.
8400 * An important property here is that each CPU is still (indirectly) connected
8401 * to every other CPU in at most O(log n) steps:
8403 * The adjacency matrix of the resulting graph is given by:
8406 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8409 * And you'll find that:
8411 * A^(log_2 n)_i,j != 0 for all i,j (7)
8413 * Showing there's indeed a path between every CPU in at most O(log n) steps.
8414 * The task movement gives a factor of O(m), giving a convergence complexity
8417 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8422 * In order to avoid CPUs going idle while there's still work to do, new idle
8423 * balancing is more aggressive and has the newly idle CPU iterate up the domain
8424 * tree itself instead of relying on other CPUs to bring it work.
8426 * This adds some complexity to both (5) and (8) but it reduces the total idle
8434 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8437 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8442 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8444 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8446 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8449 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8450 * rewrite all of this once again.]
8453 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8455 enum fbq_type { regular, remote, all };
8458 * 'group_type' describes the group of CPUs at the moment of load balancing.
8460 * The enum is ordered by pulling priority, with the group with lowest priority
8461 * first so the group_type can simply be compared when selecting the busiest
8462 * group. See update_sd_pick_busiest().
8465 /* The group has spare capacity that can be used to run more tasks. */
8466 group_has_spare = 0,
8468 * The group is fully used and the tasks don't compete for more CPU
8469 * cycles. Nevertheless, some tasks might wait before running.
8473 * One task doesn't fit with CPU's capacity and must be migrated to a
8474 * more powerful CPU.
8478 * Balance SMT group that's fully busy. Can benefit from migration
8479 * a task on SMT with busy sibling to another CPU on idle core.
8483 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8484 * and the task should be migrated to it instead of running on the
8489 * The tasks' affinity constraints previously prevented the scheduler
8490 * from balancing the load across the system.
8494 * The CPU is overloaded and can't provide expected CPU cycles to all
8500 enum migration_type {
8507 #define LBF_ALL_PINNED 0x01
8508 #define LBF_NEED_BREAK 0x02
8509 #define LBF_DST_PINNED 0x04
8510 #define LBF_SOME_PINNED 0x08
8511 #define LBF_ACTIVE_LB 0x10
8514 struct sched_domain *sd;
8522 struct cpumask *dst_grpmask;
8524 enum cpu_idle_type idle;
8526 /* The set of CPUs under consideration for load-balancing */
8527 struct cpumask *cpus;
8532 unsigned int loop_break;
8533 unsigned int loop_max;
8535 enum fbq_type fbq_type;
8536 enum migration_type migration_type;
8537 struct list_head tasks;
8541 * Is this task likely cache-hot:
8543 static int task_hot(struct task_struct *p, struct lb_env *env)
8547 lockdep_assert_rq_held(env->src_rq);
8549 if (p->sched_class != &fair_sched_class)
8552 if (unlikely(task_has_idle_policy(p)))
8555 /* SMT siblings share cache */
8556 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8560 * Buddy candidates are cache hot:
8562 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8563 (&p->se == cfs_rq_of(&p->se)->next))
8566 if (sysctl_sched_migration_cost == -1)
8570 * Don't migrate task if the task's cookie does not match
8571 * with the destination CPU's core cookie.
8573 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8576 if (sysctl_sched_migration_cost == 0)
8579 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8581 return delta < (s64)sysctl_sched_migration_cost;
8584 #ifdef CONFIG_NUMA_BALANCING
8586 * Returns 1, if task migration degrades locality
8587 * Returns 0, if task migration improves locality i.e migration preferred.
8588 * Returns -1, if task migration is not affected by locality.
8590 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8592 struct numa_group *numa_group = rcu_dereference(p->numa_group);
8593 unsigned long src_weight, dst_weight;
8594 int src_nid, dst_nid, dist;
8596 if (!static_branch_likely(&sched_numa_balancing))
8599 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8602 src_nid = cpu_to_node(env->src_cpu);
8603 dst_nid = cpu_to_node(env->dst_cpu);
8605 if (src_nid == dst_nid)
8608 /* Migrating away from the preferred node is always bad. */
8609 if (src_nid == p->numa_preferred_nid) {
8610 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8616 /* Encourage migration to the preferred node. */
8617 if (dst_nid == p->numa_preferred_nid)
8620 /* Leaving a core idle is often worse than degrading locality. */
8621 if (env->idle == CPU_IDLE)
8624 dist = node_distance(src_nid, dst_nid);
8626 src_weight = group_weight(p, src_nid, dist);
8627 dst_weight = group_weight(p, dst_nid, dist);
8629 src_weight = task_weight(p, src_nid, dist);
8630 dst_weight = task_weight(p, dst_nid, dist);
8633 return dst_weight < src_weight;
8637 static inline int migrate_degrades_locality(struct task_struct *p,
8645 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8648 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8652 lockdep_assert_rq_held(env->src_rq);
8655 * We do not migrate tasks that are:
8656 * 1) throttled_lb_pair, or
8657 * 2) cannot be migrated to this CPU due to cpus_ptr, or
8658 * 3) running (obviously), or
8659 * 4) are cache-hot on their current CPU.
8661 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8664 /* Disregard pcpu kthreads; they are where they need to be. */
8665 if (kthread_is_per_cpu(p))
8668 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8671 schedstat_inc(p->stats.nr_failed_migrations_affine);
8673 env->flags |= LBF_SOME_PINNED;
8676 * Remember if this task can be migrated to any other CPU in
8677 * our sched_group. We may want to revisit it if we couldn't
8678 * meet load balance goals by pulling other tasks on src_cpu.
8680 * Avoid computing new_dst_cpu
8682 * - if we have already computed one in current iteration
8683 * - if it's an active balance
8685 if (env->idle == CPU_NEWLY_IDLE ||
8686 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8689 /* Prevent to re-select dst_cpu via env's CPUs: */
8690 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8691 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8692 env->flags |= LBF_DST_PINNED;
8693 env->new_dst_cpu = cpu;
8701 /* Record that we found at least one task that could run on dst_cpu */
8702 env->flags &= ~LBF_ALL_PINNED;
8704 if (task_on_cpu(env->src_rq, p)) {
8705 schedstat_inc(p->stats.nr_failed_migrations_running);
8710 * Aggressive migration if:
8712 * 2) destination numa is preferred
8713 * 3) task is cache cold, or
8714 * 4) too many balance attempts have failed.
8716 if (env->flags & LBF_ACTIVE_LB)
8719 tsk_cache_hot = migrate_degrades_locality(p, env);
8720 if (tsk_cache_hot == -1)
8721 tsk_cache_hot = task_hot(p, env);
8723 if (tsk_cache_hot <= 0 ||
8724 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
8725 if (tsk_cache_hot == 1) {
8726 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
8727 schedstat_inc(p->stats.nr_forced_migrations);
8732 schedstat_inc(p->stats.nr_failed_migrations_hot);
8737 * detach_task() -- detach the task for the migration specified in env
8739 static void detach_task(struct task_struct *p, struct lb_env *env)
8741 lockdep_assert_rq_held(env->src_rq);
8743 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8744 set_task_cpu(p, env->dst_cpu);
8748 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8749 * part of active balancing operations within "domain".
8751 * Returns a task if successful and NULL otherwise.
8753 static struct task_struct *detach_one_task(struct lb_env *env)
8755 struct task_struct *p;
8757 lockdep_assert_rq_held(env->src_rq);
8759 list_for_each_entry_reverse(p,
8760 &env->src_rq->cfs_tasks, se.group_node) {
8761 if (!can_migrate_task(p, env))
8764 detach_task(p, env);
8767 * Right now, this is only the second place where
8768 * lb_gained[env->idle] is updated (other is detach_tasks)
8769 * so we can safely collect stats here rather than
8770 * inside detach_tasks().
8772 schedstat_inc(env->sd->lb_gained[env->idle]);
8779 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8780 * busiest_rq, as part of a balancing operation within domain "sd".
8782 * Returns number of detached tasks if successful and 0 otherwise.
8784 static int detach_tasks(struct lb_env *env)
8786 struct list_head *tasks = &env->src_rq->cfs_tasks;
8787 unsigned long util, load;
8788 struct task_struct *p;
8791 lockdep_assert_rq_held(env->src_rq);
8794 * Source run queue has been emptied by another CPU, clear
8795 * LBF_ALL_PINNED flag as we will not test any task.
8797 if (env->src_rq->nr_running <= 1) {
8798 env->flags &= ~LBF_ALL_PINNED;
8802 if (env->imbalance <= 0)
8805 while (!list_empty(tasks)) {
8807 * We don't want to steal all, otherwise we may be treated likewise,
8808 * which could at worst lead to a livelock crash.
8810 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
8815 * We've more or less seen every task there is, call it quits
8816 * unless we haven't found any movable task yet.
8818 if (env->loop > env->loop_max &&
8819 !(env->flags & LBF_ALL_PINNED))
8822 /* take a breather every nr_migrate tasks */
8823 if (env->loop > env->loop_break) {
8824 env->loop_break += SCHED_NR_MIGRATE_BREAK;
8825 env->flags |= LBF_NEED_BREAK;
8829 p = list_last_entry(tasks, struct task_struct, se.group_node);
8831 if (!can_migrate_task(p, env))
8834 switch (env->migration_type) {
8837 * Depending of the number of CPUs and tasks and the
8838 * cgroup hierarchy, task_h_load() can return a null
8839 * value. Make sure that env->imbalance decreases
8840 * otherwise detach_tasks() will stop only after
8841 * detaching up to loop_max tasks.
8843 load = max_t(unsigned long, task_h_load(p), 1);
8845 if (sched_feat(LB_MIN) &&
8846 load < 16 && !env->sd->nr_balance_failed)
8850 * Make sure that we don't migrate too much load.
8851 * Nevertheless, let relax the constraint if
8852 * scheduler fails to find a good waiting task to
8855 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
8858 env->imbalance -= load;
8862 util = task_util_est(p);
8864 if (util > env->imbalance)
8867 env->imbalance -= util;
8874 case migrate_misfit:
8875 /* This is not a misfit task */
8876 if (task_fits_cpu(p, env->src_cpu))
8883 detach_task(p, env);
8884 list_add(&p->se.group_node, &env->tasks);
8888 #ifdef CONFIG_PREEMPTION
8890 * NEWIDLE balancing is a source of latency, so preemptible
8891 * kernels will stop after the first task is detached to minimize
8892 * the critical section.
8894 if (env->idle == CPU_NEWLY_IDLE)
8899 * We only want to steal up to the prescribed amount of
8902 if (env->imbalance <= 0)
8907 list_move(&p->se.group_node, tasks);
8911 * Right now, this is one of only two places we collect this stat
8912 * so we can safely collect detach_one_task() stats here rather
8913 * than inside detach_one_task().
8915 schedstat_add(env->sd->lb_gained[env->idle], detached);
8921 * attach_task() -- attach the task detached by detach_task() to its new rq.
8923 static void attach_task(struct rq *rq, struct task_struct *p)
8925 lockdep_assert_rq_held(rq);
8927 WARN_ON_ONCE(task_rq(p) != rq);
8928 activate_task(rq, p, ENQUEUE_NOCLOCK);
8929 check_preempt_curr(rq, p, 0);
8933 * attach_one_task() -- attaches the task returned from detach_one_task() to
8936 static void attach_one_task(struct rq *rq, struct task_struct *p)
8941 update_rq_clock(rq);
8947 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8950 static void attach_tasks(struct lb_env *env)
8952 struct list_head *tasks = &env->tasks;
8953 struct task_struct *p;
8956 rq_lock(env->dst_rq, &rf);
8957 update_rq_clock(env->dst_rq);
8959 while (!list_empty(tasks)) {
8960 p = list_first_entry(tasks, struct task_struct, se.group_node);
8961 list_del_init(&p->se.group_node);
8963 attach_task(env->dst_rq, p);
8966 rq_unlock(env->dst_rq, &rf);
8969 #ifdef CONFIG_NO_HZ_COMMON
8970 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
8972 if (cfs_rq->avg.load_avg)
8975 if (cfs_rq->avg.util_avg)
8981 static inline bool others_have_blocked(struct rq *rq)
8983 if (READ_ONCE(rq->avg_rt.util_avg))
8986 if (READ_ONCE(rq->avg_dl.util_avg))
8989 if (thermal_load_avg(rq))
8992 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
8993 if (READ_ONCE(rq->avg_irq.util_avg))
9000 static inline void update_blocked_load_tick(struct rq *rq)
9002 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9005 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9008 rq->has_blocked_load = 0;
9011 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
9012 static inline bool others_have_blocked(struct rq *rq) { return false; }
9013 static inline void update_blocked_load_tick(struct rq *rq) {}
9014 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9017 static bool __update_blocked_others(struct rq *rq, bool *done)
9019 const struct sched_class *curr_class;
9020 u64 now = rq_clock_pelt(rq);
9021 unsigned long thermal_pressure;
9025 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9026 * DL and IRQ signals have been updated before updating CFS.
9028 curr_class = rq->curr->sched_class;
9030 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9032 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9033 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9034 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9035 update_irq_load_avg(rq, 0);
9037 if (others_have_blocked(rq))
9043 #ifdef CONFIG_FAIR_GROUP_SCHED
9045 static bool __update_blocked_fair(struct rq *rq, bool *done)
9047 struct cfs_rq *cfs_rq, *pos;
9048 bool decayed = false;
9049 int cpu = cpu_of(rq);
9052 * Iterates the task_group tree in a bottom up fashion, see
9053 * list_add_leaf_cfs_rq() for details.
9055 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9056 struct sched_entity *se;
9058 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9059 update_tg_load_avg(cfs_rq);
9061 if (cfs_rq->nr_running == 0)
9062 update_idle_cfs_rq_clock_pelt(cfs_rq);
9064 if (cfs_rq == &rq->cfs)
9068 /* Propagate pending load changes to the parent, if any: */
9069 se = cfs_rq->tg->se[cpu];
9070 if (se && !skip_blocked_update(se))
9071 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9074 * There can be a lot of idle CPU cgroups. Don't let fully
9075 * decayed cfs_rqs linger on the list.
9077 if (cfs_rq_is_decayed(cfs_rq))
9078 list_del_leaf_cfs_rq(cfs_rq);
9080 /* Don't need periodic decay once load/util_avg are null */
9081 if (cfs_rq_has_blocked(cfs_rq))
9089 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9090 * This needs to be done in a top-down fashion because the load of a child
9091 * group is a fraction of its parents load.
9093 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9095 struct rq *rq = rq_of(cfs_rq);
9096 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9097 unsigned long now = jiffies;
9100 if (cfs_rq->last_h_load_update == now)
9103 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9104 for_each_sched_entity(se) {
9105 cfs_rq = cfs_rq_of(se);
9106 WRITE_ONCE(cfs_rq->h_load_next, se);
9107 if (cfs_rq->last_h_load_update == now)
9112 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9113 cfs_rq->last_h_load_update = now;
9116 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9117 load = cfs_rq->h_load;
9118 load = div64_ul(load * se->avg.load_avg,
9119 cfs_rq_load_avg(cfs_rq) + 1);
9120 cfs_rq = group_cfs_rq(se);
9121 cfs_rq->h_load = load;
9122 cfs_rq->last_h_load_update = now;
9126 static unsigned long task_h_load(struct task_struct *p)
9128 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9130 update_cfs_rq_h_load(cfs_rq);
9131 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9132 cfs_rq_load_avg(cfs_rq) + 1);
9135 static bool __update_blocked_fair(struct rq *rq, bool *done)
9137 struct cfs_rq *cfs_rq = &rq->cfs;
9140 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9141 if (cfs_rq_has_blocked(cfs_rq))
9147 static unsigned long task_h_load(struct task_struct *p)
9149 return p->se.avg.load_avg;
9153 static void update_blocked_averages(int cpu)
9155 bool decayed = false, done = true;
9156 struct rq *rq = cpu_rq(cpu);
9159 rq_lock_irqsave(rq, &rf);
9160 update_blocked_load_tick(rq);
9161 update_rq_clock(rq);
9163 decayed |= __update_blocked_others(rq, &done);
9164 decayed |= __update_blocked_fair(rq, &done);
9166 update_blocked_load_status(rq, !done);
9168 cpufreq_update_util(rq, 0);
9169 rq_unlock_irqrestore(rq, &rf);
9172 /********** Helpers for find_busiest_group ************************/
9175 * sg_lb_stats - stats of a sched_group required for load_balancing
9177 struct sg_lb_stats {
9178 unsigned long avg_load; /*Avg load across the CPUs of the group */
9179 unsigned long group_load; /* Total load over the CPUs of the group */
9180 unsigned long group_capacity;
9181 unsigned long group_util; /* Total utilization over the CPUs of the group */
9182 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9183 unsigned int sum_nr_running; /* Nr of tasks running in the group */
9184 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9185 unsigned int idle_cpus;
9186 unsigned int group_weight;
9187 enum group_type group_type;
9188 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9189 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9190 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9191 #ifdef CONFIG_NUMA_BALANCING
9192 unsigned int nr_numa_running;
9193 unsigned int nr_preferred_running;
9198 * sd_lb_stats - Structure to store the statistics of a sched_domain
9199 * during load balancing.
9201 struct sd_lb_stats {
9202 struct sched_group *busiest; /* Busiest group in this sd */
9203 struct sched_group *local; /* Local group in this sd */
9204 unsigned long total_load; /* Total load of all groups in sd */
9205 unsigned long total_capacity; /* Total capacity of all groups in sd */
9206 unsigned long avg_load; /* Average load across all groups in sd */
9207 unsigned int prefer_sibling; /* tasks should go to sibling first */
9209 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9210 struct sg_lb_stats local_stat; /* Statistics of the local group */
9213 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9216 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9217 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9218 * We must however set busiest_stat::group_type and
9219 * busiest_stat::idle_cpus to the worst busiest group because
9220 * update_sd_pick_busiest() reads these before assignment.
9222 *sds = (struct sd_lb_stats){
9226 .total_capacity = 0UL,
9228 .idle_cpus = UINT_MAX,
9229 .group_type = group_has_spare,
9234 static unsigned long scale_rt_capacity(int cpu)
9236 struct rq *rq = cpu_rq(cpu);
9237 unsigned long max = arch_scale_cpu_capacity(cpu);
9238 unsigned long used, free;
9241 irq = cpu_util_irq(rq);
9243 if (unlikely(irq >= max))
9247 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9248 * (running and not running) with weights 0 and 1024 respectively.
9249 * avg_thermal.load_avg tracks thermal pressure and the weighted
9250 * average uses the actual delta max capacity(load).
9252 used = READ_ONCE(rq->avg_rt.util_avg);
9253 used += READ_ONCE(rq->avg_dl.util_avg);
9254 used += thermal_load_avg(rq);
9256 if (unlikely(used >= max))
9261 return scale_irq_capacity(free, irq, max);
9264 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9266 unsigned long capacity = scale_rt_capacity(cpu);
9267 struct sched_group *sdg = sd->groups;
9269 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
9274 cpu_rq(cpu)->cpu_capacity = capacity;
9275 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9277 sdg->sgc->capacity = capacity;
9278 sdg->sgc->min_capacity = capacity;
9279 sdg->sgc->max_capacity = capacity;
9282 void update_group_capacity(struct sched_domain *sd, int cpu)
9284 struct sched_domain *child = sd->child;
9285 struct sched_group *group, *sdg = sd->groups;
9286 unsigned long capacity, min_capacity, max_capacity;
9287 unsigned long interval;
9289 interval = msecs_to_jiffies(sd->balance_interval);
9290 interval = clamp(interval, 1UL, max_load_balance_interval);
9291 sdg->sgc->next_update = jiffies + interval;
9294 update_cpu_capacity(sd, cpu);
9299 min_capacity = ULONG_MAX;
9302 if (child->flags & SD_OVERLAP) {
9304 * SD_OVERLAP domains cannot assume that child groups
9305 * span the current group.
9308 for_each_cpu(cpu, sched_group_span(sdg)) {
9309 unsigned long cpu_cap = capacity_of(cpu);
9311 capacity += cpu_cap;
9312 min_capacity = min(cpu_cap, min_capacity);
9313 max_capacity = max(cpu_cap, max_capacity);
9317 * !SD_OVERLAP domains can assume that child groups
9318 * span the current group.
9321 group = child->groups;
9323 struct sched_group_capacity *sgc = group->sgc;
9325 capacity += sgc->capacity;
9326 min_capacity = min(sgc->min_capacity, min_capacity);
9327 max_capacity = max(sgc->max_capacity, max_capacity);
9328 group = group->next;
9329 } while (group != child->groups);
9332 sdg->sgc->capacity = capacity;
9333 sdg->sgc->min_capacity = min_capacity;
9334 sdg->sgc->max_capacity = max_capacity;
9338 * Check whether the capacity of the rq has been noticeably reduced by side
9339 * activity. The imbalance_pct is used for the threshold.
9340 * Return true is the capacity is reduced
9343 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9345 return ((rq->cpu_capacity * sd->imbalance_pct) <
9346 (rq->cpu_capacity_orig * 100));
9350 * Check whether a rq has a misfit task and if it looks like we can actually
9351 * help that task: we can migrate the task to a CPU of higher capacity, or
9352 * the task's current CPU is heavily pressured.
9354 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9356 return rq->misfit_task_load &&
9357 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
9358 check_cpu_capacity(rq, sd));
9362 * Group imbalance indicates (and tries to solve) the problem where balancing
9363 * groups is inadequate due to ->cpus_ptr constraints.
9365 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9366 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9369 * { 0 1 2 3 } { 4 5 6 7 }
9372 * If we were to balance group-wise we'd place two tasks in the first group and
9373 * two tasks in the second group. Clearly this is undesired as it will overload
9374 * cpu 3 and leave one of the CPUs in the second group unused.
9376 * The current solution to this issue is detecting the skew in the first group
9377 * by noticing the lower domain failed to reach balance and had difficulty
9378 * moving tasks due to affinity constraints.
9380 * When this is so detected; this group becomes a candidate for busiest; see
9381 * update_sd_pick_busiest(). And calculate_imbalance() and
9382 * find_busiest_group() avoid some of the usual balance conditions to allow it
9383 * to create an effective group imbalance.
9385 * This is a somewhat tricky proposition since the next run might not find the
9386 * group imbalance and decide the groups need to be balanced again. A most
9387 * subtle and fragile situation.
9390 static inline int sg_imbalanced(struct sched_group *group)
9392 return group->sgc->imbalance;
9396 * group_has_capacity returns true if the group has spare capacity that could
9397 * be used by some tasks.
9398 * We consider that a group has spare capacity if the number of task is
9399 * smaller than the number of CPUs or if the utilization is lower than the
9400 * available capacity for CFS tasks.
9401 * For the latter, we use a threshold to stabilize the state, to take into
9402 * account the variance of the tasks' load and to return true if the available
9403 * capacity in meaningful for the load balancer.
9404 * As an example, an available capacity of 1% can appear but it doesn't make
9405 * any benefit for the load balance.
9408 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9410 if (sgs->sum_nr_running < sgs->group_weight)
9413 if ((sgs->group_capacity * imbalance_pct) <
9414 (sgs->group_runnable * 100))
9417 if ((sgs->group_capacity * 100) >
9418 (sgs->group_util * imbalance_pct))
9425 * group_is_overloaded returns true if the group has more tasks than it can
9427 * group_is_overloaded is not equals to !group_has_capacity because a group
9428 * with the exact right number of tasks, has no more spare capacity but is not
9429 * overloaded so both group_has_capacity and group_is_overloaded return
9433 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9435 if (sgs->sum_nr_running <= sgs->group_weight)
9438 if ((sgs->group_capacity * 100) <
9439 (sgs->group_util * imbalance_pct))
9442 if ((sgs->group_capacity * imbalance_pct) <
9443 (sgs->group_runnable * 100))
9450 group_type group_classify(unsigned int imbalance_pct,
9451 struct sched_group *group,
9452 struct sg_lb_stats *sgs)
9454 if (group_is_overloaded(imbalance_pct, sgs))
9455 return group_overloaded;
9457 if (sg_imbalanced(group))
9458 return group_imbalanced;
9460 if (sgs->group_asym_packing)
9461 return group_asym_packing;
9463 if (sgs->group_smt_balance)
9464 return group_smt_balance;
9466 if (sgs->group_misfit_task_load)
9467 return group_misfit_task;
9469 if (!group_has_capacity(imbalance_pct, sgs))
9470 return group_fully_busy;
9472 return group_has_spare;
9476 * sched_use_asym_prio - Check whether asym_packing priority must be used
9477 * @sd: The scheduling domain of the load balancing
9480 * Always use CPU priority when balancing load between SMT siblings. When
9481 * balancing load between cores, it is not sufficient that @cpu is idle. Only
9482 * use CPU priority if the whole core is idle.
9484 * Returns: True if the priority of @cpu must be followed. False otherwise.
9486 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9488 if (!sched_smt_active())
9491 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9495 * sched_asym - Check if the destination CPU can do asym_packing load balance
9496 * @env: The load balancing environment
9497 * @sds: Load-balancing data with statistics of the local group
9498 * @sgs: Load-balancing statistics of the candidate busiest group
9499 * @group: The candidate busiest group
9501 * @env::dst_cpu can do asym_packing if it has higher priority than the
9502 * preferred CPU of @group.
9504 * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9505 * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9506 * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9507 * imbalances in the number of CPUS are dealt with in find_busiest_group().
9509 * If we are balancing load within an SMT core, or at DIE domain level, always
9512 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9516 sched_asym(struct lb_env *env, struct sd_lb_stats *sds, struct sg_lb_stats *sgs,
9517 struct sched_group *group)
9519 /* Ensure that the whole local core is idle, if applicable. */
9520 if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9524 * CPU priorities does not make sense for SMT cores with more than one
9527 if (group->flags & SD_SHARE_CPUCAPACITY) {
9528 if (sgs->group_weight - sgs->idle_cpus != 1)
9532 return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9535 /* One group has more than one SMT CPU while the other group does not */
9536 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9537 struct sched_group *sg2)
9542 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9543 (sg2->flags & SD_SHARE_CPUCAPACITY);
9546 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9547 struct sched_group *group)
9549 if (env->idle == CPU_NOT_IDLE)
9553 * For SMT source group, it is better to move a task
9554 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9555 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9558 if (group->flags & SD_SHARE_CPUCAPACITY &&
9559 sgs->sum_h_nr_running > 1)
9565 static inline long sibling_imbalance(struct lb_env *env,
9566 struct sd_lb_stats *sds,
9567 struct sg_lb_stats *busiest,
9568 struct sg_lb_stats *local)
9570 int ncores_busiest, ncores_local;
9573 if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9576 ncores_busiest = sds->busiest->cores;
9577 ncores_local = sds->local->cores;
9579 if (ncores_busiest == ncores_local) {
9580 imbalance = busiest->sum_nr_running;
9581 lsub_positive(&imbalance, local->sum_nr_running);
9585 /* Balance such that nr_running/ncores ratio are same on both groups */
9586 imbalance = ncores_local * busiest->sum_nr_running;
9587 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9588 /* Normalize imbalance and do rounding on normalization */
9589 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9590 imbalance /= ncores_local + ncores_busiest;
9592 /* Take advantage of resource in an empty sched group */
9593 if (imbalance <= 1 && local->sum_nr_running == 0 &&
9594 busiest->sum_nr_running > 1)
9601 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9604 * When there is more than 1 task, the group_overloaded case already
9605 * takes care of cpu with reduced capacity
9607 if (rq->cfs.h_nr_running != 1)
9610 return check_cpu_capacity(rq, sd);
9614 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9615 * @env: The load balancing environment.
9616 * @sds: Load-balancing data with statistics of the local group.
9617 * @group: sched_group whose statistics are to be updated.
9618 * @sgs: variable to hold the statistics for this group.
9619 * @sg_status: Holds flag indicating the status of the sched_group
9621 static inline void update_sg_lb_stats(struct lb_env *env,
9622 struct sd_lb_stats *sds,
9623 struct sched_group *group,
9624 struct sg_lb_stats *sgs,
9627 int i, nr_running, local_group;
9629 memset(sgs, 0, sizeof(*sgs));
9631 local_group = group == sds->local;
9633 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9634 struct rq *rq = cpu_rq(i);
9635 unsigned long load = cpu_load(rq);
9637 sgs->group_load += load;
9638 sgs->group_util += cpu_util_cfs(i);
9639 sgs->group_runnable += cpu_runnable(rq);
9640 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9642 nr_running = rq->nr_running;
9643 sgs->sum_nr_running += nr_running;
9646 *sg_status |= SG_OVERLOAD;
9648 if (cpu_overutilized(i))
9649 *sg_status |= SG_OVERUTILIZED;
9651 #ifdef CONFIG_NUMA_BALANCING
9652 sgs->nr_numa_running += rq->nr_numa_running;
9653 sgs->nr_preferred_running += rq->nr_preferred_running;
9656 * No need to call idle_cpu() if nr_running is not 0
9658 if (!nr_running && idle_cpu(i)) {
9660 /* Idle cpu can't have misfit task */
9667 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9668 /* Check for a misfit task on the cpu */
9669 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9670 sgs->group_misfit_task_load = rq->misfit_task_load;
9671 *sg_status |= SG_OVERLOAD;
9673 } else if ((env->idle != CPU_NOT_IDLE) &&
9674 sched_reduced_capacity(rq, env->sd)) {
9675 /* Check for a task running on a CPU with reduced capacity */
9676 if (sgs->group_misfit_task_load < load)
9677 sgs->group_misfit_task_load = load;
9681 sgs->group_capacity = group->sgc->capacity;
9683 sgs->group_weight = group->group_weight;
9685 /* Check if dst CPU is idle and preferred to this group */
9686 if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9687 env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9688 sched_asym(env, sds, sgs, group)) {
9689 sgs->group_asym_packing = 1;
9692 /* Check for loaded SMT group to be balanced to dst CPU */
9693 if (!local_group && smt_balance(env, sgs, group))
9694 sgs->group_smt_balance = 1;
9696 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
9698 /* Computing avg_load makes sense only when group is overloaded */
9699 if (sgs->group_type == group_overloaded)
9700 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9701 sgs->group_capacity;
9705 * update_sd_pick_busiest - return 1 on busiest group
9706 * @env: The load balancing environment.
9707 * @sds: sched_domain statistics
9708 * @sg: sched_group candidate to be checked for being the busiest
9709 * @sgs: sched_group statistics
9711 * Determine if @sg is a busier group than the previously selected
9714 * Return: %true if @sg is a busier group than the previously selected
9715 * busiest group. %false otherwise.
9717 static bool update_sd_pick_busiest(struct lb_env *env,
9718 struct sd_lb_stats *sds,
9719 struct sched_group *sg,
9720 struct sg_lb_stats *sgs)
9722 struct sg_lb_stats *busiest = &sds->busiest_stat;
9724 /* Make sure that there is at least one task to pull */
9725 if (!sgs->sum_h_nr_running)
9729 * Don't try to pull misfit tasks we can't help.
9730 * We can use max_capacity here as reduction in capacity on some
9731 * CPUs in the group should either be possible to resolve
9732 * internally or be covered by avg_load imbalance (eventually).
9734 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9735 (sgs->group_type == group_misfit_task) &&
9736 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
9737 sds->local_stat.group_type != group_has_spare))
9740 if (sgs->group_type > busiest->group_type)
9743 if (sgs->group_type < busiest->group_type)
9747 * The candidate and the current busiest group are the same type of
9748 * group. Let check which one is the busiest according to the type.
9751 switch (sgs->group_type) {
9752 case group_overloaded:
9753 /* Select the overloaded group with highest avg_load. */
9754 if (sgs->avg_load <= busiest->avg_load)
9758 case group_imbalanced:
9760 * Select the 1st imbalanced group as we don't have any way to
9761 * choose one more than another.
9765 case group_asym_packing:
9766 /* Prefer to move from lowest priority CPU's work */
9767 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
9771 case group_misfit_task:
9773 * If we have more than one misfit sg go with the biggest
9776 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
9780 case group_smt_balance:
9782 * Check if we have spare CPUs on either SMT group to
9783 * choose has spare or fully busy handling.
9785 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
9790 case group_fully_busy:
9792 * Select the fully busy group with highest avg_load. In
9793 * theory, there is no need to pull task from such kind of
9794 * group because tasks have all compute capacity that they need
9795 * but we can still improve the overall throughput by reducing
9796 * contention when accessing shared HW resources.
9798 * XXX for now avg_load is not computed and always 0 so we
9799 * select the 1st one, except if @sg is composed of SMT
9803 if (sgs->avg_load < busiest->avg_load)
9806 if (sgs->avg_load == busiest->avg_load) {
9808 * SMT sched groups need more help than non-SMT groups.
9809 * If @sg happens to also be SMT, either choice is good.
9811 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
9817 case group_has_spare:
9819 * Do not pick sg with SMT CPUs over sg with pure CPUs,
9820 * as we do not want to pull task off SMT core with one task
9821 * and make the core idle.
9823 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
9824 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
9832 * Select not overloaded group with lowest number of idle cpus
9833 * and highest number of running tasks. We could also compare
9834 * the spare capacity which is more stable but it can end up
9835 * that the group has less spare capacity but finally more idle
9836 * CPUs which means less opportunity to pull tasks.
9838 if (sgs->idle_cpus > busiest->idle_cpus)
9840 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
9841 (sgs->sum_nr_running <= busiest->sum_nr_running))
9848 * Candidate sg has no more than one task per CPU and has higher
9849 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
9850 * throughput. Maximize throughput, power/energy consequences are not
9853 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9854 (sgs->group_type <= group_fully_busy) &&
9855 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
9861 #ifdef CONFIG_NUMA_BALANCING
9862 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9864 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
9866 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
9871 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9873 if (rq->nr_running > rq->nr_numa_running)
9875 if (rq->nr_running > rq->nr_preferred_running)
9880 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9885 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9889 #endif /* CONFIG_NUMA_BALANCING */
9895 * task_running_on_cpu - return 1 if @p is running on @cpu.
9898 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
9900 /* Task has no contribution or is new */
9901 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9904 if (task_on_rq_queued(p))
9911 * idle_cpu_without - would a given CPU be idle without p ?
9912 * @cpu: the processor on which idleness is tested.
9913 * @p: task which should be ignored.
9915 * Return: 1 if the CPU would be idle. 0 otherwise.
9917 static int idle_cpu_without(int cpu, struct task_struct *p)
9919 struct rq *rq = cpu_rq(cpu);
9921 if (rq->curr != rq->idle && rq->curr != p)
9925 * rq->nr_running can't be used but an updated version without the
9926 * impact of p on cpu must be used instead. The updated nr_running
9927 * be computed and tested before calling idle_cpu_without().
9931 if (rq->ttwu_pending)
9939 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
9940 * @sd: The sched_domain level to look for idlest group.
9941 * @group: sched_group whose statistics are to be updated.
9942 * @sgs: variable to hold the statistics for this group.
9943 * @p: The task for which we look for the idlest group/CPU.
9945 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
9946 struct sched_group *group,
9947 struct sg_lb_stats *sgs,
9948 struct task_struct *p)
9952 memset(sgs, 0, sizeof(*sgs));
9954 /* Assume that task can't fit any CPU of the group */
9955 if (sd->flags & SD_ASYM_CPUCAPACITY)
9956 sgs->group_misfit_task_load = 1;
9958 for_each_cpu(i, sched_group_span(group)) {
9959 struct rq *rq = cpu_rq(i);
9962 sgs->group_load += cpu_load_without(rq, p);
9963 sgs->group_util += cpu_util_without(i, p);
9964 sgs->group_runnable += cpu_runnable_without(rq, p);
9965 local = task_running_on_cpu(i, p);
9966 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
9968 nr_running = rq->nr_running - local;
9969 sgs->sum_nr_running += nr_running;
9972 * No need to call idle_cpu_without() if nr_running is not 0
9974 if (!nr_running && idle_cpu_without(i, p))
9977 /* Check if task fits in the CPU */
9978 if (sd->flags & SD_ASYM_CPUCAPACITY &&
9979 sgs->group_misfit_task_load &&
9980 task_fits_cpu(p, i))
9981 sgs->group_misfit_task_load = 0;
9985 sgs->group_capacity = group->sgc->capacity;
9987 sgs->group_weight = group->group_weight;
9989 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
9992 * Computing avg_load makes sense only when group is fully busy or
9995 if (sgs->group_type == group_fully_busy ||
9996 sgs->group_type == group_overloaded)
9997 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9998 sgs->group_capacity;
10001 static bool update_pick_idlest(struct sched_group *idlest,
10002 struct sg_lb_stats *idlest_sgs,
10003 struct sched_group *group,
10004 struct sg_lb_stats *sgs)
10006 if (sgs->group_type < idlest_sgs->group_type)
10009 if (sgs->group_type > idlest_sgs->group_type)
10013 * The candidate and the current idlest group are the same type of
10014 * group. Let check which one is the idlest according to the type.
10017 switch (sgs->group_type) {
10018 case group_overloaded:
10019 case group_fully_busy:
10020 /* Select the group with lowest avg_load. */
10021 if (idlest_sgs->avg_load <= sgs->avg_load)
10025 case group_imbalanced:
10026 case group_asym_packing:
10027 case group_smt_balance:
10028 /* Those types are not used in the slow wakeup path */
10031 case group_misfit_task:
10032 /* Select group with the highest max capacity */
10033 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10037 case group_has_spare:
10038 /* Select group with most idle CPUs */
10039 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10042 /* Select group with lowest group_util */
10043 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10044 idlest_sgs->group_util <= sgs->group_util)
10054 * find_idlest_group() finds and returns the least busy CPU group within the
10057 * Assumes p is allowed on at least one CPU in sd.
10059 static struct sched_group *
10060 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10062 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10063 struct sg_lb_stats local_sgs, tmp_sgs;
10064 struct sg_lb_stats *sgs;
10065 unsigned long imbalance;
10066 struct sg_lb_stats idlest_sgs = {
10067 .avg_load = UINT_MAX,
10068 .group_type = group_overloaded,
10074 /* Skip over this group if it has no CPUs allowed */
10075 if (!cpumask_intersects(sched_group_span(group),
10079 /* Skip over this group if no cookie matched */
10080 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10083 local_group = cpumask_test_cpu(this_cpu,
10084 sched_group_span(group));
10093 update_sg_wakeup_stats(sd, group, sgs, p);
10095 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10100 } while (group = group->next, group != sd->groups);
10103 /* There is no idlest group to push tasks to */
10107 /* The local group has been skipped because of CPU affinity */
10112 * If the local group is idler than the selected idlest group
10113 * don't try and push the task.
10115 if (local_sgs.group_type < idlest_sgs.group_type)
10119 * If the local group is busier than the selected idlest group
10120 * try and push the task.
10122 if (local_sgs.group_type > idlest_sgs.group_type)
10125 switch (local_sgs.group_type) {
10126 case group_overloaded:
10127 case group_fully_busy:
10129 /* Calculate allowed imbalance based on load */
10130 imbalance = scale_load_down(NICE_0_LOAD) *
10131 (sd->imbalance_pct-100) / 100;
10134 * When comparing groups across NUMA domains, it's possible for
10135 * the local domain to be very lightly loaded relative to the
10136 * remote domains but "imbalance" skews the comparison making
10137 * remote CPUs look much more favourable. When considering
10138 * cross-domain, add imbalance to the load on the remote node
10139 * and consider staying local.
10142 if ((sd->flags & SD_NUMA) &&
10143 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10147 * If the local group is less loaded than the selected
10148 * idlest group don't try and push any tasks.
10150 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10153 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10157 case group_imbalanced:
10158 case group_asym_packing:
10159 case group_smt_balance:
10160 /* Those type are not used in the slow wakeup path */
10163 case group_misfit_task:
10164 /* Select group with the highest max capacity */
10165 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10169 case group_has_spare:
10171 if (sd->flags & SD_NUMA) {
10172 int imb_numa_nr = sd->imb_numa_nr;
10173 #ifdef CONFIG_NUMA_BALANCING
10176 * If there is spare capacity at NUMA, try to select
10177 * the preferred node
10179 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10182 idlest_cpu = cpumask_first(sched_group_span(idlest));
10183 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10185 #endif /* CONFIG_NUMA_BALANCING */
10187 * Otherwise, keep the task close to the wakeup source
10188 * and improve locality if the number of running tasks
10189 * would remain below threshold where an imbalance is
10190 * allowed while accounting for the possibility the
10191 * task is pinned to a subset of CPUs. If there is a
10192 * real need of migration, periodic load balance will
10195 if (p->nr_cpus_allowed != NR_CPUS) {
10196 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10198 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10199 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10202 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10203 if (!adjust_numa_imbalance(imbalance,
10204 local_sgs.sum_nr_running + 1,
10209 #endif /* CONFIG_NUMA */
10212 * Select group with highest number of idle CPUs. We could also
10213 * compare the utilization which is more stable but it can end
10214 * up that the group has less spare capacity but finally more
10215 * idle CPUs which means more opportunity to run task.
10217 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10225 static void update_idle_cpu_scan(struct lb_env *env,
10226 unsigned long sum_util)
10228 struct sched_domain_shared *sd_share;
10229 int llc_weight, pct;
10232 * Update the number of CPUs to scan in LLC domain, which could
10233 * be used as a hint in select_idle_cpu(). The update of sd_share
10234 * could be expensive because it is within a shared cache line.
10235 * So the write of this hint only occurs during periodic load
10236 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10237 * can fire way more frequently than the former.
10239 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10242 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10243 if (env->sd->span_weight != llc_weight)
10246 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10251 * The number of CPUs to search drops as sum_util increases, when
10252 * sum_util hits 85% or above, the scan stops.
10253 * The reason to choose 85% as the threshold is because this is the
10254 * imbalance_pct(117) when a LLC sched group is overloaded.
10256 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10257 * and y'= y / SCHED_CAPACITY_SCALE
10259 * x is the ratio of sum_util compared to the CPU capacity:
10260 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10261 * y' is the ratio of CPUs to be scanned in the LLC domain,
10262 * and the number of CPUs to scan is calculated by:
10264 * nr_scan = llc_weight * y' [2]
10266 * When x hits the threshold of overloaded, AKA, when
10267 * x = 100 / pct, y drops to 0. According to [1],
10268 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10270 * Scale x by SCHED_CAPACITY_SCALE:
10271 * x' = sum_util / llc_weight; [3]
10273 * and finally [1] becomes:
10274 * y = SCHED_CAPACITY_SCALE -
10275 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10280 do_div(x, llc_weight);
10283 pct = env->sd->imbalance_pct;
10284 tmp = x * x * pct * pct;
10285 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10286 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10287 y = SCHED_CAPACITY_SCALE - tmp;
10291 do_div(y, SCHED_CAPACITY_SCALE);
10292 if ((int)y != sd_share->nr_idle_scan)
10293 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10297 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10298 * @env: The load balancing environment.
10299 * @sds: variable to hold the statistics for this sched_domain.
10302 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10304 struct sched_group *sg = env->sd->groups;
10305 struct sg_lb_stats *local = &sds->local_stat;
10306 struct sg_lb_stats tmp_sgs;
10307 unsigned long sum_util = 0;
10311 struct sg_lb_stats *sgs = &tmp_sgs;
10314 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10319 if (env->idle != CPU_NEWLY_IDLE ||
10320 time_after_eq(jiffies, sg->sgc->next_update))
10321 update_group_capacity(env->sd, env->dst_cpu);
10324 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10330 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10332 sds->busiest_stat = *sgs;
10336 /* Now, start updating sd_lb_stats */
10337 sds->total_load += sgs->group_load;
10338 sds->total_capacity += sgs->group_capacity;
10340 sum_util += sgs->group_util;
10342 } while (sg != env->sd->groups);
10345 * Indicate that the child domain of the busiest group prefers tasks
10346 * go to a child's sibling domains first. NB the flags of a sched group
10347 * are those of the child domain.
10350 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10353 if (env->sd->flags & SD_NUMA)
10354 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10356 if (!env->sd->parent) {
10357 struct root_domain *rd = env->dst_rq->rd;
10359 /* update overload indicator if we are at root domain */
10360 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10362 /* Update over-utilization (tipping point, U >= 0) indicator */
10363 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10364 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10365 } else if (sg_status & SG_OVERUTILIZED) {
10366 struct root_domain *rd = env->dst_rq->rd;
10368 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10369 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10372 update_idle_cpu_scan(env, sum_util);
10376 * calculate_imbalance - Calculate the amount of imbalance present within the
10377 * groups of a given sched_domain during load balance.
10378 * @env: load balance environment
10379 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10381 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10383 struct sg_lb_stats *local, *busiest;
10385 local = &sds->local_stat;
10386 busiest = &sds->busiest_stat;
10388 if (busiest->group_type == group_misfit_task) {
10389 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10390 /* Set imbalance to allow misfit tasks to be balanced. */
10391 env->migration_type = migrate_misfit;
10392 env->imbalance = 1;
10395 * Set load imbalance to allow moving task from cpu
10396 * with reduced capacity.
10398 env->migration_type = migrate_load;
10399 env->imbalance = busiest->group_misfit_task_load;
10404 if (busiest->group_type == group_asym_packing) {
10406 * In case of asym capacity, we will try to migrate all load to
10407 * the preferred CPU.
10409 env->migration_type = migrate_task;
10410 env->imbalance = busiest->sum_h_nr_running;
10414 if (busiest->group_type == group_smt_balance) {
10415 /* Reduce number of tasks sharing CPU capacity */
10416 env->migration_type = migrate_task;
10417 env->imbalance = 1;
10421 if (busiest->group_type == group_imbalanced) {
10423 * In the group_imb case we cannot rely on group-wide averages
10424 * to ensure CPU-load equilibrium, try to move any task to fix
10425 * the imbalance. The next load balance will take care of
10426 * balancing back the system.
10428 env->migration_type = migrate_task;
10429 env->imbalance = 1;
10434 * Try to use spare capacity of local group without overloading it or
10435 * emptying busiest.
10437 if (local->group_type == group_has_spare) {
10438 if ((busiest->group_type > group_fully_busy) &&
10439 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10441 * If busiest is overloaded, try to fill spare
10442 * capacity. This might end up creating spare capacity
10443 * in busiest or busiest still being overloaded but
10444 * there is no simple way to directly compute the
10445 * amount of load to migrate in order to balance the
10448 env->migration_type = migrate_util;
10449 env->imbalance = max(local->group_capacity, local->group_util) -
10453 * In some cases, the group's utilization is max or even
10454 * higher than capacity because of migrations but the
10455 * local CPU is (newly) idle. There is at least one
10456 * waiting task in this overloaded busiest group. Let's
10459 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10460 env->migration_type = migrate_task;
10461 env->imbalance = 1;
10467 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10469 * When prefer sibling, evenly spread running tasks on
10472 env->migration_type = migrate_task;
10473 env->imbalance = sibling_imbalance(env, sds, busiest, local);
10477 * If there is no overload, we just want to even the number of
10480 env->migration_type = migrate_task;
10481 env->imbalance = max_t(long, 0,
10482 (local->idle_cpus - busiest->idle_cpus));
10486 /* Consider allowing a small imbalance between NUMA groups */
10487 if (env->sd->flags & SD_NUMA) {
10488 env->imbalance = adjust_numa_imbalance(env->imbalance,
10489 local->sum_nr_running + 1,
10490 env->sd->imb_numa_nr);
10494 /* Number of tasks to move to restore balance */
10495 env->imbalance >>= 1;
10501 * Local is fully busy but has to take more load to relieve the
10504 if (local->group_type < group_overloaded) {
10506 * Local will become overloaded so the avg_load metrics are
10510 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10511 local->group_capacity;
10514 * If the local group is more loaded than the selected
10515 * busiest group don't try to pull any tasks.
10517 if (local->avg_load >= busiest->avg_load) {
10518 env->imbalance = 0;
10522 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10523 sds->total_capacity;
10526 * If the local group is more loaded than the average system
10527 * load, don't try to pull any tasks.
10529 if (local->avg_load >= sds->avg_load) {
10530 env->imbalance = 0;
10537 * Both group are or will become overloaded and we're trying to get all
10538 * the CPUs to the average_load, so we don't want to push ourselves
10539 * above the average load, nor do we wish to reduce the max loaded CPU
10540 * below the average load. At the same time, we also don't want to
10541 * reduce the group load below the group capacity. Thus we look for
10542 * the minimum possible imbalance.
10544 env->migration_type = migrate_load;
10545 env->imbalance = min(
10546 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10547 (sds->avg_load - local->avg_load) * local->group_capacity
10548 ) / SCHED_CAPACITY_SCALE;
10551 /******* find_busiest_group() helpers end here *********************/
10554 * Decision matrix according to the local and busiest group type:
10556 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10557 * has_spare nr_idle balanced N/A N/A balanced balanced
10558 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
10559 * misfit_task force N/A N/A N/A N/A N/A
10560 * asym_packing force force N/A N/A force force
10561 * imbalanced force force N/A N/A force force
10562 * overloaded force force N/A N/A force avg_load
10564 * N/A : Not Applicable because already filtered while updating
10566 * balanced : The system is balanced for these 2 groups.
10567 * force : Calculate the imbalance as load migration is probably needed.
10568 * avg_load : Only if imbalance is significant enough.
10569 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
10570 * different in groups.
10574 * find_busiest_group - Returns the busiest group within the sched_domain
10575 * if there is an imbalance.
10576 * @env: The load balancing environment.
10578 * Also calculates the amount of runnable load which should be moved
10579 * to restore balance.
10581 * Return: - The busiest group if imbalance exists.
10583 static struct sched_group *find_busiest_group(struct lb_env *env)
10585 struct sg_lb_stats *local, *busiest;
10586 struct sd_lb_stats sds;
10588 init_sd_lb_stats(&sds);
10591 * Compute the various statistics relevant for load balancing at
10594 update_sd_lb_stats(env, &sds);
10596 /* There is no busy sibling group to pull tasks from */
10600 busiest = &sds.busiest_stat;
10602 /* Misfit tasks should be dealt with regardless of the avg load */
10603 if (busiest->group_type == group_misfit_task)
10604 goto force_balance;
10606 if (sched_energy_enabled()) {
10607 struct root_domain *rd = env->dst_rq->rd;
10609 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10613 /* ASYM feature bypasses nice load balance check */
10614 if (busiest->group_type == group_asym_packing)
10615 goto force_balance;
10618 * If the busiest group is imbalanced the below checks don't
10619 * work because they assume all things are equal, which typically
10620 * isn't true due to cpus_ptr constraints and the like.
10622 if (busiest->group_type == group_imbalanced)
10623 goto force_balance;
10625 local = &sds.local_stat;
10627 * If the local group is busier than the selected busiest group
10628 * don't try and pull any tasks.
10630 if (local->group_type > busiest->group_type)
10634 * When groups are overloaded, use the avg_load to ensure fairness
10637 if (local->group_type == group_overloaded) {
10639 * If the local group is more loaded than the selected
10640 * busiest group don't try to pull any tasks.
10642 if (local->avg_load >= busiest->avg_load)
10645 /* XXX broken for overlapping NUMA groups */
10646 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10647 sds.total_capacity;
10650 * Don't pull any tasks if this group is already above the
10651 * domain average load.
10653 if (local->avg_load >= sds.avg_load)
10657 * If the busiest group is more loaded, use imbalance_pct to be
10660 if (100 * busiest->avg_load <=
10661 env->sd->imbalance_pct * local->avg_load)
10666 * Try to move all excess tasks to a sibling domain of the busiest
10667 * group's child domain.
10669 if (sds.prefer_sibling && local->group_type == group_has_spare &&
10670 sibling_imbalance(env, &sds, busiest, local) > 1)
10671 goto force_balance;
10673 if (busiest->group_type != group_overloaded) {
10674 if (env->idle == CPU_NOT_IDLE) {
10676 * If the busiest group is not overloaded (and as a
10677 * result the local one too) but this CPU is already
10678 * busy, let another idle CPU try to pull task.
10683 if (busiest->group_type == group_smt_balance &&
10684 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10685 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10686 goto force_balance;
10689 if (busiest->group_weight > 1 &&
10690 local->idle_cpus <= (busiest->idle_cpus + 1)) {
10692 * If the busiest group is not overloaded
10693 * and there is no imbalance between this and busiest
10694 * group wrt idle CPUs, it is balanced. The imbalance
10695 * becomes significant if the diff is greater than 1
10696 * otherwise we might end up to just move the imbalance
10697 * on another group. Of course this applies only if
10698 * there is more than 1 CPU per group.
10703 if (busiest->sum_h_nr_running == 1) {
10705 * busiest doesn't have any tasks waiting to run
10712 /* Looks like there is an imbalance. Compute it */
10713 calculate_imbalance(env, &sds);
10714 return env->imbalance ? sds.busiest : NULL;
10717 env->imbalance = 0;
10722 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
10724 static struct rq *find_busiest_queue(struct lb_env *env,
10725 struct sched_group *group)
10727 struct rq *busiest = NULL, *rq;
10728 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
10729 unsigned int busiest_nr = 0;
10732 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10733 unsigned long capacity, load, util;
10734 unsigned int nr_running;
10738 rt = fbq_classify_rq(rq);
10741 * We classify groups/runqueues into three groups:
10742 * - regular: there are !numa tasks
10743 * - remote: there are numa tasks that run on the 'wrong' node
10744 * - all: there is no distinction
10746 * In order to avoid migrating ideally placed numa tasks,
10747 * ignore those when there's better options.
10749 * If we ignore the actual busiest queue to migrate another
10750 * task, the next balance pass can still reduce the busiest
10751 * queue by moving tasks around inside the node.
10753 * If we cannot move enough load due to this classification
10754 * the next pass will adjust the group classification and
10755 * allow migration of more tasks.
10757 * Both cases only affect the total convergence complexity.
10759 if (rt > env->fbq_type)
10762 nr_running = rq->cfs.h_nr_running;
10766 capacity = capacity_of(i);
10769 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
10770 * eventually lead to active_balancing high->low capacity.
10771 * Higher per-CPU capacity is considered better than balancing
10774 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
10775 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
10780 * Make sure we only pull tasks from a CPU of lower priority
10781 * when balancing between SMT siblings.
10783 * If balancing between cores, let lower priority CPUs help
10784 * SMT cores with more than one busy sibling.
10786 if ((env->sd->flags & SD_ASYM_PACKING) &&
10787 sched_use_asym_prio(env->sd, i) &&
10788 sched_asym_prefer(i, env->dst_cpu) &&
10792 switch (env->migration_type) {
10795 * When comparing with load imbalance, use cpu_load()
10796 * which is not scaled with the CPU capacity.
10798 load = cpu_load(rq);
10800 if (nr_running == 1 && load > env->imbalance &&
10801 !check_cpu_capacity(rq, env->sd))
10805 * For the load comparisons with the other CPUs,
10806 * consider the cpu_load() scaled with the CPU
10807 * capacity, so that the load can be moved away
10808 * from the CPU that is potentially running at a
10811 * Thus we're looking for max(load_i / capacity_i),
10812 * crosswise multiplication to rid ourselves of the
10813 * division works out to:
10814 * load_i * capacity_j > load_j * capacity_i;
10815 * where j is our previous maximum.
10817 if (load * busiest_capacity > busiest_load * capacity) {
10818 busiest_load = load;
10819 busiest_capacity = capacity;
10825 util = cpu_util_cfs_boost(i);
10828 * Don't try to pull utilization from a CPU with one
10829 * running task. Whatever its utilization, we will fail
10832 if (nr_running <= 1)
10835 if (busiest_util < util) {
10836 busiest_util = util;
10842 if (busiest_nr < nr_running) {
10843 busiest_nr = nr_running;
10848 case migrate_misfit:
10850 * For ASYM_CPUCAPACITY domains with misfit tasks we
10851 * simply seek the "biggest" misfit task.
10853 if (rq->misfit_task_load > busiest_load) {
10854 busiest_load = rq->misfit_task_load;
10867 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
10868 * so long as it is large enough.
10870 #define MAX_PINNED_INTERVAL 512
10873 asym_active_balance(struct lb_env *env)
10876 * ASYM_PACKING needs to force migrate tasks from busy but lower
10877 * priority CPUs in order to pack all tasks in the highest priority
10878 * CPUs. When done between cores, do it only if the whole core if the
10879 * whole core is idle.
10881 * If @env::src_cpu is an SMT core with busy siblings, let
10882 * the lower priority @env::dst_cpu help it. Do not follow
10885 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
10886 sched_use_asym_prio(env->sd, env->dst_cpu) &&
10887 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
10888 !sched_use_asym_prio(env->sd, env->src_cpu));
10892 imbalanced_active_balance(struct lb_env *env)
10894 struct sched_domain *sd = env->sd;
10897 * The imbalanced case includes the case of pinned tasks preventing a fair
10898 * distribution of the load on the system but also the even distribution of the
10899 * threads on a system with spare capacity
10901 if ((env->migration_type == migrate_task) &&
10902 (sd->nr_balance_failed > sd->cache_nice_tries+2))
10908 static int need_active_balance(struct lb_env *env)
10910 struct sched_domain *sd = env->sd;
10912 if (asym_active_balance(env))
10915 if (imbalanced_active_balance(env))
10919 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
10920 * It's worth migrating the task if the src_cpu's capacity is reduced
10921 * because of other sched_class or IRQs if more capacity stays
10922 * available on dst_cpu.
10924 if ((env->idle != CPU_NOT_IDLE) &&
10925 (env->src_rq->cfs.h_nr_running == 1)) {
10926 if ((check_cpu_capacity(env->src_rq, sd)) &&
10927 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
10931 if (env->migration_type == migrate_misfit)
10937 static int active_load_balance_cpu_stop(void *data);
10939 static int should_we_balance(struct lb_env *env)
10941 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
10942 struct sched_group *sg = env->sd->groups;
10943 int cpu, idle_smt = -1;
10946 * Ensure the balancing environment is consistent; can happen
10947 * when the softirq triggers 'during' hotplug.
10949 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
10953 * In the newly idle case, we will allow all the CPUs
10954 * to do the newly idle load balance.
10956 * However, we bail out if we already have tasks or a wakeup pending,
10957 * to optimize wakeup latency.
10959 if (env->idle == CPU_NEWLY_IDLE) {
10960 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
10965 cpumask_copy(swb_cpus, group_balance_mask(sg));
10966 /* Try to find first idle CPU */
10967 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
10968 if (!idle_cpu(cpu))
10972 * Don't balance to idle SMT in busy core right away when
10973 * balancing cores, but remember the first idle SMT CPU for
10974 * later consideration. Find CPU on an idle core first.
10976 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
10977 if (idle_smt == -1)
10980 * If the core is not idle, and first SMT sibling which is
10981 * idle has been found, then its not needed to check other
10982 * SMT siblings for idleness:
10984 #ifdef CONFIG_SCHED_SMT
10985 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
10990 /* Are we the first idle CPU? */
10991 return cpu == env->dst_cpu;
10994 if (idle_smt == env->dst_cpu)
10997 /* Are we the first CPU of this group ? */
10998 return group_balance_cpu(sg) == env->dst_cpu;
11002 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11003 * tasks if there is an imbalance.
11005 static int load_balance(int this_cpu, struct rq *this_rq,
11006 struct sched_domain *sd, enum cpu_idle_type idle,
11007 int *continue_balancing)
11009 int ld_moved, cur_ld_moved, active_balance = 0;
11010 struct sched_domain *sd_parent = sd->parent;
11011 struct sched_group *group;
11012 struct rq *busiest;
11013 struct rq_flags rf;
11014 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11015 struct lb_env env = {
11017 .dst_cpu = this_cpu,
11019 .dst_grpmask = group_balance_mask(sd->groups),
11021 .loop_break = SCHED_NR_MIGRATE_BREAK,
11024 .tasks = LIST_HEAD_INIT(env.tasks),
11027 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11029 schedstat_inc(sd->lb_count[idle]);
11032 if (!should_we_balance(&env)) {
11033 *continue_balancing = 0;
11037 group = find_busiest_group(&env);
11039 schedstat_inc(sd->lb_nobusyg[idle]);
11043 busiest = find_busiest_queue(&env, group);
11045 schedstat_inc(sd->lb_nobusyq[idle]);
11049 WARN_ON_ONCE(busiest == env.dst_rq);
11051 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11053 env.src_cpu = busiest->cpu;
11054 env.src_rq = busiest;
11057 /* Clear this flag as soon as we find a pullable task */
11058 env.flags |= LBF_ALL_PINNED;
11059 if (busiest->nr_running > 1) {
11061 * Attempt to move tasks. If find_busiest_group has found
11062 * an imbalance but busiest->nr_running <= 1, the group is
11063 * still unbalanced. ld_moved simply stays zero, so it is
11064 * correctly treated as an imbalance.
11066 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11069 rq_lock_irqsave(busiest, &rf);
11070 update_rq_clock(busiest);
11073 * cur_ld_moved - load moved in current iteration
11074 * ld_moved - cumulative load moved across iterations
11076 cur_ld_moved = detach_tasks(&env);
11079 * We've detached some tasks from busiest_rq. Every
11080 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11081 * unlock busiest->lock, and we are able to be sure
11082 * that nobody can manipulate the tasks in parallel.
11083 * See task_rq_lock() family for the details.
11086 rq_unlock(busiest, &rf);
11088 if (cur_ld_moved) {
11089 attach_tasks(&env);
11090 ld_moved += cur_ld_moved;
11093 local_irq_restore(rf.flags);
11095 if (env.flags & LBF_NEED_BREAK) {
11096 env.flags &= ~LBF_NEED_BREAK;
11097 /* Stop if we tried all running tasks */
11098 if (env.loop < busiest->nr_running)
11103 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11104 * us and move them to an alternate dst_cpu in our sched_group
11105 * where they can run. The upper limit on how many times we
11106 * iterate on same src_cpu is dependent on number of CPUs in our
11109 * This changes load balance semantics a bit on who can move
11110 * load to a given_cpu. In addition to the given_cpu itself
11111 * (or a ilb_cpu acting on its behalf where given_cpu is
11112 * nohz-idle), we now have balance_cpu in a position to move
11113 * load to given_cpu. In rare situations, this may cause
11114 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11115 * _independently_ and at _same_ time to move some load to
11116 * given_cpu) causing excess load to be moved to given_cpu.
11117 * This however should not happen so much in practice and
11118 * moreover subsequent load balance cycles should correct the
11119 * excess load moved.
11121 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11123 /* Prevent to re-select dst_cpu via env's CPUs */
11124 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11126 env.dst_rq = cpu_rq(env.new_dst_cpu);
11127 env.dst_cpu = env.new_dst_cpu;
11128 env.flags &= ~LBF_DST_PINNED;
11130 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11133 * Go back to "more_balance" rather than "redo" since we
11134 * need to continue with same src_cpu.
11140 * We failed to reach balance because of affinity.
11143 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11145 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11146 *group_imbalance = 1;
11149 /* All tasks on this runqueue were pinned by CPU affinity */
11150 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11151 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11153 * Attempting to continue load balancing at the current
11154 * sched_domain level only makes sense if there are
11155 * active CPUs remaining as possible busiest CPUs to
11156 * pull load from which are not contained within the
11157 * destination group that is receiving any migrated
11160 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11162 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11165 goto out_all_pinned;
11170 schedstat_inc(sd->lb_failed[idle]);
11172 * Increment the failure counter only on periodic balance.
11173 * We do not want newidle balance, which can be very
11174 * frequent, pollute the failure counter causing
11175 * excessive cache_hot migrations and active balances.
11177 if (idle != CPU_NEWLY_IDLE)
11178 sd->nr_balance_failed++;
11180 if (need_active_balance(&env)) {
11181 unsigned long flags;
11183 raw_spin_rq_lock_irqsave(busiest, flags);
11186 * Don't kick the active_load_balance_cpu_stop,
11187 * if the curr task on busiest CPU can't be
11188 * moved to this_cpu:
11190 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11191 raw_spin_rq_unlock_irqrestore(busiest, flags);
11192 goto out_one_pinned;
11195 /* Record that we found at least one task that could run on this_cpu */
11196 env.flags &= ~LBF_ALL_PINNED;
11199 * ->active_balance synchronizes accesses to
11200 * ->active_balance_work. Once set, it's cleared
11201 * only after active load balance is finished.
11203 if (!busiest->active_balance) {
11204 busiest->active_balance = 1;
11205 busiest->push_cpu = this_cpu;
11206 active_balance = 1;
11208 raw_spin_rq_unlock_irqrestore(busiest, flags);
11210 if (active_balance) {
11211 stop_one_cpu_nowait(cpu_of(busiest),
11212 active_load_balance_cpu_stop, busiest,
11213 &busiest->active_balance_work);
11217 sd->nr_balance_failed = 0;
11220 if (likely(!active_balance) || need_active_balance(&env)) {
11221 /* We were unbalanced, so reset the balancing interval */
11222 sd->balance_interval = sd->min_interval;
11229 * We reach balance although we may have faced some affinity
11230 * constraints. Clear the imbalance flag only if other tasks got
11231 * a chance to move and fix the imbalance.
11233 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11234 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11236 if (*group_imbalance)
11237 *group_imbalance = 0;
11242 * We reach balance because all tasks are pinned at this level so
11243 * we can't migrate them. Let the imbalance flag set so parent level
11244 * can try to migrate them.
11246 schedstat_inc(sd->lb_balanced[idle]);
11248 sd->nr_balance_failed = 0;
11254 * newidle_balance() disregards balance intervals, so we could
11255 * repeatedly reach this code, which would lead to balance_interval
11256 * skyrocketing in a short amount of time. Skip the balance_interval
11257 * increase logic to avoid that.
11259 if (env.idle == CPU_NEWLY_IDLE)
11262 /* tune up the balancing interval */
11263 if ((env.flags & LBF_ALL_PINNED &&
11264 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11265 sd->balance_interval < sd->max_interval)
11266 sd->balance_interval *= 2;
11271 static inline unsigned long
11272 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11274 unsigned long interval = sd->balance_interval;
11277 interval *= sd->busy_factor;
11279 /* scale ms to jiffies */
11280 interval = msecs_to_jiffies(interval);
11283 * Reduce likelihood of busy balancing at higher domains racing with
11284 * balancing at lower domains by preventing their balancing periods
11285 * from being multiples of each other.
11290 interval = clamp(interval, 1UL, max_load_balance_interval);
11296 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11298 unsigned long interval, next;
11300 /* used by idle balance, so cpu_busy = 0 */
11301 interval = get_sd_balance_interval(sd, 0);
11302 next = sd->last_balance + interval;
11304 if (time_after(*next_balance, next))
11305 *next_balance = next;
11309 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11310 * running tasks off the busiest CPU onto idle CPUs. It requires at
11311 * least 1 task to be running on each physical CPU where possible, and
11312 * avoids physical / logical imbalances.
11314 static int active_load_balance_cpu_stop(void *data)
11316 struct rq *busiest_rq = data;
11317 int busiest_cpu = cpu_of(busiest_rq);
11318 int target_cpu = busiest_rq->push_cpu;
11319 struct rq *target_rq = cpu_rq(target_cpu);
11320 struct sched_domain *sd;
11321 struct task_struct *p = NULL;
11322 struct rq_flags rf;
11324 rq_lock_irq(busiest_rq, &rf);
11326 * Between queueing the stop-work and running it is a hole in which
11327 * CPUs can become inactive. We should not move tasks from or to
11330 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11333 /* Make sure the requested CPU hasn't gone down in the meantime: */
11334 if (unlikely(busiest_cpu != smp_processor_id() ||
11335 !busiest_rq->active_balance))
11338 /* Is there any task to move? */
11339 if (busiest_rq->nr_running <= 1)
11343 * This condition is "impossible", if it occurs
11344 * we need to fix it. Originally reported by
11345 * Bjorn Helgaas on a 128-CPU setup.
11347 WARN_ON_ONCE(busiest_rq == target_rq);
11349 /* Search for an sd spanning us and the target CPU. */
11351 for_each_domain(target_cpu, sd) {
11352 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11357 struct lb_env env = {
11359 .dst_cpu = target_cpu,
11360 .dst_rq = target_rq,
11361 .src_cpu = busiest_rq->cpu,
11362 .src_rq = busiest_rq,
11364 .flags = LBF_ACTIVE_LB,
11367 schedstat_inc(sd->alb_count);
11368 update_rq_clock(busiest_rq);
11370 p = detach_one_task(&env);
11372 schedstat_inc(sd->alb_pushed);
11373 /* Active balancing done, reset the failure counter. */
11374 sd->nr_balance_failed = 0;
11376 schedstat_inc(sd->alb_failed);
11381 busiest_rq->active_balance = 0;
11382 rq_unlock(busiest_rq, &rf);
11385 attach_one_task(target_rq, p);
11387 local_irq_enable();
11392 static DEFINE_SPINLOCK(balancing);
11395 * Scale the max load_balance interval with the number of CPUs in the system.
11396 * This trades load-balance latency on larger machines for less cross talk.
11398 void update_max_interval(void)
11400 max_load_balance_interval = HZ*num_online_cpus()/10;
11403 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11405 if (cost > sd->max_newidle_lb_cost) {
11407 * Track max cost of a domain to make sure to not delay the
11408 * next wakeup on the CPU.
11410 sd->max_newidle_lb_cost = cost;
11411 sd->last_decay_max_lb_cost = jiffies;
11412 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11414 * Decay the newidle max times by ~1% per second to ensure that
11415 * it is not outdated and the current max cost is actually
11418 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11419 sd->last_decay_max_lb_cost = jiffies;
11428 * It checks each scheduling domain to see if it is due to be balanced,
11429 * and initiates a balancing operation if so.
11431 * Balancing parameters are set up in init_sched_domains.
11433 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11435 int continue_balancing = 1;
11437 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11438 unsigned long interval;
11439 struct sched_domain *sd;
11440 /* Earliest time when we have to do rebalance again */
11441 unsigned long next_balance = jiffies + 60*HZ;
11442 int update_next_balance = 0;
11443 int need_serialize, need_decay = 0;
11447 for_each_domain(cpu, sd) {
11449 * Decay the newidle max times here because this is a regular
11450 * visit to all the domains.
11452 need_decay = update_newidle_cost(sd, 0);
11453 max_cost += sd->max_newidle_lb_cost;
11456 * Stop the load balance at this level. There is another
11457 * CPU in our sched group which is doing load balancing more
11460 if (!continue_balancing) {
11466 interval = get_sd_balance_interval(sd, busy);
11468 need_serialize = sd->flags & SD_SERIALIZE;
11469 if (need_serialize) {
11470 if (!spin_trylock(&balancing))
11474 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11475 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11477 * The LBF_DST_PINNED logic could have changed
11478 * env->dst_cpu, so we can't know our idle
11479 * state even if we migrated tasks. Update it.
11481 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11482 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11484 sd->last_balance = jiffies;
11485 interval = get_sd_balance_interval(sd, busy);
11487 if (need_serialize)
11488 spin_unlock(&balancing);
11490 if (time_after(next_balance, sd->last_balance + interval)) {
11491 next_balance = sd->last_balance + interval;
11492 update_next_balance = 1;
11497 * Ensure the rq-wide value also decays but keep it at a
11498 * reasonable floor to avoid funnies with rq->avg_idle.
11500 rq->max_idle_balance_cost =
11501 max((u64)sysctl_sched_migration_cost, max_cost);
11506 * next_balance will be updated only when there is a need.
11507 * When the cpu is attached to null domain for ex, it will not be
11510 if (likely(update_next_balance))
11511 rq->next_balance = next_balance;
11515 static inline int on_null_domain(struct rq *rq)
11517 return unlikely(!rcu_dereference_sched(rq->sd));
11520 #ifdef CONFIG_NO_HZ_COMMON
11522 * idle load balancing details
11523 * - When one of the busy CPUs notice that there may be an idle rebalancing
11524 * needed, they will kick the idle load balancer, which then does idle
11525 * load balancing for all the idle CPUs.
11526 * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED not set
11530 static inline int find_new_ilb(void)
11533 const struct cpumask *hk_mask;
11535 hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11537 for_each_cpu_and(ilb, nohz.idle_cpus_mask, hk_mask) {
11539 if (ilb == smp_processor_id())
11550 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
11551 * idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11553 static void kick_ilb(unsigned int flags)
11558 * Increase nohz.next_balance only when if full ilb is triggered but
11559 * not if we only update stats.
11561 if (flags & NOHZ_BALANCE_KICK)
11562 nohz.next_balance = jiffies+1;
11564 ilb_cpu = find_new_ilb();
11566 if (ilb_cpu >= nr_cpu_ids)
11570 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11571 * the first flag owns it; cleared by nohz_csd_func().
11573 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11574 if (flags & NOHZ_KICK_MASK)
11578 * This way we generate an IPI on the target CPU which
11579 * is idle. And the softirq performing nohz idle load balance
11580 * will be run before returning from the IPI.
11582 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11586 * Current decision point for kicking the idle load balancer in the presence
11587 * of idle CPUs in the system.
11589 static void nohz_balancer_kick(struct rq *rq)
11591 unsigned long now = jiffies;
11592 struct sched_domain_shared *sds;
11593 struct sched_domain *sd;
11594 int nr_busy, i, cpu = rq->cpu;
11595 unsigned int flags = 0;
11597 if (unlikely(rq->idle_balance))
11601 * We may be recently in ticked or tickless idle mode. At the first
11602 * busy tick after returning from idle, we will update the busy stats.
11604 nohz_balance_exit_idle(rq);
11607 * None are in tickless mode and hence no need for NOHZ idle load
11610 if (likely(!atomic_read(&nohz.nr_cpus)))
11613 if (READ_ONCE(nohz.has_blocked) &&
11614 time_after(now, READ_ONCE(nohz.next_blocked)))
11615 flags = NOHZ_STATS_KICK;
11617 if (time_before(now, nohz.next_balance))
11620 if (rq->nr_running >= 2) {
11621 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11627 sd = rcu_dereference(rq->sd);
11630 * If there's a CFS task and the current CPU has reduced
11631 * capacity; kick the ILB to see if there's a better CPU to run
11634 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11635 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11640 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11643 * When ASYM_PACKING; see if there's a more preferred CPU
11644 * currently idle; in which case, kick the ILB to move tasks
11647 * When balancing betwen cores, all the SMT siblings of the
11648 * preferred CPU must be idle.
11650 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11651 if (sched_use_asym_prio(sd, i) &&
11652 sched_asym_prefer(i, cpu)) {
11653 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11659 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11662 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11663 * to run the misfit task on.
11665 if (check_misfit_status(rq, sd)) {
11666 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11671 * For asymmetric systems, we do not want to nicely balance
11672 * cache use, instead we want to embrace asymmetry and only
11673 * ensure tasks have enough CPU capacity.
11675 * Skip the LLC logic because it's not relevant in that case.
11680 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11683 * If there is an imbalance between LLC domains (IOW we could
11684 * increase the overall cache use), we need some less-loaded LLC
11685 * domain to pull some load. Likewise, we may need to spread
11686 * load within the current LLC domain (e.g. packed SMT cores but
11687 * other CPUs are idle). We can't really know from here how busy
11688 * the others are - so just get a nohz balance going if it looks
11689 * like this LLC domain has tasks we could move.
11691 nr_busy = atomic_read(&sds->nr_busy_cpus);
11693 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11700 if (READ_ONCE(nohz.needs_update))
11701 flags |= NOHZ_NEXT_KICK;
11707 static void set_cpu_sd_state_busy(int cpu)
11709 struct sched_domain *sd;
11712 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11714 if (!sd || !sd->nohz_idle)
11718 atomic_inc(&sd->shared->nr_busy_cpus);
11723 void nohz_balance_exit_idle(struct rq *rq)
11725 SCHED_WARN_ON(rq != this_rq());
11727 if (likely(!rq->nohz_tick_stopped))
11730 rq->nohz_tick_stopped = 0;
11731 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
11732 atomic_dec(&nohz.nr_cpus);
11734 set_cpu_sd_state_busy(rq->cpu);
11737 static void set_cpu_sd_state_idle(int cpu)
11739 struct sched_domain *sd;
11742 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11744 if (!sd || sd->nohz_idle)
11748 atomic_dec(&sd->shared->nr_busy_cpus);
11754 * This routine will record that the CPU is going idle with tick stopped.
11755 * This info will be used in performing idle load balancing in the future.
11757 void nohz_balance_enter_idle(int cpu)
11759 struct rq *rq = cpu_rq(cpu);
11761 SCHED_WARN_ON(cpu != smp_processor_id());
11763 /* If this CPU is going down, then nothing needs to be done: */
11764 if (!cpu_active(cpu))
11767 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
11768 if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
11772 * Can be set safely without rq->lock held
11773 * If a clear happens, it will have evaluated last additions because
11774 * rq->lock is held during the check and the clear
11776 rq->has_blocked_load = 1;
11779 * The tick is still stopped but load could have been added in the
11780 * meantime. We set the nohz.has_blocked flag to trig a check of the
11781 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
11782 * of nohz.has_blocked can only happen after checking the new load
11784 if (rq->nohz_tick_stopped)
11787 /* If we're a completely isolated CPU, we don't play: */
11788 if (on_null_domain(rq))
11791 rq->nohz_tick_stopped = 1;
11793 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
11794 atomic_inc(&nohz.nr_cpus);
11797 * Ensures that if nohz_idle_balance() fails to observe our
11798 * @idle_cpus_mask store, it must observe the @has_blocked
11799 * and @needs_update stores.
11801 smp_mb__after_atomic();
11803 set_cpu_sd_state_idle(cpu);
11805 WRITE_ONCE(nohz.needs_update, 1);
11808 * Each time a cpu enter idle, we assume that it has blocked load and
11809 * enable the periodic update of the load of idle cpus
11811 WRITE_ONCE(nohz.has_blocked, 1);
11814 static bool update_nohz_stats(struct rq *rq)
11816 unsigned int cpu = rq->cpu;
11818 if (!rq->has_blocked_load)
11821 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
11824 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
11827 update_blocked_averages(cpu);
11829 return rq->has_blocked_load;
11833 * Internal function that runs load balance for all idle cpus. The load balance
11834 * can be a simple update of blocked load or a complete load balance with
11835 * tasks movement depending of flags.
11837 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
11839 /* Earliest time when we have to do rebalance again */
11840 unsigned long now = jiffies;
11841 unsigned long next_balance = now + 60*HZ;
11842 bool has_blocked_load = false;
11843 int update_next_balance = 0;
11844 int this_cpu = this_rq->cpu;
11848 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
11851 * We assume there will be no idle load after this update and clear
11852 * the has_blocked flag. If a cpu enters idle in the mean time, it will
11853 * set the has_blocked flag and trigger another update of idle load.
11854 * Because a cpu that becomes idle, is added to idle_cpus_mask before
11855 * setting the flag, we are sure to not clear the state and not
11856 * check the load of an idle cpu.
11858 * Same applies to idle_cpus_mask vs needs_update.
11860 if (flags & NOHZ_STATS_KICK)
11861 WRITE_ONCE(nohz.has_blocked, 0);
11862 if (flags & NOHZ_NEXT_KICK)
11863 WRITE_ONCE(nohz.needs_update, 0);
11866 * Ensures that if we miss the CPU, we must see the has_blocked
11867 * store from nohz_balance_enter_idle().
11872 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
11873 * chance for other idle cpu to pull load.
11875 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
11876 if (!idle_cpu(balance_cpu))
11880 * If this CPU gets work to do, stop the load balancing
11881 * work being done for other CPUs. Next load
11882 * balancing owner will pick it up.
11884 if (need_resched()) {
11885 if (flags & NOHZ_STATS_KICK)
11886 has_blocked_load = true;
11887 if (flags & NOHZ_NEXT_KICK)
11888 WRITE_ONCE(nohz.needs_update, 1);
11892 rq = cpu_rq(balance_cpu);
11894 if (flags & NOHZ_STATS_KICK)
11895 has_blocked_load |= update_nohz_stats(rq);
11898 * If time for next balance is due,
11901 if (time_after_eq(jiffies, rq->next_balance)) {
11902 struct rq_flags rf;
11904 rq_lock_irqsave(rq, &rf);
11905 update_rq_clock(rq);
11906 rq_unlock_irqrestore(rq, &rf);
11908 if (flags & NOHZ_BALANCE_KICK)
11909 rebalance_domains(rq, CPU_IDLE);
11912 if (time_after(next_balance, rq->next_balance)) {
11913 next_balance = rq->next_balance;
11914 update_next_balance = 1;
11919 * next_balance will be updated only when there is a need.
11920 * When the CPU is attached to null domain for ex, it will not be
11923 if (likely(update_next_balance))
11924 nohz.next_balance = next_balance;
11926 if (flags & NOHZ_STATS_KICK)
11927 WRITE_ONCE(nohz.next_blocked,
11928 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
11931 /* There is still blocked load, enable periodic update */
11932 if (has_blocked_load)
11933 WRITE_ONCE(nohz.has_blocked, 1);
11937 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
11938 * rebalancing for all the cpus for whom scheduler ticks are stopped.
11940 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
11942 unsigned int flags = this_rq->nohz_idle_balance;
11947 this_rq->nohz_idle_balance = 0;
11949 if (idle != CPU_IDLE)
11952 _nohz_idle_balance(this_rq, flags);
11958 * Check if we need to run the ILB for updating blocked load before entering
11961 void nohz_run_idle_balance(int cpu)
11963 unsigned int flags;
11965 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
11968 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
11969 * (ie NOHZ_STATS_KICK set) and will do the same.
11971 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
11972 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
11975 static void nohz_newidle_balance(struct rq *this_rq)
11977 int this_cpu = this_rq->cpu;
11980 * This CPU doesn't want to be disturbed by scheduler
11983 if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
11986 /* Will wake up very soon. No time for doing anything else*/
11987 if (this_rq->avg_idle < sysctl_sched_migration_cost)
11990 /* Don't need to update blocked load of idle CPUs*/
11991 if (!READ_ONCE(nohz.has_blocked) ||
11992 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
11996 * Set the need to trigger ILB in order to update blocked load
11997 * before entering idle state.
11999 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12002 #else /* !CONFIG_NO_HZ_COMMON */
12003 static inline void nohz_balancer_kick(struct rq *rq) { }
12005 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12010 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12011 #endif /* CONFIG_NO_HZ_COMMON */
12014 * newidle_balance is called by schedule() if this_cpu is about to become
12015 * idle. Attempts to pull tasks from other CPUs.
12018 * < 0 - we released the lock and there are !fair tasks present
12019 * 0 - failed, no new tasks
12020 * > 0 - success, new (fair) tasks present
12022 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12024 unsigned long next_balance = jiffies + HZ;
12025 int this_cpu = this_rq->cpu;
12026 u64 t0, t1, curr_cost = 0;
12027 struct sched_domain *sd;
12028 int pulled_task = 0;
12030 update_misfit_status(NULL, this_rq);
12033 * There is a task waiting to run. No need to search for one.
12034 * Return 0; the task will be enqueued when switching to idle.
12036 if (this_rq->ttwu_pending)
12040 * We must set idle_stamp _before_ calling idle_balance(), such that we
12041 * measure the duration of idle_balance() as idle time.
12043 this_rq->idle_stamp = rq_clock(this_rq);
12046 * Do not pull tasks towards !active CPUs...
12048 if (!cpu_active(this_cpu))
12052 * This is OK, because current is on_cpu, which avoids it being picked
12053 * for load-balance and preemption/IRQs are still disabled avoiding
12054 * further scheduler activity on it and we're being very careful to
12055 * re-start the picking loop.
12057 rq_unpin_lock(this_rq, rf);
12060 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12062 if (!READ_ONCE(this_rq->rd->overload) ||
12063 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12066 update_next_balance(sd, &next_balance);
12073 raw_spin_rq_unlock(this_rq);
12075 t0 = sched_clock_cpu(this_cpu);
12076 update_blocked_averages(this_cpu);
12079 for_each_domain(this_cpu, sd) {
12080 int continue_balancing = 1;
12083 update_next_balance(sd, &next_balance);
12085 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12088 if (sd->flags & SD_BALANCE_NEWIDLE) {
12090 pulled_task = load_balance(this_cpu, this_rq,
12091 sd, CPU_NEWLY_IDLE,
12092 &continue_balancing);
12094 t1 = sched_clock_cpu(this_cpu);
12095 domain_cost = t1 - t0;
12096 update_newidle_cost(sd, domain_cost);
12098 curr_cost += domain_cost;
12103 * Stop searching for tasks to pull if there are
12104 * now runnable tasks on this rq.
12106 if (pulled_task || this_rq->nr_running > 0 ||
12107 this_rq->ttwu_pending)
12112 raw_spin_rq_lock(this_rq);
12114 if (curr_cost > this_rq->max_idle_balance_cost)
12115 this_rq->max_idle_balance_cost = curr_cost;
12118 * While browsing the domains, we released the rq lock, a task could
12119 * have been enqueued in the meantime. Since we're not going idle,
12120 * pretend we pulled a task.
12122 if (this_rq->cfs.h_nr_running && !pulled_task)
12125 /* Is there a task of a high priority class? */
12126 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12130 /* Move the next balance forward */
12131 if (time_after(this_rq->next_balance, next_balance))
12132 this_rq->next_balance = next_balance;
12135 this_rq->idle_stamp = 0;
12137 nohz_newidle_balance(this_rq);
12139 rq_repin_lock(this_rq, rf);
12141 return pulled_task;
12145 * run_rebalance_domains is triggered when needed from the scheduler tick.
12146 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12148 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12150 struct rq *this_rq = this_rq();
12151 enum cpu_idle_type idle = this_rq->idle_balance ?
12152 CPU_IDLE : CPU_NOT_IDLE;
12155 * If this CPU has a pending nohz_balance_kick, then do the
12156 * balancing on behalf of the other idle CPUs whose ticks are
12157 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12158 * give the idle CPUs a chance to load balance. Else we may
12159 * load balance only within the local sched_domain hierarchy
12160 * and abort nohz_idle_balance altogether if we pull some load.
12162 if (nohz_idle_balance(this_rq, idle))
12165 /* normal load balance */
12166 update_blocked_averages(this_rq->cpu);
12167 rebalance_domains(this_rq, idle);
12171 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12173 void trigger_load_balance(struct rq *rq)
12176 * Don't need to rebalance while attached to NULL domain or
12177 * runqueue CPU is not active
12179 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12182 if (time_after_eq(jiffies, rq->next_balance))
12183 raise_softirq(SCHED_SOFTIRQ);
12185 nohz_balancer_kick(rq);
12188 static void rq_online_fair(struct rq *rq)
12192 update_runtime_enabled(rq);
12195 static void rq_offline_fair(struct rq *rq)
12199 /* Ensure any throttled groups are reachable by pick_next_task */
12200 unthrottle_offline_cfs_rqs(rq);
12203 #endif /* CONFIG_SMP */
12205 #ifdef CONFIG_SCHED_CORE
12207 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12209 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12210 u64 slice = se->slice;
12212 return (rtime * min_nr_tasks > slice);
12215 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
12216 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12218 if (!sched_core_enabled(rq))
12222 * If runqueue has only one task which used up its slice and
12223 * if the sibling is forced idle, then trigger schedule to
12224 * give forced idle task a chance.
12226 * sched_slice() considers only this active rq and it gets the
12227 * whole slice. But during force idle, we have siblings acting
12228 * like a single runqueue and hence we need to consider runnable
12229 * tasks on this CPU and the forced idle CPU. Ideally, we should
12230 * go through the forced idle rq, but that would be a perf hit.
12231 * We can assume that the forced idle CPU has at least
12232 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12233 * if we need to give up the CPU.
12235 if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12236 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12241 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12243 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12246 for_each_sched_entity(se) {
12247 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12250 if (cfs_rq->forceidle_seq == fi_seq)
12252 cfs_rq->forceidle_seq = fi_seq;
12255 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12259 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12261 struct sched_entity *se = &p->se;
12263 if (p->sched_class != &fair_sched_class)
12266 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12269 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12272 struct rq *rq = task_rq(a);
12273 const struct sched_entity *sea = &a->se;
12274 const struct sched_entity *seb = &b->se;
12275 struct cfs_rq *cfs_rqa;
12276 struct cfs_rq *cfs_rqb;
12279 SCHED_WARN_ON(task_rq(b)->core != rq->core);
12281 #ifdef CONFIG_FAIR_GROUP_SCHED
12283 * Find an se in the hierarchy for tasks a and b, such that the se's
12284 * are immediate siblings.
12286 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12287 int sea_depth = sea->depth;
12288 int seb_depth = seb->depth;
12290 if (sea_depth >= seb_depth)
12291 sea = parent_entity(sea);
12292 if (sea_depth <= seb_depth)
12293 seb = parent_entity(seb);
12296 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12297 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12299 cfs_rqa = sea->cfs_rq;
12300 cfs_rqb = seb->cfs_rq;
12302 cfs_rqa = &task_rq(a)->cfs;
12303 cfs_rqb = &task_rq(b)->cfs;
12307 * Find delta after normalizing se's vruntime with its cfs_rq's
12308 * min_vruntime_fi, which would have been updated in prior calls
12309 * to se_fi_update().
12311 delta = (s64)(sea->vruntime - seb->vruntime) +
12312 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12317 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12319 struct cfs_rq *cfs_rq;
12321 #ifdef CONFIG_FAIR_GROUP_SCHED
12322 cfs_rq = task_group(p)->cfs_rq[cpu];
12324 cfs_rq = &cpu_rq(cpu)->cfs;
12326 return throttled_hierarchy(cfs_rq);
12329 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12333 * scheduler tick hitting a task of our scheduling class.
12335 * NOTE: This function can be called remotely by the tick offload that
12336 * goes along full dynticks. Therefore no local assumption can be made
12337 * and everything must be accessed through the @rq and @curr passed in
12340 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12342 struct cfs_rq *cfs_rq;
12343 struct sched_entity *se = &curr->se;
12345 for_each_sched_entity(se) {
12346 cfs_rq = cfs_rq_of(se);
12347 entity_tick(cfs_rq, se, queued);
12350 if (static_branch_unlikely(&sched_numa_balancing))
12351 task_tick_numa(rq, curr);
12353 update_misfit_status(curr, rq);
12354 update_overutilized_status(task_rq(curr));
12356 task_tick_core(rq, curr);
12360 * called on fork with the child task as argument from the parent's context
12361 * - child not yet on the tasklist
12362 * - preemption disabled
12364 static void task_fork_fair(struct task_struct *p)
12366 struct sched_entity *se = &p->se, *curr;
12367 struct cfs_rq *cfs_rq;
12368 struct rq *rq = this_rq();
12369 struct rq_flags rf;
12372 update_rq_clock(rq);
12374 cfs_rq = task_cfs_rq(current);
12375 curr = cfs_rq->curr;
12377 update_curr(cfs_rq);
12378 place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12379 rq_unlock(rq, &rf);
12383 * Priority of the task has changed. Check to see if we preempt
12384 * the current task.
12387 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12389 if (!task_on_rq_queued(p))
12392 if (rq->cfs.nr_running == 1)
12396 * Reschedule if we are currently running on this runqueue and
12397 * our priority decreased, or if we are not currently running on
12398 * this runqueue and our priority is higher than the current's
12400 if (task_current(rq, p)) {
12401 if (p->prio > oldprio)
12404 check_preempt_curr(rq, p, 0);
12407 #ifdef CONFIG_FAIR_GROUP_SCHED
12409 * Propagate the changes of the sched_entity across the tg tree to make it
12410 * visible to the root
12412 static void propagate_entity_cfs_rq(struct sched_entity *se)
12414 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12416 if (cfs_rq_throttled(cfs_rq))
12419 if (!throttled_hierarchy(cfs_rq))
12420 list_add_leaf_cfs_rq(cfs_rq);
12422 /* Start to propagate at parent */
12425 for_each_sched_entity(se) {
12426 cfs_rq = cfs_rq_of(se);
12428 update_load_avg(cfs_rq, se, UPDATE_TG);
12430 if (cfs_rq_throttled(cfs_rq))
12433 if (!throttled_hierarchy(cfs_rq))
12434 list_add_leaf_cfs_rq(cfs_rq);
12438 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12441 static void detach_entity_cfs_rq(struct sched_entity *se)
12443 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12447 * In case the task sched_avg hasn't been attached:
12448 * - A forked task which hasn't been woken up by wake_up_new_task().
12449 * - A task which has been woken up by try_to_wake_up() but is
12450 * waiting for actually being woken up by sched_ttwu_pending().
12452 if (!se->avg.last_update_time)
12456 /* Catch up with the cfs_rq and remove our load when we leave */
12457 update_load_avg(cfs_rq, se, 0);
12458 detach_entity_load_avg(cfs_rq, se);
12459 update_tg_load_avg(cfs_rq);
12460 propagate_entity_cfs_rq(se);
12463 static void attach_entity_cfs_rq(struct sched_entity *se)
12465 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12467 /* Synchronize entity with its cfs_rq */
12468 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12469 attach_entity_load_avg(cfs_rq, se);
12470 update_tg_load_avg(cfs_rq);
12471 propagate_entity_cfs_rq(se);
12474 static void detach_task_cfs_rq(struct task_struct *p)
12476 struct sched_entity *se = &p->se;
12478 detach_entity_cfs_rq(se);
12481 static void attach_task_cfs_rq(struct task_struct *p)
12483 struct sched_entity *se = &p->se;
12485 attach_entity_cfs_rq(se);
12488 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12490 detach_task_cfs_rq(p);
12493 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12495 attach_task_cfs_rq(p);
12497 if (task_on_rq_queued(p)) {
12499 * We were most likely switched from sched_rt, so
12500 * kick off the schedule if running, otherwise just see
12501 * if we can still preempt the current task.
12503 if (task_current(rq, p))
12506 check_preempt_curr(rq, p, 0);
12510 /* Account for a task changing its policy or group.
12512 * This routine is mostly called to set cfs_rq->curr field when a task
12513 * migrates between groups/classes.
12515 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12517 struct sched_entity *se = &p->se;
12520 if (task_on_rq_queued(p)) {
12522 * Move the next running task to the front of the list, so our
12523 * cfs_tasks list becomes MRU one.
12525 list_move(&se->group_node, &rq->cfs_tasks);
12529 for_each_sched_entity(se) {
12530 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12532 set_next_entity(cfs_rq, se);
12533 /* ensure bandwidth has been allocated on our new cfs_rq */
12534 account_cfs_rq_runtime(cfs_rq, 0);
12538 void init_cfs_rq(struct cfs_rq *cfs_rq)
12540 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12541 u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12543 raw_spin_lock_init(&cfs_rq->removed.lock);
12547 #ifdef CONFIG_FAIR_GROUP_SCHED
12548 static void task_change_group_fair(struct task_struct *p)
12551 * We couldn't detach or attach a forked task which
12552 * hasn't been woken up by wake_up_new_task().
12554 if (READ_ONCE(p->__state) == TASK_NEW)
12557 detach_task_cfs_rq(p);
12560 /* Tell se's cfs_rq has been changed -- migrated */
12561 p->se.avg.last_update_time = 0;
12563 set_task_rq(p, task_cpu(p));
12564 attach_task_cfs_rq(p);
12567 void free_fair_sched_group(struct task_group *tg)
12571 for_each_possible_cpu(i) {
12573 kfree(tg->cfs_rq[i]);
12582 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12584 struct sched_entity *se;
12585 struct cfs_rq *cfs_rq;
12588 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12591 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12595 tg->shares = NICE_0_LOAD;
12597 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12599 for_each_possible_cpu(i) {
12600 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12601 GFP_KERNEL, cpu_to_node(i));
12605 se = kzalloc_node(sizeof(struct sched_entity_stats),
12606 GFP_KERNEL, cpu_to_node(i));
12610 init_cfs_rq(cfs_rq);
12611 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12612 init_entity_runnable_average(se);
12623 void online_fair_sched_group(struct task_group *tg)
12625 struct sched_entity *se;
12626 struct rq_flags rf;
12630 for_each_possible_cpu(i) {
12633 rq_lock_irq(rq, &rf);
12634 update_rq_clock(rq);
12635 attach_entity_cfs_rq(se);
12636 sync_throttle(tg, i);
12637 rq_unlock_irq(rq, &rf);
12641 void unregister_fair_sched_group(struct task_group *tg)
12643 unsigned long flags;
12647 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12649 for_each_possible_cpu(cpu) {
12651 remove_entity_load_avg(tg->se[cpu]);
12654 * Only empty task groups can be destroyed; so we can speculatively
12655 * check on_list without danger of it being re-added.
12657 if (!tg->cfs_rq[cpu]->on_list)
12662 raw_spin_rq_lock_irqsave(rq, flags);
12663 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12664 raw_spin_rq_unlock_irqrestore(rq, flags);
12668 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12669 struct sched_entity *se, int cpu,
12670 struct sched_entity *parent)
12672 struct rq *rq = cpu_rq(cpu);
12676 init_cfs_rq_runtime(cfs_rq);
12678 tg->cfs_rq[cpu] = cfs_rq;
12681 /* se could be NULL for root_task_group */
12686 se->cfs_rq = &rq->cfs;
12689 se->cfs_rq = parent->my_q;
12690 se->depth = parent->depth + 1;
12694 /* guarantee group entities always have weight */
12695 update_load_set(&se->load, NICE_0_LOAD);
12696 se->parent = parent;
12699 static DEFINE_MUTEX(shares_mutex);
12701 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
12705 lockdep_assert_held(&shares_mutex);
12708 * We can't change the weight of the root cgroup.
12713 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
12715 if (tg->shares == shares)
12718 tg->shares = shares;
12719 for_each_possible_cpu(i) {
12720 struct rq *rq = cpu_rq(i);
12721 struct sched_entity *se = tg->se[i];
12722 struct rq_flags rf;
12724 /* Propagate contribution to hierarchy */
12725 rq_lock_irqsave(rq, &rf);
12726 update_rq_clock(rq);
12727 for_each_sched_entity(se) {
12728 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
12729 update_cfs_group(se);
12731 rq_unlock_irqrestore(rq, &rf);
12737 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
12741 mutex_lock(&shares_mutex);
12742 if (tg_is_idle(tg))
12745 ret = __sched_group_set_shares(tg, shares);
12746 mutex_unlock(&shares_mutex);
12751 int sched_group_set_idle(struct task_group *tg, long idle)
12755 if (tg == &root_task_group)
12758 if (idle < 0 || idle > 1)
12761 mutex_lock(&shares_mutex);
12763 if (tg->idle == idle) {
12764 mutex_unlock(&shares_mutex);
12770 for_each_possible_cpu(i) {
12771 struct rq *rq = cpu_rq(i);
12772 struct sched_entity *se = tg->se[i];
12773 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
12774 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
12775 long idle_task_delta;
12776 struct rq_flags rf;
12778 rq_lock_irqsave(rq, &rf);
12780 grp_cfs_rq->idle = idle;
12781 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
12785 parent_cfs_rq = cfs_rq_of(se);
12786 if (cfs_rq_is_idle(grp_cfs_rq))
12787 parent_cfs_rq->idle_nr_running++;
12789 parent_cfs_rq->idle_nr_running--;
12792 idle_task_delta = grp_cfs_rq->h_nr_running -
12793 grp_cfs_rq->idle_h_nr_running;
12794 if (!cfs_rq_is_idle(grp_cfs_rq))
12795 idle_task_delta *= -1;
12797 for_each_sched_entity(se) {
12798 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12803 cfs_rq->idle_h_nr_running += idle_task_delta;
12805 /* Already accounted at parent level and above. */
12806 if (cfs_rq_is_idle(cfs_rq))
12811 rq_unlock_irqrestore(rq, &rf);
12814 /* Idle groups have minimum weight. */
12815 if (tg_is_idle(tg))
12816 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
12818 __sched_group_set_shares(tg, NICE_0_LOAD);
12820 mutex_unlock(&shares_mutex);
12824 #else /* CONFIG_FAIR_GROUP_SCHED */
12826 void free_fair_sched_group(struct task_group *tg) { }
12828 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12833 void online_fair_sched_group(struct task_group *tg) { }
12835 void unregister_fair_sched_group(struct task_group *tg) { }
12837 #endif /* CONFIG_FAIR_GROUP_SCHED */
12840 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
12842 struct sched_entity *se = &task->se;
12843 unsigned int rr_interval = 0;
12846 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
12849 if (rq->cfs.load.weight)
12850 rr_interval = NS_TO_JIFFIES(se->slice);
12852 return rr_interval;
12856 * All the scheduling class methods:
12858 DEFINE_SCHED_CLASS(fair) = {
12860 .enqueue_task = enqueue_task_fair,
12861 .dequeue_task = dequeue_task_fair,
12862 .yield_task = yield_task_fair,
12863 .yield_to_task = yield_to_task_fair,
12865 .check_preempt_curr = check_preempt_wakeup,
12867 .pick_next_task = __pick_next_task_fair,
12868 .put_prev_task = put_prev_task_fair,
12869 .set_next_task = set_next_task_fair,
12872 .balance = balance_fair,
12873 .pick_task = pick_task_fair,
12874 .select_task_rq = select_task_rq_fair,
12875 .migrate_task_rq = migrate_task_rq_fair,
12877 .rq_online = rq_online_fair,
12878 .rq_offline = rq_offline_fair,
12880 .task_dead = task_dead_fair,
12881 .set_cpus_allowed = set_cpus_allowed_common,
12884 .task_tick = task_tick_fair,
12885 .task_fork = task_fork_fair,
12887 .prio_changed = prio_changed_fair,
12888 .switched_from = switched_from_fair,
12889 .switched_to = switched_to_fair,
12891 .get_rr_interval = get_rr_interval_fair,
12893 .update_curr = update_curr_fair,
12895 #ifdef CONFIG_FAIR_GROUP_SCHED
12896 .task_change_group = task_change_group_fair,
12899 #ifdef CONFIG_SCHED_CORE
12900 .task_is_throttled = task_is_throttled_fair,
12903 #ifdef CONFIG_UCLAMP_TASK
12904 .uclamp_enabled = 1,
12908 #ifdef CONFIG_SCHED_DEBUG
12909 void print_cfs_stats(struct seq_file *m, int cpu)
12911 struct cfs_rq *cfs_rq, *pos;
12914 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
12915 print_cfs_rq(m, cpu, cfs_rq);
12919 #ifdef CONFIG_NUMA_BALANCING
12920 void show_numa_stats(struct task_struct *p, struct seq_file *m)
12923 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
12924 struct numa_group *ng;
12927 ng = rcu_dereference(p->numa_group);
12928 for_each_online_node(node) {
12929 if (p->numa_faults) {
12930 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
12931 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
12934 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
12935 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
12937 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
12941 #endif /* CONFIG_NUMA_BALANCING */
12942 #endif /* CONFIG_SCHED_DEBUG */
12944 __init void init_sched_fair_class(void)
12949 for_each_possible_cpu(i) {
12950 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
12951 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
12952 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
12953 GFP_KERNEL, cpu_to_node(i));
12955 #ifdef CONFIG_CFS_BANDWIDTH
12956 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
12957 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
12961 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
12963 #ifdef CONFIG_NO_HZ_COMMON
12964 nohz.next_balance = jiffies;
12965 nohz.next_blocked = jiffies;
12966 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);