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;
667 u64 avg_vruntime(struct cfs_rq *cfs_rq)
669 struct sched_entity *curr = cfs_rq->curr;
670 s64 avg = cfs_rq->avg_vruntime;
671 long load = cfs_rq->avg_load;
673 if (curr && curr->on_rq) {
674 unsigned long weight = scale_load_down(curr->load.weight);
676 avg += entity_key(cfs_rq, curr) * weight;
681 avg = div_s64(avg, load);
683 return cfs_rq->min_vruntime + avg;
687 * lag_i = S - s_i = w_i * (V - v_i)
689 * However, since V is approximated by the weighted average of all entities it
690 * is possible -- by addition/removal/reweight to the tree -- to move V around
691 * and end up with a larger lag than we started with.
693 * Limit this to either double the slice length with a minimum of TICK_NSEC
694 * since that is the timing granularity.
696 * EEVDF gives the following limit for a steady state system:
698 * -r_max < lag < max(r_max, q)
700 * XXX could add max_slice to the augmented data to track this.
702 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
706 SCHED_WARN_ON(!se->on_rq);
707 lag = avg_vruntime(cfs_rq) - se->vruntime;
709 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
710 se->vlag = clamp(lag, -limit, limit);
714 * Entity is eligible once it received less service than it ought to have,
717 * lag_i = S - s_i = w_i*(V - v_i)
719 * lag_i >= 0 -> V >= v_i
722 * V = ------------------ + v
725 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
727 * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
728 * to the loss in precision caused by the division.
730 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
732 struct sched_entity *curr = cfs_rq->curr;
733 s64 avg = cfs_rq->avg_vruntime;
734 long load = cfs_rq->avg_load;
736 if (curr && curr->on_rq) {
737 unsigned long weight = scale_load_down(curr->load.weight);
739 avg += entity_key(cfs_rq, curr) * weight;
743 return avg >= entity_key(cfs_rq, se) * load;
746 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
748 u64 min_vruntime = cfs_rq->min_vruntime;
750 * open coded max_vruntime() to allow updating avg_vruntime
752 s64 delta = (s64)(vruntime - min_vruntime);
754 avg_vruntime_update(cfs_rq, delta);
755 min_vruntime = vruntime;
760 static void update_min_vruntime(struct cfs_rq *cfs_rq)
762 struct sched_entity *se = __pick_first_entity(cfs_rq);
763 struct sched_entity *curr = cfs_rq->curr;
765 u64 vruntime = cfs_rq->min_vruntime;
769 vruntime = curr->vruntime;
776 vruntime = se->vruntime;
778 vruntime = min_vruntime(vruntime, se->vruntime);
781 /* ensure we never gain time by being placed backwards. */
782 u64_u32_store(cfs_rq->min_vruntime,
783 __update_min_vruntime(cfs_rq, vruntime));
786 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
788 return entity_before(__node_2_se(a), __node_2_se(b));
791 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
793 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
796 struct sched_entity *rse = __node_2_se(node);
797 if (deadline_gt(min_deadline, se, rse))
798 se->min_deadline = rse->min_deadline;
803 * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
805 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
807 u64 old_min_deadline = se->min_deadline;
808 struct rb_node *node = &se->run_node;
810 se->min_deadline = se->deadline;
811 __update_min_deadline(se, node->rb_right);
812 __update_min_deadline(se, node->rb_left);
814 return se->min_deadline == old_min_deadline;
817 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
818 run_node, min_deadline, min_deadline_update);
821 * Enqueue an entity into the rb-tree:
823 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
825 avg_vruntime_add(cfs_rq, se);
826 se->min_deadline = se->deadline;
827 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
828 __entity_less, &min_deadline_cb);
831 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
833 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
835 avg_vruntime_sub(cfs_rq, se);
838 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
840 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
845 return __node_2_se(left);
849 * Earliest Eligible Virtual Deadline First
851 * In order to provide latency guarantees for different request sizes
852 * EEVDF selects the best runnable task from two criteria:
854 * 1) the task must be eligible (must be owed service)
856 * 2) from those tasks that meet 1), we select the one
857 * with the earliest virtual deadline.
859 * We can do this in O(log n) time due to an augmented RB-tree. The
860 * tree keeps the entries sorted on service, but also functions as a
861 * heap based on the deadline by keeping:
863 * se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
865 * Which allows an EDF like search on (sub)trees.
867 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
869 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
870 struct sched_entity *curr = cfs_rq->curr;
871 struct sched_entity *best = NULL;
873 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
877 * Once selected, run a task until it either becomes non-eligible or
878 * until it gets a new slice. See the HACK in set_next_entity().
880 if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
884 struct sched_entity *se = __node_2_se(node);
887 * If this entity is not eligible, try the left subtree.
889 if (!entity_eligible(cfs_rq, se)) {
890 node = node->rb_left;
895 * If this entity has an earlier deadline than the previous
896 * best, take this one. If it also has the earliest deadline
897 * of its subtree, we're done.
899 if (!best || deadline_gt(deadline, best, se)) {
901 if (best->deadline == best->min_deadline)
906 * If the earlest deadline in this subtree is in the fully
907 * eligible left half of our space, go there.
910 __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
911 node = node->rb_left;
915 node = node->rb_right;
918 if (!best || (curr && deadline_gt(deadline, best, curr)))
921 if (unlikely(!best)) {
922 struct sched_entity *left = __pick_first_entity(cfs_rq);
924 pr_err("EEVDF scheduling fail, picking leftmost\n");
932 #ifdef CONFIG_SCHED_DEBUG
933 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
935 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
940 return __node_2_se(last);
943 /**************************************************************
944 * Scheduling class statistics methods:
947 int sched_update_scaling(void)
949 unsigned int factor = get_update_sysctl_factor();
951 #define WRT_SYSCTL(name) \
952 (normalized_sysctl_##name = sysctl_##name / (factor))
953 WRT_SYSCTL(sched_base_slice);
961 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
964 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
965 * this is probably good enough.
967 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
969 if ((s64)(se->vruntime - se->deadline) < 0)
973 * For EEVDF the virtual time slope is determined by w_i (iow.
974 * nice) while the request time r_i is determined by
975 * sysctl_sched_base_slice.
977 se->slice = sysctl_sched_base_slice;
980 * EEVDF: vd_i = ve_i + r_i / w_i
982 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
985 * The task has consumed its request, reschedule.
987 if (cfs_rq->nr_running > 1) {
988 resched_curr(rq_of(cfs_rq));
989 clear_buddies(cfs_rq, se);
996 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
997 static unsigned long task_h_load(struct task_struct *p);
998 static unsigned long capacity_of(int cpu);
1000 /* Give new sched_entity start runnable values to heavy its load in infant time */
1001 void init_entity_runnable_average(struct sched_entity *se)
1003 struct sched_avg *sa = &se->avg;
1005 memset(sa, 0, sizeof(*sa));
1008 * Tasks are initialized with full load to be seen as heavy tasks until
1009 * they get a chance to stabilize to their real load level.
1010 * Group entities are initialized with zero load to reflect the fact that
1011 * nothing has been attached to the task group yet.
1013 if (entity_is_task(se))
1014 sa->load_avg = scale_load_down(se->load.weight);
1016 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1020 * With new tasks being created, their initial util_avgs are extrapolated
1021 * based on the cfs_rq's current util_avg:
1023 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1025 * However, in many cases, the above util_avg does not give a desired
1026 * value. Moreover, the sum of the util_avgs may be divergent, such
1027 * as when the series is a harmonic series.
1029 * To solve this problem, we also cap the util_avg of successive tasks to
1030 * only 1/2 of the left utilization budget:
1032 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1034 * where n denotes the nth task and cpu_scale the CPU capacity.
1036 * For example, for a CPU with 1024 of capacity, a simplest series from
1037 * the beginning would be like:
1039 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1040 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1042 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1043 * if util_avg > util_avg_cap.
1045 void post_init_entity_util_avg(struct task_struct *p)
1047 struct sched_entity *se = &p->se;
1048 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1049 struct sched_avg *sa = &se->avg;
1050 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1051 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1053 if (p->sched_class != &fair_sched_class) {
1055 * For !fair tasks do:
1057 update_cfs_rq_load_avg(now, cfs_rq);
1058 attach_entity_load_avg(cfs_rq, se);
1059 switched_from_fair(rq, p);
1061 * such that the next switched_to_fair() has the
1064 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1069 if (cfs_rq->avg.util_avg != 0) {
1070 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
1071 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1073 if (sa->util_avg > cap)
1080 sa->runnable_avg = sa->util_avg;
1083 #else /* !CONFIG_SMP */
1084 void init_entity_runnable_average(struct sched_entity *se)
1087 void post_init_entity_util_avg(struct task_struct *p)
1090 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1093 #endif /* CONFIG_SMP */
1096 * Update the current task's runtime statistics.
1098 static void update_curr(struct cfs_rq *cfs_rq)
1100 struct sched_entity *curr = cfs_rq->curr;
1101 u64 now = rq_clock_task(rq_of(cfs_rq));
1104 if (unlikely(!curr))
1107 delta_exec = now - curr->exec_start;
1108 if (unlikely((s64)delta_exec <= 0))
1111 curr->exec_start = now;
1113 if (schedstat_enabled()) {
1114 struct sched_statistics *stats;
1116 stats = __schedstats_from_se(curr);
1117 __schedstat_set(stats->exec_max,
1118 max(delta_exec, stats->exec_max));
1121 curr->sum_exec_runtime += delta_exec;
1122 schedstat_add(cfs_rq->exec_clock, delta_exec);
1124 curr->vruntime += calc_delta_fair(delta_exec, curr);
1125 update_deadline(cfs_rq, curr);
1126 update_min_vruntime(cfs_rq);
1128 if (entity_is_task(curr)) {
1129 struct task_struct *curtask = task_of(curr);
1131 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1132 cgroup_account_cputime(curtask, delta_exec);
1133 account_group_exec_runtime(curtask, delta_exec);
1136 account_cfs_rq_runtime(cfs_rq, delta_exec);
1139 static void update_curr_fair(struct rq *rq)
1141 update_curr(cfs_rq_of(&rq->curr->se));
1145 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1147 struct sched_statistics *stats;
1148 struct task_struct *p = NULL;
1150 if (!schedstat_enabled())
1153 stats = __schedstats_from_se(se);
1155 if (entity_is_task(se))
1158 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1162 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1164 struct sched_statistics *stats;
1165 struct task_struct *p = NULL;
1167 if (!schedstat_enabled())
1170 stats = __schedstats_from_se(se);
1173 * When the sched_schedstat changes from 0 to 1, some sched se
1174 * maybe already in the runqueue, the se->statistics.wait_start
1175 * will be 0.So it will let the delta wrong. We need to avoid this
1178 if (unlikely(!schedstat_val(stats->wait_start)))
1181 if (entity_is_task(se))
1184 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1188 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1190 struct sched_statistics *stats;
1191 struct task_struct *tsk = NULL;
1193 if (!schedstat_enabled())
1196 stats = __schedstats_from_se(se);
1198 if (entity_is_task(se))
1201 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1205 * Task is being enqueued - update stats:
1208 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1210 if (!schedstat_enabled())
1214 * Are we enqueueing a waiting task? (for current tasks
1215 * a dequeue/enqueue event is a NOP)
1217 if (se != cfs_rq->curr)
1218 update_stats_wait_start_fair(cfs_rq, se);
1220 if (flags & ENQUEUE_WAKEUP)
1221 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1225 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1228 if (!schedstat_enabled())
1232 * Mark the end of the wait period if dequeueing a
1235 if (se != cfs_rq->curr)
1236 update_stats_wait_end_fair(cfs_rq, se);
1238 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1239 struct task_struct *tsk = task_of(se);
1242 /* XXX racy against TTWU */
1243 state = READ_ONCE(tsk->__state);
1244 if (state & TASK_INTERRUPTIBLE)
1245 __schedstat_set(tsk->stats.sleep_start,
1246 rq_clock(rq_of(cfs_rq)));
1247 if (state & TASK_UNINTERRUPTIBLE)
1248 __schedstat_set(tsk->stats.block_start,
1249 rq_clock(rq_of(cfs_rq)));
1254 * We are picking a new current task - update its stats:
1257 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1260 * We are starting a new run period:
1262 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1265 /**************************************************
1266 * Scheduling class queueing methods:
1269 static inline bool is_core_idle(int cpu)
1271 #ifdef CONFIG_SCHED_SMT
1274 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1278 if (!idle_cpu(sibling))
1287 #define NUMA_IMBALANCE_MIN 2
1290 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1293 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1294 * threshold. Above this threshold, individual tasks may be contending
1295 * for both memory bandwidth and any shared HT resources. This is an
1296 * approximation as the number of running tasks may not be related to
1297 * the number of busy CPUs due to sched_setaffinity.
1299 if (dst_running > imb_numa_nr)
1303 * Allow a small imbalance based on a simple pair of communicating
1304 * tasks that remain local when the destination is lightly loaded.
1306 if (imbalance <= NUMA_IMBALANCE_MIN)
1311 #endif /* CONFIG_NUMA */
1313 #ifdef CONFIG_NUMA_BALANCING
1315 * Approximate time to scan a full NUMA task in ms. The task scan period is
1316 * calculated based on the tasks virtual memory size and
1317 * numa_balancing_scan_size.
1319 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1320 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1322 /* Portion of address space to scan in MB */
1323 unsigned int sysctl_numa_balancing_scan_size = 256;
1325 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1326 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1328 /* The page with hint page fault latency < threshold in ms is considered hot */
1329 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1332 refcount_t refcount;
1334 spinlock_t lock; /* nr_tasks, tasks */
1339 struct rcu_head rcu;
1340 unsigned long total_faults;
1341 unsigned long max_faults_cpu;
1343 * faults[] array is split into two regions: faults_mem and faults_cpu.
1345 * Faults_cpu is used to decide whether memory should move
1346 * towards the CPU. As a consequence, these stats are weighted
1347 * more by CPU use than by memory faults.
1349 unsigned long faults[];
1353 * For functions that can be called in multiple contexts that permit reading
1354 * ->numa_group (see struct task_struct for locking rules).
1356 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1358 return rcu_dereference_check(p->numa_group, p == current ||
1359 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1362 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1364 return rcu_dereference_protected(p->numa_group, p == current);
1367 static inline unsigned long group_faults_priv(struct numa_group *ng);
1368 static inline unsigned long group_faults_shared(struct numa_group *ng);
1370 static unsigned int task_nr_scan_windows(struct task_struct *p)
1372 unsigned long rss = 0;
1373 unsigned long nr_scan_pages;
1376 * Calculations based on RSS as non-present and empty pages are skipped
1377 * by the PTE scanner and NUMA hinting faults should be trapped based
1380 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1381 rss = get_mm_rss(p->mm);
1383 rss = nr_scan_pages;
1385 rss = round_up(rss, nr_scan_pages);
1386 return rss / nr_scan_pages;
1389 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1390 #define MAX_SCAN_WINDOW 2560
1392 static unsigned int task_scan_min(struct task_struct *p)
1394 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1395 unsigned int scan, floor;
1396 unsigned int windows = 1;
1398 if (scan_size < MAX_SCAN_WINDOW)
1399 windows = MAX_SCAN_WINDOW / scan_size;
1400 floor = 1000 / windows;
1402 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1403 return max_t(unsigned int, floor, scan);
1406 static unsigned int task_scan_start(struct task_struct *p)
1408 unsigned long smin = task_scan_min(p);
1409 unsigned long period = smin;
1410 struct numa_group *ng;
1412 /* Scale the maximum scan period with the amount of shared memory. */
1414 ng = rcu_dereference(p->numa_group);
1416 unsigned long shared = group_faults_shared(ng);
1417 unsigned long private = group_faults_priv(ng);
1419 period *= refcount_read(&ng->refcount);
1420 period *= shared + 1;
1421 period /= private + shared + 1;
1425 return max(smin, period);
1428 static unsigned int task_scan_max(struct task_struct *p)
1430 unsigned long smin = task_scan_min(p);
1432 struct numa_group *ng;
1434 /* Watch for min being lower than max due to floor calculations */
1435 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1437 /* Scale the maximum scan period with the amount of shared memory. */
1438 ng = deref_curr_numa_group(p);
1440 unsigned long shared = group_faults_shared(ng);
1441 unsigned long private = group_faults_priv(ng);
1442 unsigned long period = smax;
1444 period *= refcount_read(&ng->refcount);
1445 period *= shared + 1;
1446 period /= private + shared + 1;
1448 smax = max(smax, period);
1451 return max(smin, smax);
1454 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1456 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1457 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1460 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1462 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1463 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1466 /* Shared or private faults. */
1467 #define NR_NUMA_HINT_FAULT_TYPES 2
1469 /* Memory and CPU locality */
1470 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1472 /* Averaged statistics, and temporary buffers. */
1473 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1475 pid_t task_numa_group_id(struct task_struct *p)
1477 struct numa_group *ng;
1481 ng = rcu_dereference(p->numa_group);
1490 * The averaged statistics, shared & private, memory & CPU,
1491 * occupy the first half of the array. The second half of the
1492 * array is for current counters, which are averaged into the
1493 * first set by task_numa_placement.
1495 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1497 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1500 static inline unsigned long task_faults(struct task_struct *p, int nid)
1502 if (!p->numa_faults)
1505 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1506 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1509 static inline unsigned long group_faults(struct task_struct *p, int nid)
1511 struct numa_group *ng = deref_task_numa_group(p);
1516 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1517 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1520 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1522 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1523 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1526 static inline unsigned long group_faults_priv(struct numa_group *ng)
1528 unsigned long faults = 0;
1531 for_each_online_node(node) {
1532 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1538 static inline unsigned long group_faults_shared(struct numa_group *ng)
1540 unsigned long faults = 0;
1543 for_each_online_node(node) {
1544 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1551 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1552 * considered part of a numa group's pseudo-interleaving set. Migrations
1553 * between these nodes are slowed down, to allow things to settle down.
1555 #define ACTIVE_NODE_FRACTION 3
1557 static bool numa_is_active_node(int nid, struct numa_group *ng)
1559 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1562 /* Handle placement on systems where not all nodes are directly connected. */
1563 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1564 int lim_dist, bool task)
1566 unsigned long score = 0;
1570 * All nodes are directly connected, and the same distance
1571 * from each other. No need for fancy placement algorithms.
1573 if (sched_numa_topology_type == NUMA_DIRECT)
1576 /* sched_max_numa_distance may be changed in parallel. */
1577 max_dist = READ_ONCE(sched_max_numa_distance);
1579 * This code is called for each node, introducing N^2 complexity,
1580 * which should be ok given the number of nodes rarely exceeds 8.
1582 for_each_online_node(node) {
1583 unsigned long faults;
1584 int dist = node_distance(nid, node);
1587 * The furthest away nodes in the system are not interesting
1588 * for placement; nid was already counted.
1590 if (dist >= max_dist || node == nid)
1594 * On systems with a backplane NUMA topology, compare groups
1595 * of nodes, and move tasks towards the group with the most
1596 * memory accesses. When comparing two nodes at distance
1597 * "hoplimit", only nodes closer by than "hoplimit" are part
1598 * of each group. Skip other nodes.
1600 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1603 /* Add up the faults from nearby nodes. */
1605 faults = task_faults(p, node);
1607 faults = group_faults(p, node);
1610 * On systems with a glueless mesh NUMA topology, there are
1611 * no fixed "groups of nodes". Instead, nodes that are not
1612 * directly connected bounce traffic through intermediate
1613 * nodes; a numa_group can occupy any set of nodes.
1614 * The further away a node is, the less the faults count.
1615 * This seems to result in good task placement.
1617 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1618 faults *= (max_dist - dist);
1619 faults /= (max_dist - LOCAL_DISTANCE);
1629 * These return the fraction of accesses done by a particular task, or
1630 * task group, on a particular numa node. The group weight is given a
1631 * larger multiplier, in order to group tasks together that are almost
1632 * evenly spread out between numa nodes.
1634 static inline unsigned long task_weight(struct task_struct *p, int nid,
1637 unsigned long faults, total_faults;
1639 if (!p->numa_faults)
1642 total_faults = p->total_numa_faults;
1647 faults = task_faults(p, nid);
1648 faults += score_nearby_nodes(p, nid, dist, true);
1650 return 1000 * faults / total_faults;
1653 static inline unsigned long group_weight(struct task_struct *p, int nid,
1656 struct numa_group *ng = deref_task_numa_group(p);
1657 unsigned long faults, total_faults;
1662 total_faults = ng->total_faults;
1667 faults = group_faults(p, nid);
1668 faults += score_nearby_nodes(p, nid, dist, false);
1670 return 1000 * faults / total_faults;
1674 * If memory tiering mode is enabled, cpupid of slow memory page is
1675 * used to record scan time instead of CPU and PID. When tiering mode
1676 * is disabled at run time, the scan time (in cpupid) will be
1677 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1678 * access out of array bound.
1680 static inline bool cpupid_valid(int cpupid)
1682 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1686 * For memory tiering mode, if there are enough free pages (more than
1687 * enough watermark defined here) in fast memory node, to take full
1688 * advantage of fast memory capacity, all recently accessed slow
1689 * memory pages will be migrated to fast memory node without
1690 * considering hot threshold.
1692 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1695 unsigned long enough_wmark;
1697 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1698 pgdat->node_present_pages >> 4);
1699 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1700 struct zone *zone = pgdat->node_zones + z;
1702 if (!populated_zone(zone))
1705 if (zone_watermark_ok(zone, 0,
1706 wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1714 * For memory tiering mode, when page tables are scanned, the scan
1715 * time will be recorded in struct page in addition to make page
1716 * PROT_NONE for slow memory page. So when the page is accessed, in
1717 * hint page fault handler, the hint page fault latency is calculated
1720 * hint page fault latency = hint page fault time - scan time
1722 * The smaller the hint page fault latency, the higher the possibility
1723 * for the page to be hot.
1725 static int numa_hint_fault_latency(struct page *page)
1727 int last_time, time;
1729 time = jiffies_to_msecs(jiffies);
1730 last_time = xchg_page_access_time(page, time);
1732 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1736 * For memory tiering mode, too high promotion/demotion throughput may
1737 * hurt application latency. So we provide a mechanism to rate limit
1738 * the number of pages that are tried to be promoted.
1740 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1741 unsigned long rate_limit, int nr)
1743 unsigned long nr_cand;
1744 unsigned int now, start;
1746 now = jiffies_to_msecs(jiffies);
1747 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1748 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1749 start = pgdat->nbp_rl_start;
1750 if (now - start > MSEC_PER_SEC &&
1751 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1752 pgdat->nbp_rl_nr_cand = nr_cand;
1753 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1758 #define NUMA_MIGRATION_ADJUST_STEPS 16
1760 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1761 unsigned long rate_limit,
1762 unsigned int ref_th)
1764 unsigned int now, start, th_period, unit_th, th;
1765 unsigned long nr_cand, ref_cand, diff_cand;
1767 now = jiffies_to_msecs(jiffies);
1768 th_period = sysctl_numa_balancing_scan_period_max;
1769 start = pgdat->nbp_th_start;
1770 if (now - start > th_period &&
1771 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1772 ref_cand = rate_limit *
1773 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1774 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1775 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1776 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1777 th = pgdat->nbp_threshold ? : ref_th;
1778 if (diff_cand > ref_cand * 11 / 10)
1779 th = max(th - unit_th, unit_th);
1780 else if (diff_cand < ref_cand * 9 / 10)
1781 th = min(th + unit_th, ref_th * 2);
1782 pgdat->nbp_th_nr_cand = nr_cand;
1783 pgdat->nbp_threshold = th;
1787 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1788 int src_nid, int dst_cpu)
1790 struct numa_group *ng = deref_curr_numa_group(p);
1791 int dst_nid = cpu_to_node(dst_cpu);
1792 int last_cpupid, this_cpupid;
1795 * The pages in slow memory node should be migrated according
1796 * to hot/cold instead of private/shared.
1798 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1799 !node_is_toptier(src_nid)) {
1800 struct pglist_data *pgdat;
1801 unsigned long rate_limit;
1802 unsigned int latency, th, def_th;
1804 pgdat = NODE_DATA(dst_nid);
1805 if (pgdat_free_space_enough(pgdat)) {
1806 /* workload changed, reset hot threshold */
1807 pgdat->nbp_threshold = 0;
1811 def_th = sysctl_numa_balancing_hot_threshold;
1812 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1814 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1816 th = pgdat->nbp_threshold ? : def_th;
1817 latency = numa_hint_fault_latency(page);
1821 return !numa_promotion_rate_limit(pgdat, rate_limit,
1822 thp_nr_pages(page));
1825 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1826 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1828 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1829 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1833 * Allow first faults or private faults to migrate immediately early in
1834 * the lifetime of a task. The magic number 4 is based on waiting for
1835 * two full passes of the "multi-stage node selection" test that is
1838 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1839 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1843 * Multi-stage node selection is used in conjunction with a periodic
1844 * migration fault to build a temporal task<->page relation. By using
1845 * a two-stage filter we remove short/unlikely relations.
1847 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1848 * a task's usage of a particular page (n_p) per total usage of this
1849 * page (n_t) (in a given time-span) to a probability.
1851 * Our periodic faults will sample this probability and getting the
1852 * same result twice in a row, given these samples are fully
1853 * independent, is then given by P(n)^2, provided our sample period
1854 * is sufficiently short compared to the usage pattern.
1856 * This quadric squishes small probabilities, making it less likely we
1857 * act on an unlikely task<->page relation.
1859 if (!cpupid_pid_unset(last_cpupid) &&
1860 cpupid_to_nid(last_cpupid) != dst_nid)
1863 /* Always allow migrate on private faults */
1864 if (cpupid_match_pid(p, last_cpupid))
1867 /* A shared fault, but p->numa_group has not been set up yet. */
1872 * Destination node is much more heavily used than the source
1873 * node? Allow migration.
1875 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1876 ACTIVE_NODE_FRACTION)
1880 * Distribute memory according to CPU & memory use on each node,
1881 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1883 * faults_cpu(dst) 3 faults_cpu(src)
1884 * --------------- * - > ---------------
1885 * faults_mem(dst) 4 faults_mem(src)
1887 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1888 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1892 * 'numa_type' describes the node at the moment of load balancing.
1895 /* The node has spare capacity that can be used to run more tasks. */
1898 * The node is fully used and the tasks don't compete for more CPU
1899 * cycles. Nevertheless, some tasks might wait before running.
1903 * The node is overloaded and can't provide expected CPU cycles to all
1909 /* Cached statistics for all CPUs within a node */
1912 unsigned long runnable;
1914 /* Total compute capacity of CPUs on a node */
1915 unsigned long compute_capacity;
1916 unsigned int nr_running;
1917 unsigned int weight;
1918 enum numa_type node_type;
1922 struct task_numa_env {
1923 struct task_struct *p;
1925 int src_cpu, src_nid;
1926 int dst_cpu, dst_nid;
1929 struct numa_stats src_stats, dst_stats;
1934 struct task_struct *best_task;
1939 static unsigned long cpu_load(struct rq *rq);
1940 static unsigned long cpu_runnable(struct rq *rq);
1943 numa_type numa_classify(unsigned int imbalance_pct,
1944 struct numa_stats *ns)
1946 if ((ns->nr_running > ns->weight) &&
1947 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
1948 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
1949 return node_overloaded;
1951 if ((ns->nr_running < ns->weight) ||
1952 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
1953 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
1954 return node_has_spare;
1956 return node_fully_busy;
1959 #ifdef CONFIG_SCHED_SMT
1960 /* Forward declarations of select_idle_sibling helpers */
1961 static inline bool test_idle_cores(int cpu);
1962 static inline int numa_idle_core(int idle_core, int cpu)
1964 if (!static_branch_likely(&sched_smt_present) ||
1965 idle_core >= 0 || !test_idle_cores(cpu))
1969 * Prefer cores instead of packing HT siblings
1970 * and triggering future load balancing.
1972 if (is_core_idle(cpu))
1978 static inline int numa_idle_core(int idle_core, int cpu)
1985 * Gather all necessary information to make NUMA balancing placement
1986 * decisions that are compatible with standard load balancer. This
1987 * borrows code and logic from update_sg_lb_stats but sharing a
1988 * common implementation is impractical.
1990 static void update_numa_stats(struct task_numa_env *env,
1991 struct numa_stats *ns, int nid,
1994 int cpu, idle_core = -1;
1996 memset(ns, 0, sizeof(*ns));
2000 for_each_cpu(cpu, cpumask_of_node(nid)) {
2001 struct rq *rq = cpu_rq(cpu);
2003 ns->load += cpu_load(rq);
2004 ns->runnable += cpu_runnable(rq);
2005 ns->util += cpu_util_cfs(cpu);
2006 ns->nr_running += rq->cfs.h_nr_running;
2007 ns->compute_capacity += capacity_of(cpu);
2009 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2010 if (READ_ONCE(rq->numa_migrate_on) ||
2011 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2014 if (ns->idle_cpu == -1)
2017 idle_core = numa_idle_core(idle_core, cpu);
2022 ns->weight = cpumask_weight(cpumask_of_node(nid));
2024 ns->node_type = numa_classify(env->imbalance_pct, ns);
2027 ns->idle_cpu = idle_core;
2030 static void task_numa_assign(struct task_numa_env *env,
2031 struct task_struct *p, long imp)
2033 struct rq *rq = cpu_rq(env->dst_cpu);
2035 /* Check if run-queue part of active NUMA balance. */
2036 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2038 int start = env->dst_cpu;
2040 /* Find alternative idle CPU. */
2041 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2042 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2043 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2048 rq = cpu_rq(env->dst_cpu);
2049 if (!xchg(&rq->numa_migrate_on, 1))
2053 /* Failed to find an alternative idle CPU */
2059 * Clear previous best_cpu/rq numa-migrate flag, since task now
2060 * found a better CPU to move/swap.
2062 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2063 rq = cpu_rq(env->best_cpu);
2064 WRITE_ONCE(rq->numa_migrate_on, 0);
2068 put_task_struct(env->best_task);
2073 env->best_imp = imp;
2074 env->best_cpu = env->dst_cpu;
2077 static bool load_too_imbalanced(long src_load, long dst_load,
2078 struct task_numa_env *env)
2081 long orig_src_load, orig_dst_load;
2082 long src_capacity, dst_capacity;
2085 * The load is corrected for the CPU capacity available on each node.
2088 * ------------ vs ---------
2089 * src_capacity dst_capacity
2091 src_capacity = env->src_stats.compute_capacity;
2092 dst_capacity = env->dst_stats.compute_capacity;
2094 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2096 orig_src_load = env->src_stats.load;
2097 orig_dst_load = env->dst_stats.load;
2099 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2101 /* Would this change make things worse? */
2102 return (imb > old_imb);
2106 * Maximum NUMA importance can be 1998 (2*999);
2107 * SMALLIMP @ 30 would be close to 1998/64.
2108 * Used to deter task migration.
2113 * This checks if the overall compute and NUMA accesses of the system would
2114 * be improved if the source tasks was migrated to the target dst_cpu taking
2115 * into account that it might be best if task running on the dst_cpu should
2116 * be exchanged with the source task
2118 static bool task_numa_compare(struct task_numa_env *env,
2119 long taskimp, long groupimp, bool maymove)
2121 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2122 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2123 long imp = p_ng ? groupimp : taskimp;
2124 struct task_struct *cur;
2125 long src_load, dst_load;
2126 int dist = env->dist;
2129 bool stopsearch = false;
2131 if (READ_ONCE(dst_rq->numa_migrate_on))
2135 cur = rcu_dereference(dst_rq->curr);
2136 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2140 * Because we have preemption enabled we can get migrated around and
2141 * end try selecting ourselves (current == env->p) as a swap candidate.
2143 if (cur == env->p) {
2149 if (maymove && moveimp >= env->best_imp)
2155 /* Skip this swap candidate if cannot move to the source cpu. */
2156 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2160 * Skip this swap candidate if it is not moving to its preferred
2161 * node and the best task is.
2163 if (env->best_task &&
2164 env->best_task->numa_preferred_nid == env->src_nid &&
2165 cur->numa_preferred_nid != env->src_nid) {
2170 * "imp" is the fault differential for the source task between the
2171 * source and destination node. Calculate the total differential for
2172 * the source task and potential destination task. The more negative
2173 * the value is, the more remote accesses that would be expected to
2174 * be incurred if the tasks were swapped.
2176 * If dst and source tasks are in the same NUMA group, or not
2177 * in any group then look only at task weights.
2179 cur_ng = rcu_dereference(cur->numa_group);
2180 if (cur_ng == p_ng) {
2182 * Do not swap within a group or between tasks that have
2183 * no group if there is spare capacity. Swapping does
2184 * not address the load imbalance and helps one task at
2185 * the cost of punishing another.
2187 if (env->dst_stats.node_type == node_has_spare)
2190 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2191 task_weight(cur, env->dst_nid, dist);
2193 * Add some hysteresis to prevent swapping the
2194 * tasks within a group over tiny differences.
2200 * Compare the group weights. If a task is all by itself
2201 * (not part of a group), use the task weight instead.
2204 imp += group_weight(cur, env->src_nid, dist) -
2205 group_weight(cur, env->dst_nid, dist);
2207 imp += task_weight(cur, env->src_nid, dist) -
2208 task_weight(cur, env->dst_nid, dist);
2211 /* Discourage picking a task already on its preferred node */
2212 if (cur->numa_preferred_nid == env->dst_nid)
2216 * Encourage picking a task that moves to its preferred node.
2217 * This potentially makes imp larger than it's maximum of
2218 * 1998 (see SMALLIMP and task_weight for why) but in this
2219 * case, it does not matter.
2221 if (cur->numa_preferred_nid == env->src_nid)
2224 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2231 * Prefer swapping with a task moving to its preferred node over a
2234 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2235 env->best_task->numa_preferred_nid != env->src_nid) {
2240 * If the NUMA importance is less than SMALLIMP,
2241 * task migration might only result in ping pong
2242 * of tasks and also hurt performance due to cache
2245 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2249 * In the overloaded case, try and keep the load balanced.
2251 load = task_h_load(env->p) - task_h_load(cur);
2255 dst_load = env->dst_stats.load + load;
2256 src_load = env->src_stats.load - load;
2258 if (load_too_imbalanced(src_load, dst_load, env))
2262 /* Evaluate an idle CPU for a task numa move. */
2264 int cpu = env->dst_stats.idle_cpu;
2266 /* Nothing cached so current CPU went idle since the search. */
2271 * If the CPU is no longer truly idle and the previous best CPU
2272 * is, keep using it.
2274 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2275 idle_cpu(env->best_cpu)) {
2276 cpu = env->best_cpu;
2282 task_numa_assign(env, cur, imp);
2285 * If a move to idle is allowed because there is capacity or load
2286 * balance improves then stop the search. While a better swap
2287 * candidate may exist, a search is not free.
2289 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2293 * If a swap candidate must be identified and the current best task
2294 * moves its preferred node then stop the search.
2296 if (!maymove && env->best_task &&
2297 env->best_task->numa_preferred_nid == env->src_nid) {
2306 static void task_numa_find_cpu(struct task_numa_env *env,
2307 long taskimp, long groupimp)
2309 bool maymove = false;
2313 * If dst node has spare capacity, then check if there is an
2314 * imbalance that would be overruled by the load balancer.
2316 if (env->dst_stats.node_type == node_has_spare) {
2317 unsigned int imbalance;
2318 int src_running, dst_running;
2321 * Would movement cause an imbalance? Note that if src has
2322 * more running tasks that the imbalance is ignored as the
2323 * move improves the imbalance from the perspective of the
2324 * CPU load balancer.
2326 src_running = env->src_stats.nr_running - 1;
2327 dst_running = env->dst_stats.nr_running + 1;
2328 imbalance = max(0, dst_running - src_running);
2329 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2332 /* Use idle CPU if there is no imbalance */
2335 if (env->dst_stats.idle_cpu >= 0) {
2336 env->dst_cpu = env->dst_stats.idle_cpu;
2337 task_numa_assign(env, NULL, 0);
2342 long src_load, dst_load, load;
2344 * If the improvement from just moving env->p direction is better
2345 * than swapping tasks around, check if a move is possible.
2347 load = task_h_load(env->p);
2348 dst_load = env->dst_stats.load + load;
2349 src_load = env->src_stats.load - load;
2350 maymove = !load_too_imbalanced(src_load, dst_load, env);
2353 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2354 /* Skip this CPU if the source task cannot migrate */
2355 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2359 if (task_numa_compare(env, taskimp, groupimp, maymove))
2364 static int task_numa_migrate(struct task_struct *p)
2366 struct task_numa_env env = {
2369 .src_cpu = task_cpu(p),
2370 .src_nid = task_node(p),
2372 .imbalance_pct = 112,
2378 unsigned long taskweight, groupweight;
2379 struct sched_domain *sd;
2380 long taskimp, groupimp;
2381 struct numa_group *ng;
2386 * Pick the lowest SD_NUMA domain, as that would have the smallest
2387 * imbalance and would be the first to start moving tasks about.
2389 * And we want to avoid any moving of tasks about, as that would create
2390 * random movement of tasks -- counter the numa conditions we're trying
2394 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2396 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2397 env.imb_numa_nr = sd->imb_numa_nr;
2402 * Cpusets can break the scheduler domain tree into smaller
2403 * balance domains, some of which do not cross NUMA boundaries.
2404 * Tasks that are "trapped" in such domains cannot be migrated
2405 * elsewhere, so there is no point in (re)trying.
2407 if (unlikely(!sd)) {
2408 sched_setnuma(p, task_node(p));
2412 env.dst_nid = p->numa_preferred_nid;
2413 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2414 taskweight = task_weight(p, env.src_nid, dist);
2415 groupweight = group_weight(p, env.src_nid, dist);
2416 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2417 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2418 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2419 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2421 /* Try to find a spot on the preferred nid. */
2422 task_numa_find_cpu(&env, taskimp, groupimp);
2425 * Look at other nodes in these cases:
2426 * - there is no space available on the preferred_nid
2427 * - the task is part of a numa_group that is interleaved across
2428 * multiple NUMA nodes; in order to better consolidate the group,
2429 * we need to check other locations.
2431 ng = deref_curr_numa_group(p);
2432 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2433 for_each_node_state(nid, N_CPU) {
2434 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2437 dist = node_distance(env.src_nid, env.dst_nid);
2438 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2440 taskweight = task_weight(p, env.src_nid, dist);
2441 groupweight = group_weight(p, env.src_nid, dist);
2444 /* Only consider nodes where both task and groups benefit */
2445 taskimp = task_weight(p, nid, dist) - taskweight;
2446 groupimp = group_weight(p, nid, dist) - groupweight;
2447 if (taskimp < 0 && groupimp < 0)
2452 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2453 task_numa_find_cpu(&env, taskimp, groupimp);
2458 * If the task is part of a workload that spans multiple NUMA nodes,
2459 * and is migrating into one of the workload's active nodes, remember
2460 * this node as the task's preferred numa node, so the workload can
2462 * A task that migrated to a second choice node will be better off
2463 * trying for a better one later. Do not set the preferred node here.
2466 if (env.best_cpu == -1)
2469 nid = cpu_to_node(env.best_cpu);
2471 if (nid != p->numa_preferred_nid)
2472 sched_setnuma(p, nid);
2475 /* No better CPU than the current one was found. */
2476 if (env.best_cpu == -1) {
2477 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2481 best_rq = cpu_rq(env.best_cpu);
2482 if (env.best_task == NULL) {
2483 ret = migrate_task_to(p, env.best_cpu);
2484 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2486 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2490 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2491 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2494 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2495 put_task_struct(env.best_task);
2499 /* Attempt to migrate a task to a CPU on the preferred node. */
2500 static void numa_migrate_preferred(struct task_struct *p)
2502 unsigned long interval = HZ;
2504 /* This task has no NUMA fault statistics yet */
2505 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2508 /* Periodically retry migrating the task to the preferred node */
2509 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2510 p->numa_migrate_retry = jiffies + interval;
2512 /* Success if task is already running on preferred CPU */
2513 if (task_node(p) == p->numa_preferred_nid)
2516 /* Otherwise, try migrate to a CPU on the preferred node */
2517 task_numa_migrate(p);
2521 * Find out how many nodes the workload is actively running on. Do this by
2522 * tracking the nodes from which NUMA hinting faults are triggered. This can
2523 * be different from the set of nodes where the workload's memory is currently
2526 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2528 unsigned long faults, max_faults = 0;
2529 int nid, active_nodes = 0;
2531 for_each_node_state(nid, N_CPU) {
2532 faults = group_faults_cpu(numa_group, nid);
2533 if (faults > max_faults)
2534 max_faults = faults;
2537 for_each_node_state(nid, N_CPU) {
2538 faults = group_faults_cpu(numa_group, nid);
2539 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2543 numa_group->max_faults_cpu = max_faults;
2544 numa_group->active_nodes = active_nodes;
2548 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2549 * increments. The more local the fault statistics are, the higher the scan
2550 * period will be for the next scan window. If local/(local+remote) ratio is
2551 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2552 * the scan period will decrease. Aim for 70% local accesses.
2554 #define NUMA_PERIOD_SLOTS 10
2555 #define NUMA_PERIOD_THRESHOLD 7
2558 * Increase the scan period (slow down scanning) if the majority of
2559 * our memory is already on our local node, or if the majority of
2560 * the page accesses are shared with other processes.
2561 * Otherwise, decrease the scan period.
2563 static void update_task_scan_period(struct task_struct *p,
2564 unsigned long shared, unsigned long private)
2566 unsigned int period_slot;
2567 int lr_ratio, ps_ratio;
2570 unsigned long remote = p->numa_faults_locality[0];
2571 unsigned long local = p->numa_faults_locality[1];
2574 * If there were no record hinting faults then either the task is
2575 * completely idle or all activity is in areas that are not of interest
2576 * to automatic numa balancing. Related to that, if there were failed
2577 * migration then it implies we are migrating too quickly or the local
2578 * node is overloaded. In either case, scan slower
2580 if (local + shared == 0 || p->numa_faults_locality[2]) {
2581 p->numa_scan_period = min(p->numa_scan_period_max,
2582 p->numa_scan_period << 1);
2584 p->mm->numa_next_scan = jiffies +
2585 msecs_to_jiffies(p->numa_scan_period);
2591 * Prepare to scale scan period relative to the current period.
2592 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2593 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2594 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2596 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2597 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2598 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2600 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2602 * Most memory accesses are local. There is no need to
2603 * do fast NUMA scanning, since memory is already local.
2605 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2608 diff = slot * period_slot;
2609 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2611 * Most memory accesses are shared with other tasks.
2612 * There is no point in continuing fast NUMA scanning,
2613 * since other tasks may just move the memory elsewhere.
2615 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2618 diff = slot * period_slot;
2621 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2622 * yet they are not on the local NUMA node. Speed up
2623 * NUMA scanning to get the memory moved over.
2625 int ratio = max(lr_ratio, ps_ratio);
2626 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2629 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2630 task_scan_min(p), task_scan_max(p));
2631 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2635 * Get the fraction of time the task has been running since the last
2636 * NUMA placement cycle. The scheduler keeps similar statistics, but
2637 * decays those on a 32ms period, which is orders of magnitude off
2638 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2639 * stats only if the task is so new there are no NUMA statistics yet.
2641 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2643 u64 runtime, delta, now;
2644 /* Use the start of this time slice to avoid calculations. */
2645 now = p->se.exec_start;
2646 runtime = p->se.sum_exec_runtime;
2648 if (p->last_task_numa_placement) {
2649 delta = runtime - p->last_sum_exec_runtime;
2650 *period = now - p->last_task_numa_placement;
2652 /* Avoid time going backwards, prevent potential divide error: */
2653 if (unlikely((s64)*period < 0))
2656 delta = p->se.avg.load_sum;
2657 *period = LOAD_AVG_MAX;
2660 p->last_sum_exec_runtime = runtime;
2661 p->last_task_numa_placement = now;
2667 * Determine the preferred nid for a task in a numa_group. This needs to
2668 * be done in a way that produces consistent results with group_weight,
2669 * otherwise workloads might not converge.
2671 static int preferred_group_nid(struct task_struct *p, int nid)
2676 /* Direct connections between all NUMA nodes. */
2677 if (sched_numa_topology_type == NUMA_DIRECT)
2681 * On a system with glueless mesh NUMA topology, group_weight
2682 * scores nodes according to the number of NUMA hinting faults on
2683 * both the node itself, and on nearby nodes.
2685 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2686 unsigned long score, max_score = 0;
2687 int node, max_node = nid;
2689 dist = sched_max_numa_distance;
2691 for_each_node_state(node, N_CPU) {
2692 score = group_weight(p, node, dist);
2693 if (score > max_score) {
2702 * Finding the preferred nid in a system with NUMA backplane
2703 * interconnect topology is more involved. The goal is to locate
2704 * tasks from numa_groups near each other in the system, and
2705 * untangle workloads from different sides of the system. This requires
2706 * searching down the hierarchy of node groups, recursively searching
2707 * inside the highest scoring group of nodes. The nodemask tricks
2708 * keep the complexity of the search down.
2710 nodes = node_states[N_CPU];
2711 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2712 unsigned long max_faults = 0;
2713 nodemask_t max_group = NODE_MASK_NONE;
2716 /* Are there nodes at this distance from each other? */
2717 if (!find_numa_distance(dist))
2720 for_each_node_mask(a, nodes) {
2721 unsigned long faults = 0;
2722 nodemask_t this_group;
2723 nodes_clear(this_group);
2725 /* Sum group's NUMA faults; includes a==b case. */
2726 for_each_node_mask(b, nodes) {
2727 if (node_distance(a, b) < dist) {
2728 faults += group_faults(p, b);
2729 node_set(b, this_group);
2730 node_clear(b, nodes);
2734 /* Remember the top group. */
2735 if (faults > max_faults) {
2736 max_faults = faults;
2737 max_group = this_group;
2739 * subtle: at the smallest distance there is
2740 * just one node left in each "group", the
2741 * winner is the preferred nid.
2746 /* Next round, evaluate the nodes within max_group. */
2754 static void task_numa_placement(struct task_struct *p)
2756 int seq, nid, max_nid = NUMA_NO_NODE;
2757 unsigned long max_faults = 0;
2758 unsigned long fault_types[2] = { 0, 0 };
2759 unsigned long total_faults;
2760 u64 runtime, period;
2761 spinlock_t *group_lock = NULL;
2762 struct numa_group *ng;
2765 * The p->mm->numa_scan_seq field gets updated without
2766 * exclusive access. Use READ_ONCE() here to ensure
2767 * that the field is read in a single access:
2769 seq = READ_ONCE(p->mm->numa_scan_seq);
2770 if (p->numa_scan_seq == seq)
2772 p->numa_scan_seq = seq;
2773 p->numa_scan_period_max = task_scan_max(p);
2775 total_faults = p->numa_faults_locality[0] +
2776 p->numa_faults_locality[1];
2777 runtime = numa_get_avg_runtime(p, &period);
2779 /* If the task is part of a group prevent parallel updates to group stats */
2780 ng = deref_curr_numa_group(p);
2782 group_lock = &ng->lock;
2783 spin_lock_irq(group_lock);
2786 /* Find the node with the highest number of faults */
2787 for_each_online_node(nid) {
2788 /* Keep track of the offsets in numa_faults array */
2789 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2790 unsigned long faults = 0, group_faults = 0;
2793 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2794 long diff, f_diff, f_weight;
2796 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2797 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2798 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2799 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2801 /* Decay existing window, copy faults since last scan */
2802 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2803 fault_types[priv] += p->numa_faults[membuf_idx];
2804 p->numa_faults[membuf_idx] = 0;
2807 * Normalize the faults_from, so all tasks in a group
2808 * count according to CPU use, instead of by the raw
2809 * number of faults. Tasks with little runtime have
2810 * little over-all impact on throughput, and thus their
2811 * faults are less important.
2813 f_weight = div64_u64(runtime << 16, period + 1);
2814 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2816 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2817 p->numa_faults[cpubuf_idx] = 0;
2819 p->numa_faults[mem_idx] += diff;
2820 p->numa_faults[cpu_idx] += f_diff;
2821 faults += p->numa_faults[mem_idx];
2822 p->total_numa_faults += diff;
2825 * safe because we can only change our own group
2827 * mem_idx represents the offset for a given
2828 * nid and priv in a specific region because it
2829 * is at the beginning of the numa_faults array.
2831 ng->faults[mem_idx] += diff;
2832 ng->faults[cpu_idx] += f_diff;
2833 ng->total_faults += diff;
2834 group_faults += ng->faults[mem_idx];
2839 if (faults > max_faults) {
2840 max_faults = faults;
2843 } else if (group_faults > max_faults) {
2844 max_faults = group_faults;
2849 /* Cannot migrate task to CPU-less node */
2850 if (max_nid != NUMA_NO_NODE && !node_state(max_nid, N_CPU)) {
2851 int near_nid = max_nid;
2852 int distance, near_distance = INT_MAX;
2854 for_each_node_state(nid, N_CPU) {
2855 distance = node_distance(max_nid, nid);
2856 if (distance < near_distance) {
2858 near_distance = distance;
2865 numa_group_count_active_nodes(ng);
2866 spin_unlock_irq(group_lock);
2867 max_nid = preferred_group_nid(p, max_nid);
2871 /* Set the new preferred node */
2872 if (max_nid != p->numa_preferred_nid)
2873 sched_setnuma(p, max_nid);
2876 update_task_scan_period(p, fault_types[0], fault_types[1]);
2879 static inline int get_numa_group(struct numa_group *grp)
2881 return refcount_inc_not_zero(&grp->refcount);
2884 static inline void put_numa_group(struct numa_group *grp)
2886 if (refcount_dec_and_test(&grp->refcount))
2887 kfree_rcu(grp, rcu);
2890 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2893 struct numa_group *grp, *my_grp;
2894 struct task_struct *tsk;
2896 int cpu = cpupid_to_cpu(cpupid);
2899 if (unlikely(!deref_curr_numa_group(p))) {
2900 unsigned int size = sizeof(struct numa_group) +
2901 NR_NUMA_HINT_FAULT_STATS *
2902 nr_node_ids * sizeof(unsigned long);
2904 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2908 refcount_set(&grp->refcount, 1);
2909 grp->active_nodes = 1;
2910 grp->max_faults_cpu = 0;
2911 spin_lock_init(&grp->lock);
2914 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2915 grp->faults[i] = p->numa_faults[i];
2917 grp->total_faults = p->total_numa_faults;
2920 rcu_assign_pointer(p->numa_group, grp);
2924 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2926 if (!cpupid_match_pid(tsk, cpupid))
2929 grp = rcu_dereference(tsk->numa_group);
2933 my_grp = deref_curr_numa_group(p);
2938 * Only join the other group if its bigger; if we're the bigger group,
2939 * the other task will join us.
2941 if (my_grp->nr_tasks > grp->nr_tasks)
2945 * Tie-break on the grp address.
2947 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2950 /* Always join threads in the same process. */
2951 if (tsk->mm == current->mm)
2954 /* Simple filter to avoid false positives due to PID collisions */
2955 if (flags & TNF_SHARED)
2958 /* Update priv based on whether false sharing was detected */
2961 if (join && !get_numa_group(grp))
2969 WARN_ON_ONCE(irqs_disabled());
2970 double_lock_irq(&my_grp->lock, &grp->lock);
2972 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2973 my_grp->faults[i] -= p->numa_faults[i];
2974 grp->faults[i] += p->numa_faults[i];
2976 my_grp->total_faults -= p->total_numa_faults;
2977 grp->total_faults += p->total_numa_faults;
2982 spin_unlock(&my_grp->lock);
2983 spin_unlock_irq(&grp->lock);
2985 rcu_assign_pointer(p->numa_group, grp);
2987 put_numa_group(my_grp);
2996 * Get rid of NUMA statistics associated with a task (either current or dead).
2997 * If @final is set, the task is dead and has reached refcount zero, so we can
2998 * safely free all relevant data structures. Otherwise, there might be
2999 * concurrent reads from places like load balancing and procfs, and we should
3000 * reset the data back to default state without freeing ->numa_faults.
3002 void task_numa_free(struct task_struct *p, bool final)
3004 /* safe: p either is current or is being freed by current */
3005 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3006 unsigned long *numa_faults = p->numa_faults;
3007 unsigned long flags;
3014 spin_lock_irqsave(&grp->lock, flags);
3015 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3016 grp->faults[i] -= p->numa_faults[i];
3017 grp->total_faults -= p->total_numa_faults;
3020 spin_unlock_irqrestore(&grp->lock, flags);
3021 RCU_INIT_POINTER(p->numa_group, NULL);
3022 put_numa_group(grp);
3026 p->numa_faults = NULL;
3029 p->total_numa_faults = 0;
3030 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3036 * Got a PROT_NONE fault for a page on @node.
3038 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3040 struct task_struct *p = current;
3041 bool migrated = flags & TNF_MIGRATED;
3042 int cpu_node = task_node(current);
3043 int local = !!(flags & TNF_FAULT_LOCAL);
3044 struct numa_group *ng;
3047 if (!static_branch_likely(&sched_numa_balancing))
3050 /* for example, ksmd faulting in a user's mm */
3055 * NUMA faults statistics are unnecessary for the slow memory
3056 * node for memory tiering mode.
3058 if (!node_is_toptier(mem_node) &&
3059 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3060 !cpupid_valid(last_cpupid)))
3063 /* Allocate buffer to track faults on a per-node basis */
3064 if (unlikely(!p->numa_faults)) {
3065 int size = sizeof(*p->numa_faults) *
3066 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3068 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3069 if (!p->numa_faults)
3072 p->total_numa_faults = 0;
3073 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3077 * First accesses are treated as private, otherwise consider accesses
3078 * to be private if the accessing pid has not changed
3080 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3083 priv = cpupid_match_pid(p, last_cpupid);
3084 if (!priv && !(flags & TNF_NO_GROUP))
3085 task_numa_group(p, last_cpupid, flags, &priv);
3089 * If a workload spans multiple NUMA nodes, a shared fault that
3090 * occurs wholly within the set of nodes that the workload is
3091 * actively using should be counted as local. This allows the
3092 * scan rate to slow down when a workload has settled down.
3094 ng = deref_curr_numa_group(p);
3095 if (!priv && !local && ng && ng->active_nodes > 1 &&
3096 numa_is_active_node(cpu_node, ng) &&
3097 numa_is_active_node(mem_node, ng))
3101 * Retry to migrate task to preferred node periodically, in case it
3102 * previously failed, or the scheduler moved us.
3104 if (time_after(jiffies, p->numa_migrate_retry)) {
3105 task_numa_placement(p);
3106 numa_migrate_preferred(p);
3110 p->numa_pages_migrated += pages;
3111 if (flags & TNF_MIGRATE_FAIL)
3112 p->numa_faults_locality[2] += pages;
3114 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3115 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3116 p->numa_faults_locality[local] += pages;
3119 static void reset_ptenuma_scan(struct task_struct *p)
3122 * We only did a read acquisition of the mmap sem, so
3123 * p->mm->numa_scan_seq is written to without exclusive access
3124 * and the update is not guaranteed to be atomic. That's not
3125 * much of an issue though, since this is just used for
3126 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3127 * expensive, to avoid any form of compiler optimizations:
3129 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3130 p->mm->numa_scan_offset = 0;
3133 static bool vma_is_accessed(struct vm_area_struct *vma)
3137 * Allow unconditional access first two times, so that all the (pages)
3138 * of VMAs get prot_none fault introduced irrespective of accesses.
3139 * This is also done to avoid any side effect of task scanning
3140 * amplifying the unfairness of disjoint set of VMAs' access.
3142 if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3145 pids = vma->numab_state->access_pids[0] | vma->numab_state->access_pids[1];
3146 return test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids);
3149 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3152 * The expensive part of numa migration is done from task_work context.
3153 * Triggered from task_tick_numa().
3155 static void task_numa_work(struct callback_head *work)
3157 unsigned long migrate, next_scan, now = jiffies;
3158 struct task_struct *p = current;
3159 struct mm_struct *mm = p->mm;
3160 u64 runtime = p->se.sum_exec_runtime;
3161 struct vm_area_struct *vma;
3162 unsigned long start, end;
3163 unsigned long nr_pte_updates = 0;
3164 long pages, virtpages;
3165 struct vma_iterator vmi;
3167 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3171 * Who cares about NUMA placement when they're dying.
3173 * NOTE: make sure not to dereference p->mm before this check,
3174 * exit_task_work() happens _after_ exit_mm() so we could be called
3175 * without p->mm even though we still had it when we enqueued this
3178 if (p->flags & PF_EXITING)
3181 if (!mm->numa_next_scan) {
3182 mm->numa_next_scan = now +
3183 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3187 * Enforce maximal scan/migration frequency..
3189 migrate = mm->numa_next_scan;
3190 if (time_before(now, migrate))
3193 if (p->numa_scan_period == 0) {
3194 p->numa_scan_period_max = task_scan_max(p);
3195 p->numa_scan_period = task_scan_start(p);
3198 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3199 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3203 * Delay this task enough that another task of this mm will likely win
3204 * the next time around.
3206 p->node_stamp += 2 * TICK_NSEC;
3208 start = mm->numa_scan_offset;
3209 pages = sysctl_numa_balancing_scan_size;
3210 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3211 virtpages = pages * 8; /* Scan up to this much virtual space */
3216 if (!mmap_read_trylock(mm))
3218 vma_iter_init(&vmi, mm, start);
3219 vma = vma_next(&vmi);
3221 reset_ptenuma_scan(p);
3223 vma_iter_set(&vmi, start);
3224 vma = vma_next(&vmi);
3228 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3229 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3234 * Shared library pages mapped by multiple processes are not
3235 * migrated as it is expected they are cache replicated. Avoid
3236 * hinting faults in read-only file-backed mappings or the vdso
3237 * as migrating the pages will be of marginal benefit.
3240 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
3244 * Skip inaccessible VMAs to avoid any confusion between
3245 * PROT_NONE and NUMA hinting ptes
3247 if (!vma_is_accessible(vma))
3250 /* Initialise new per-VMA NUMAB state. */
3251 if (!vma->numab_state) {
3252 vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3254 if (!vma->numab_state)
3257 vma->numab_state->next_scan = now +
3258 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3260 /* Reset happens after 4 times scan delay of scan start */
3261 vma->numab_state->next_pid_reset = vma->numab_state->next_scan +
3262 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3266 * Scanning the VMA's of short lived tasks add more overhead. So
3267 * delay the scan for new VMAs.
3269 if (mm->numa_scan_seq && time_before(jiffies,
3270 vma->numab_state->next_scan))
3273 /* Do not scan the VMA if task has not accessed */
3274 if (!vma_is_accessed(vma))
3278 * RESET access PIDs regularly for old VMAs. Resetting after checking
3279 * vma for recent access to avoid clearing PID info before access..
3281 if (mm->numa_scan_seq &&
3282 time_after(jiffies, vma->numab_state->next_pid_reset)) {
3283 vma->numab_state->next_pid_reset = vma->numab_state->next_pid_reset +
3284 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3285 vma->numab_state->access_pids[0] = READ_ONCE(vma->numab_state->access_pids[1]);
3286 vma->numab_state->access_pids[1] = 0;
3290 start = max(start, vma->vm_start);
3291 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3292 end = min(end, vma->vm_end);
3293 nr_pte_updates = change_prot_numa(vma, start, end);
3296 * Try to scan sysctl_numa_balancing_size worth of
3297 * hpages that have at least one present PTE that
3298 * is not already pte-numa. If the VMA contains
3299 * areas that are unused or already full of prot_numa
3300 * PTEs, scan up to virtpages, to skip through those
3304 pages -= (end - start) >> PAGE_SHIFT;
3305 virtpages -= (end - start) >> PAGE_SHIFT;
3308 if (pages <= 0 || virtpages <= 0)
3312 } while (end != vma->vm_end);
3313 } for_each_vma(vmi, vma);
3317 * It is possible to reach the end of the VMA list but the last few
3318 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3319 * would find the !migratable VMA on the next scan but not reset the
3320 * scanner to the start so check it now.
3323 mm->numa_scan_offset = start;
3325 reset_ptenuma_scan(p);
3326 mmap_read_unlock(mm);
3329 * Make sure tasks use at least 32x as much time to run other code
3330 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3331 * Usually update_task_scan_period slows down scanning enough; on an
3332 * overloaded system we need to limit overhead on a per task basis.
3334 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3335 u64 diff = p->se.sum_exec_runtime - runtime;
3336 p->node_stamp += 32 * diff;
3340 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3343 struct mm_struct *mm = p->mm;
3346 mm_users = atomic_read(&mm->mm_users);
3347 if (mm_users == 1) {
3348 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3349 mm->numa_scan_seq = 0;
3353 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3354 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3355 p->numa_migrate_retry = 0;
3356 /* Protect against double add, see task_tick_numa and task_numa_work */
3357 p->numa_work.next = &p->numa_work;
3358 p->numa_faults = NULL;
3359 p->numa_pages_migrated = 0;
3360 p->total_numa_faults = 0;
3361 RCU_INIT_POINTER(p->numa_group, NULL);
3362 p->last_task_numa_placement = 0;
3363 p->last_sum_exec_runtime = 0;
3365 init_task_work(&p->numa_work, task_numa_work);
3367 /* New address space, reset the preferred nid */
3368 if (!(clone_flags & CLONE_VM)) {
3369 p->numa_preferred_nid = NUMA_NO_NODE;
3374 * New thread, keep existing numa_preferred_nid which should be copied
3375 * already by arch_dup_task_struct but stagger when scans start.
3380 delay = min_t(unsigned int, task_scan_max(current),
3381 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3382 delay += 2 * TICK_NSEC;
3383 p->node_stamp = delay;
3388 * Drive the periodic memory faults..
3390 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3392 struct callback_head *work = &curr->numa_work;
3396 * We don't care about NUMA placement if we don't have memory.
3398 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3402 * Using runtime rather than walltime has the dual advantage that
3403 * we (mostly) drive the selection from busy threads and that the
3404 * task needs to have done some actual work before we bother with
3407 now = curr->se.sum_exec_runtime;
3408 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3410 if (now > curr->node_stamp + period) {
3411 if (!curr->node_stamp)
3412 curr->numa_scan_period = task_scan_start(curr);
3413 curr->node_stamp += period;
3415 if (!time_before(jiffies, curr->mm->numa_next_scan))
3416 task_work_add(curr, work, TWA_RESUME);
3420 static void update_scan_period(struct task_struct *p, int new_cpu)
3422 int src_nid = cpu_to_node(task_cpu(p));
3423 int dst_nid = cpu_to_node(new_cpu);
3425 if (!static_branch_likely(&sched_numa_balancing))
3428 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3431 if (src_nid == dst_nid)
3435 * Allow resets if faults have been trapped before one scan
3436 * has completed. This is most likely due to a new task that
3437 * is pulled cross-node due to wakeups or load balancing.
3439 if (p->numa_scan_seq) {
3441 * Avoid scan adjustments if moving to the preferred
3442 * node or if the task was not previously running on
3443 * the preferred node.
3445 if (dst_nid == p->numa_preferred_nid ||
3446 (p->numa_preferred_nid != NUMA_NO_NODE &&
3447 src_nid != p->numa_preferred_nid))
3451 p->numa_scan_period = task_scan_start(p);
3455 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3459 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3463 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3467 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3471 #endif /* CONFIG_NUMA_BALANCING */
3474 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3476 update_load_add(&cfs_rq->load, se->load.weight);
3478 if (entity_is_task(se)) {
3479 struct rq *rq = rq_of(cfs_rq);
3481 account_numa_enqueue(rq, task_of(se));
3482 list_add(&se->group_node, &rq->cfs_tasks);
3485 cfs_rq->nr_running++;
3487 cfs_rq->idle_nr_running++;
3491 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3493 update_load_sub(&cfs_rq->load, se->load.weight);
3495 if (entity_is_task(se)) {
3496 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3497 list_del_init(&se->group_node);
3500 cfs_rq->nr_running--;
3502 cfs_rq->idle_nr_running--;
3506 * Signed add and clamp on underflow.
3508 * Explicitly do a load-store to ensure the intermediate value never hits
3509 * memory. This allows lockless observations without ever seeing the negative
3512 #define add_positive(_ptr, _val) do { \
3513 typeof(_ptr) ptr = (_ptr); \
3514 typeof(_val) val = (_val); \
3515 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3519 if (val < 0 && res > var) \
3522 WRITE_ONCE(*ptr, res); \
3526 * Unsigned subtract and clamp on underflow.
3528 * Explicitly do a load-store to ensure the intermediate value never hits
3529 * memory. This allows lockless observations without ever seeing the negative
3532 #define sub_positive(_ptr, _val) do { \
3533 typeof(_ptr) ptr = (_ptr); \
3534 typeof(*ptr) val = (_val); \
3535 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3539 WRITE_ONCE(*ptr, res); \
3543 * Remove and clamp on negative, from a local variable.
3545 * A variant of sub_positive(), which does not use explicit load-store
3546 * and is thus optimized for local variable updates.
3548 #define lsub_positive(_ptr, _val) do { \
3549 typeof(_ptr) ptr = (_ptr); \
3550 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3555 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3557 cfs_rq->avg.load_avg += se->avg.load_avg;
3558 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3562 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3564 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3565 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3566 /* See update_cfs_rq_load_avg() */
3567 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3568 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3572 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3574 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3577 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3578 unsigned long weight)
3580 unsigned long old_weight = se->load.weight;
3583 /* commit outstanding execution time */
3584 if (cfs_rq->curr == se)
3585 update_curr(cfs_rq);
3587 avg_vruntime_sub(cfs_rq, se);
3588 update_load_sub(&cfs_rq->load, se->load.weight);
3590 dequeue_load_avg(cfs_rq, se);
3592 update_load_set(&se->load, weight);
3596 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3597 * we need to scale se->vlag when w_i changes.
3599 se->vlag = div_s64(se->vlag * old_weight, weight);
3601 s64 deadline = se->deadline - se->vruntime;
3603 * When the weight changes, the virtual time slope changes and
3604 * we should adjust the relative virtual deadline accordingly.
3606 deadline = div_s64(deadline * old_weight, weight);
3607 se->deadline = se->vruntime + deadline;
3612 u32 divider = get_pelt_divider(&se->avg);
3614 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3618 enqueue_load_avg(cfs_rq, se);
3620 update_load_add(&cfs_rq->load, se->load.weight);
3621 if (cfs_rq->curr != se)
3622 avg_vruntime_add(cfs_rq, se);
3626 void reweight_task(struct task_struct *p, int prio)
3628 struct sched_entity *se = &p->se;
3629 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3630 struct load_weight *load = &se->load;
3631 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3633 reweight_entity(cfs_rq, se, weight);
3634 load->inv_weight = sched_prio_to_wmult[prio];
3637 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3639 #ifdef CONFIG_FAIR_GROUP_SCHED
3642 * All this does is approximate the hierarchical proportion which includes that
3643 * global sum we all love to hate.
3645 * That is, the weight of a group entity, is the proportional share of the
3646 * group weight based on the group runqueue weights. That is:
3648 * tg->weight * grq->load.weight
3649 * ge->load.weight = ----------------------------- (1)
3650 * \Sum grq->load.weight
3652 * Now, because computing that sum is prohibitively expensive to compute (been
3653 * there, done that) we approximate it with this average stuff. The average
3654 * moves slower and therefore the approximation is cheaper and more stable.
3656 * So instead of the above, we substitute:
3658 * grq->load.weight -> grq->avg.load_avg (2)
3660 * which yields the following:
3662 * tg->weight * grq->avg.load_avg
3663 * ge->load.weight = ------------------------------ (3)
3666 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3668 * That is shares_avg, and it is right (given the approximation (2)).
3670 * The problem with it is that because the average is slow -- it was designed
3671 * to be exactly that of course -- this leads to transients in boundary
3672 * conditions. In specific, the case where the group was idle and we start the
3673 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3674 * yielding bad latency etc..
3676 * Now, in that special case (1) reduces to:
3678 * tg->weight * grq->load.weight
3679 * ge->load.weight = ----------------------------- = tg->weight (4)
3682 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3684 * So what we do is modify our approximation (3) to approach (4) in the (near)
3689 * tg->weight * grq->load.weight
3690 * --------------------------------------------------- (5)
3691 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3693 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3694 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3697 * tg->weight * grq->load.weight
3698 * ge->load.weight = ----------------------------- (6)
3703 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3704 * max(grq->load.weight, grq->avg.load_avg)
3706 * And that is shares_weight and is icky. In the (near) UP case it approaches
3707 * (4) while in the normal case it approaches (3). It consistently
3708 * overestimates the ge->load.weight and therefore:
3710 * \Sum ge->load.weight >= tg->weight
3714 static long calc_group_shares(struct cfs_rq *cfs_rq)
3716 long tg_weight, tg_shares, load, shares;
3717 struct task_group *tg = cfs_rq->tg;
3719 tg_shares = READ_ONCE(tg->shares);
3721 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3723 tg_weight = atomic_long_read(&tg->load_avg);
3725 /* Ensure tg_weight >= load */
3726 tg_weight -= cfs_rq->tg_load_avg_contrib;
3729 shares = (tg_shares * load);
3731 shares /= tg_weight;
3734 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3735 * of a group with small tg->shares value. It is a floor value which is
3736 * assigned as a minimum load.weight to the sched_entity representing
3737 * the group on a CPU.
3739 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3740 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3741 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3742 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3745 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3747 #endif /* CONFIG_SMP */
3750 * Recomputes the group entity based on the current state of its group
3753 static void update_cfs_group(struct sched_entity *se)
3755 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3761 if (throttled_hierarchy(gcfs_rq))
3765 shares = READ_ONCE(gcfs_rq->tg->shares);
3767 if (likely(se->load.weight == shares))
3770 shares = calc_group_shares(gcfs_rq);
3773 reweight_entity(cfs_rq_of(se), se, shares);
3776 #else /* CONFIG_FAIR_GROUP_SCHED */
3777 static inline void update_cfs_group(struct sched_entity *se)
3780 #endif /* CONFIG_FAIR_GROUP_SCHED */
3782 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3784 struct rq *rq = rq_of(cfs_rq);
3786 if (&rq->cfs == cfs_rq) {
3788 * There are a few boundary cases this might miss but it should
3789 * get called often enough that that should (hopefully) not be
3792 * It will not get called when we go idle, because the idle
3793 * thread is a different class (!fair), nor will the utilization
3794 * number include things like RT tasks.
3796 * As is, the util number is not freq-invariant (we'd have to
3797 * implement arch_scale_freq_capacity() for that).
3799 * See cpu_util_cfs().
3801 cpufreq_update_util(rq, flags);
3806 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3814 if (sa->runnable_sum)
3818 * _avg must be null when _sum are null because _avg = _sum / divider
3819 * Make sure that rounding and/or propagation of PELT values never
3822 SCHED_WARN_ON(sa->load_avg ||
3829 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3831 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3832 cfs_rq->last_update_time_copy);
3834 #ifdef CONFIG_FAIR_GROUP_SCHED
3836 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
3837 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
3838 * bottom-up, we only have to test whether the cfs_rq before us on the list
3840 * If cfs_rq is not on the list, test whether a child needs its to be added to
3841 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
3843 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
3845 struct cfs_rq *prev_cfs_rq;
3846 struct list_head *prev;
3848 if (cfs_rq->on_list) {
3849 prev = cfs_rq->leaf_cfs_rq_list.prev;
3851 struct rq *rq = rq_of(cfs_rq);
3853 prev = rq->tmp_alone_branch;
3856 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
3858 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
3861 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
3863 if (cfs_rq->load.weight)
3866 if (!load_avg_is_decayed(&cfs_rq->avg))
3869 if (child_cfs_rq_on_list(cfs_rq))
3876 * update_tg_load_avg - update the tg's load avg
3877 * @cfs_rq: the cfs_rq whose avg changed
3879 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3880 * However, because tg->load_avg is a global value there are performance
3883 * In order to avoid having to look at the other cfs_rq's, we use a
3884 * differential update where we store the last value we propagated. This in
3885 * turn allows skipping updates if the differential is 'small'.
3887 * Updating tg's load_avg is necessary before update_cfs_share().
3889 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
3891 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3894 * No need to update load_avg for root_task_group as it is not used.
3896 if (cfs_rq->tg == &root_task_group)
3899 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3900 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3901 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3906 * Called within set_task_rq() right before setting a task's CPU. The
3907 * caller only guarantees p->pi_lock is held; no other assumptions,
3908 * including the state of rq->lock, should be made.
3910 void set_task_rq_fair(struct sched_entity *se,
3911 struct cfs_rq *prev, struct cfs_rq *next)
3913 u64 p_last_update_time;
3914 u64 n_last_update_time;
3916 if (!sched_feat(ATTACH_AGE_LOAD))
3920 * We are supposed to update the task to "current" time, then its up to
3921 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3922 * getting what current time is, so simply throw away the out-of-date
3923 * time. This will result in the wakee task is less decayed, but giving
3924 * the wakee more load sounds not bad.
3926 if (!(se->avg.last_update_time && prev))
3929 p_last_update_time = cfs_rq_last_update_time(prev);
3930 n_last_update_time = cfs_rq_last_update_time(next);
3932 __update_load_avg_blocked_se(p_last_update_time, se);
3933 se->avg.last_update_time = n_last_update_time;
3937 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3938 * propagate its contribution. The key to this propagation is the invariant
3939 * that for each group:
3941 * ge->avg == grq->avg (1)
3943 * _IFF_ we look at the pure running and runnable sums. Because they
3944 * represent the very same entity, just at different points in the hierarchy.
3946 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
3947 * and simply copies the running/runnable sum over (but still wrong, because
3948 * the group entity and group rq do not have their PELT windows aligned).
3950 * However, update_tg_cfs_load() is more complex. So we have:
3952 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
3954 * And since, like util, the runnable part should be directly transferable,
3955 * the following would _appear_ to be the straight forward approach:
3957 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
3959 * And per (1) we have:
3961 * ge->avg.runnable_avg == grq->avg.runnable_avg
3965 * ge->load.weight * grq->avg.load_avg
3966 * ge->avg.load_avg = ----------------------------------- (4)
3969 * Except that is wrong!
3971 * Because while for entities historical weight is not important and we
3972 * really only care about our future and therefore can consider a pure
3973 * runnable sum, runqueues can NOT do this.
3975 * We specifically want runqueues to have a load_avg that includes
3976 * historical weights. Those represent the blocked load, the load we expect
3977 * to (shortly) return to us. This only works by keeping the weights as
3978 * integral part of the sum. We therefore cannot decompose as per (3).
3980 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
3981 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
3982 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
3983 * runnable section of these tasks overlap (or not). If they were to perfectly
3984 * align the rq as a whole would be runnable 2/3 of the time. If however we
3985 * always have at least 1 runnable task, the rq as a whole is always runnable.
3987 * So we'll have to approximate.. :/
3989 * Given the constraint:
3991 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
3993 * We can construct a rule that adds runnable to a rq by assuming minimal
3996 * On removal, we'll assume each task is equally runnable; which yields:
3998 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4000 * XXX: only do this for the part of runnable > running ?
4004 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4006 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4007 u32 new_sum, divider;
4009 /* Nothing to update */
4014 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4015 * See ___update_load_avg() for details.
4017 divider = get_pelt_divider(&cfs_rq->avg);
4020 /* Set new sched_entity's utilization */
4021 se->avg.util_avg = gcfs_rq->avg.util_avg;
4022 new_sum = se->avg.util_avg * divider;
4023 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4024 se->avg.util_sum = new_sum;
4026 /* Update parent cfs_rq utilization */
4027 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4028 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4030 /* See update_cfs_rq_load_avg() */
4031 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4032 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4036 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4038 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4039 u32 new_sum, divider;
4041 /* Nothing to update */
4046 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4047 * See ___update_load_avg() for details.
4049 divider = get_pelt_divider(&cfs_rq->avg);
4051 /* Set new sched_entity's runnable */
4052 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4053 new_sum = se->avg.runnable_avg * divider;
4054 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4055 se->avg.runnable_sum = new_sum;
4057 /* Update parent cfs_rq runnable */
4058 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4059 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4060 /* See update_cfs_rq_load_avg() */
4061 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4062 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4066 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4068 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4069 unsigned long load_avg;
4077 gcfs_rq->prop_runnable_sum = 0;
4080 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4081 * See ___update_load_avg() for details.
4083 divider = get_pelt_divider(&cfs_rq->avg);
4085 if (runnable_sum >= 0) {
4087 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4088 * the CPU is saturated running == runnable.
4090 runnable_sum += se->avg.load_sum;
4091 runnable_sum = min_t(long, runnable_sum, divider);
4094 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4095 * assuming all tasks are equally runnable.
4097 if (scale_load_down(gcfs_rq->load.weight)) {
4098 load_sum = div_u64(gcfs_rq->avg.load_sum,
4099 scale_load_down(gcfs_rq->load.weight));
4102 /* But make sure to not inflate se's runnable */
4103 runnable_sum = min(se->avg.load_sum, load_sum);
4107 * runnable_sum can't be lower than running_sum
4108 * Rescale running sum to be in the same range as runnable sum
4109 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4110 * runnable_sum is in [0 : LOAD_AVG_MAX]
4112 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4113 runnable_sum = max(runnable_sum, running_sum);
4115 load_sum = se_weight(se) * runnable_sum;
4116 load_avg = div_u64(load_sum, divider);
4118 delta_avg = load_avg - se->avg.load_avg;
4122 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4124 se->avg.load_sum = runnable_sum;
4125 se->avg.load_avg = load_avg;
4126 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4127 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4128 /* See update_cfs_rq_load_avg() */
4129 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4130 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4133 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4135 cfs_rq->propagate = 1;
4136 cfs_rq->prop_runnable_sum += runnable_sum;
4139 /* Update task and its cfs_rq load average */
4140 static inline int propagate_entity_load_avg(struct sched_entity *se)
4142 struct cfs_rq *cfs_rq, *gcfs_rq;
4144 if (entity_is_task(se))
4147 gcfs_rq = group_cfs_rq(se);
4148 if (!gcfs_rq->propagate)
4151 gcfs_rq->propagate = 0;
4153 cfs_rq = cfs_rq_of(se);
4155 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4157 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4158 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4159 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4161 trace_pelt_cfs_tp(cfs_rq);
4162 trace_pelt_se_tp(se);
4168 * Check if we need to update the load and the utilization of a blocked
4171 static inline bool skip_blocked_update(struct sched_entity *se)
4173 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4176 * If sched_entity still have not zero load or utilization, we have to
4179 if (se->avg.load_avg || se->avg.util_avg)
4183 * If there is a pending propagation, we have to update the load and
4184 * the utilization of the sched_entity:
4186 if (gcfs_rq->propagate)
4190 * Otherwise, the load and the utilization of the sched_entity is
4191 * already zero and there is no pending propagation, so it will be a
4192 * waste of time to try to decay it:
4197 #else /* CONFIG_FAIR_GROUP_SCHED */
4199 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4201 static inline int propagate_entity_load_avg(struct sched_entity *se)
4206 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4208 #endif /* CONFIG_FAIR_GROUP_SCHED */
4210 #ifdef CONFIG_NO_HZ_COMMON
4211 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4213 u64 throttled = 0, now, lut;
4214 struct cfs_rq *cfs_rq;
4218 if (load_avg_is_decayed(&se->avg))
4221 cfs_rq = cfs_rq_of(se);
4225 is_idle = is_idle_task(rcu_dereference(rq->curr));
4229 * The lag estimation comes with a cost we don't want to pay all the
4230 * time. Hence, limiting to the case where the source CPU is idle and
4231 * we know we are at the greatest risk to have an outdated clock.
4237 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4239 * last_update_time (the cfs_rq's last_update_time)
4240 * = cfs_rq_clock_pelt()@cfs_rq_idle
4241 * = rq_clock_pelt()@cfs_rq_idle
4242 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4244 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4245 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4247 * rq_idle_lag (delta between now and rq's update)
4248 * = sched_clock_cpu() - rq_clock()@rq_idle
4250 * We can then write:
4252 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4253 * sched_clock_cpu() - rq_clock()@rq_idle
4255 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4256 * rq_clock()@rq_idle is rq->clock_idle
4257 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4258 * is cfs_rq->throttled_pelt_idle
4261 #ifdef CONFIG_CFS_BANDWIDTH
4262 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4263 /* The clock has been stopped for throttling */
4264 if (throttled == U64_MAX)
4267 now = u64_u32_load(rq->clock_pelt_idle);
4269 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4270 * is observed the old clock_pelt_idle value and the new clock_idle,
4271 * which lead to an underestimation. The opposite would lead to an
4275 lut = cfs_rq_last_update_time(cfs_rq);
4280 * cfs_rq->avg.last_update_time is more recent than our
4281 * estimation, let's use it.
4285 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4287 __update_load_avg_blocked_se(now, se);
4290 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4294 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4295 * @now: current time, as per cfs_rq_clock_pelt()
4296 * @cfs_rq: cfs_rq to update
4298 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4299 * avg. The immediate corollary is that all (fair) tasks must be attached.
4301 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4303 * Return: true if the load decayed or we removed load.
4305 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4306 * call update_tg_load_avg() when this function returns true.
4309 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4311 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4312 struct sched_avg *sa = &cfs_rq->avg;
4315 if (cfs_rq->removed.nr) {
4317 u32 divider = get_pelt_divider(&cfs_rq->avg);
4319 raw_spin_lock(&cfs_rq->removed.lock);
4320 swap(cfs_rq->removed.util_avg, removed_util);
4321 swap(cfs_rq->removed.load_avg, removed_load);
4322 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4323 cfs_rq->removed.nr = 0;
4324 raw_spin_unlock(&cfs_rq->removed.lock);
4327 sub_positive(&sa->load_avg, r);
4328 sub_positive(&sa->load_sum, r * divider);
4329 /* See sa->util_sum below */
4330 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4333 sub_positive(&sa->util_avg, r);
4334 sub_positive(&sa->util_sum, r * divider);
4336 * Because of rounding, se->util_sum might ends up being +1 more than
4337 * cfs->util_sum. Although this is not a problem by itself, detaching
4338 * a lot of tasks with the rounding problem between 2 updates of
4339 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4340 * cfs_util_avg is not.
4341 * Check that util_sum is still above its lower bound for the new
4342 * util_avg. Given that period_contrib might have moved since the last
4343 * sync, we are only sure that util_sum must be above or equal to
4344 * util_avg * minimum possible divider
4346 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4348 r = removed_runnable;
4349 sub_positive(&sa->runnable_avg, r);
4350 sub_positive(&sa->runnable_sum, r * divider);
4351 /* See sa->util_sum above */
4352 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4353 sa->runnable_avg * PELT_MIN_DIVIDER);
4356 * removed_runnable is the unweighted version of removed_load so we
4357 * can use it to estimate removed_load_sum.
4359 add_tg_cfs_propagate(cfs_rq,
4360 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4365 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4366 u64_u32_store_copy(sa->last_update_time,
4367 cfs_rq->last_update_time_copy,
4368 sa->last_update_time);
4373 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4374 * @cfs_rq: cfs_rq to attach to
4375 * @se: sched_entity to attach
4377 * Must call update_cfs_rq_load_avg() before this, since we rely on
4378 * cfs_rq->avg.last_update_time being current.
4380 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4383 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4384 * See ___update_load_avg() for details.
4386 u32 divider = get_pelt_divider(&cfs_rq->avg);
4389 * When we attach the @se to the @cfs_rq, we must align the decay
4390 * window because without that, really weird and wonderful things can
4395 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4396 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4399 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4400 * period_contrib. This isn't strictly correct, but since we're
4401 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4404 se->avg.util_sum = se->avg.util_avg * divider;
4406 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4408 se->avg.load_sum = se->avg.load_avg * divider;
4409 if (se_weight(se) < se->avg.load_sum)
4410 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4412 se->avg.load_sum = 1;
4414 enqueue_load_avg(cfs_rq, se);
4415 cfs_rq->avg.util_avg += se->avg.util_avg;
4416 cfs_rq->avg.util_sum += se->avg.util_sum;
4417 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4418 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4420 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4422 cfs_rq_util_change(cfs_rq, 0);
4424 trace_pelt_cfs_tp(cfs_rq);
4428 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4429 * @cfs_rq: cfs_rq to detach from
4430 * @se: sched_entity to detach
4432 * Must call update_cfs_rq_load_avg() before this, since we rely on
4433 * cfs_rq->avg.last_update_time being current.
4435 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4437 dequeue_load_avg(cfs_rq, se);
4438 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4439 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4440 /* See update_cfs_rq_load_avg() */
4441 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4442 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4444 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4445 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4446 /* See update_cfs_rq_load_avg() */
4447 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4448 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4450 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4452 cfs_rq_util_change(cfs_rq, 0);
4454 trace_pelt_cfs_tp(cfs_rq);
4458 * Optional action to be done while updating the load average
4460 #define UPDATE_TG 0x1
4461 #define SKIP_AGE_LOAD 0x2
4462 #define DO_ATTACH 0x4
4463 #define DO_DETACH 0x8
4465 /* Update task and its cfs_rq load average */
4466 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4468 u64 now = cfs_rq_clock_pelt(cfs_rq);
4472 * Track task load average for carrying it to new CPU after migrated, and
4473 * track group sched_entity load average for task_h_load calc in migration
4475 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4476 __update_load_avg_se(now, cfs_rq, se);
4478 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4479 decayed |= propagate_entity_load_avg(se);
4481 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4484 * DO_ATTACH means we're here from enqueue_entity().
4485 * !last_update_time means we've passed through
4486 * migrate_task_rq_fair() indicating we migrated.
4488 * IOW we're enqueueing a task on a new CPU.
4490 attach_entity_load_avg(cfs_rq, se);
4491 update_tg_load_avg(cfs_rq);
4493 } else if (flags & DO_DETACH) {
4495 * DO_DETACH means we're here from dequeue_entity()
4496 * and we are migrating task out of the CPU.
4498 detach_entity_load_avg(cfs_rq, se);
4499 update_tg_load_avg(cfs_rq);
4500 } else if (decayed) {
4501 cfs_rq_util_change(cfs_rq, 0);
4503 if (flags & UPDATE_TG)
4504 update_tg_load_avg(cfs_rq);
4509 * Synchronize entity load avg of dequeued entity without locking
4512 static void sync_entity_load_avg(struct sched_entity *se)
4514 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4515 u64 last_update_time;
4517 last_update_time = cfs_rq_last_update_time(cfs_rq);
4518 __update_load_avg_blocked_se(last_update_time, se);
4522 * Task first catches up with cfs_rq, and then subtract
4523 * itself from the cfs_rq (task must be off the queue now).
4525 static void remove_entity_load_avg(struct sched_entity *se)
4527 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4528 unsigned long flags;
4531 * tasks cannot exit without having gone through wake_up_new_task() ->
4532 * enqueue_task_fair() which will have added things to the cfs_rq,
4533 * so we can remove unconditionally.
4536 sync_entity_load_avg(se);
4538 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4539 ++cfs_rq->removed.nr;
4540 cfs_rq->removed.util_avg += se->avg.util_avg;
4541 cfs_rq->removed.load_avg += se->avg.load_avg;
4542 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4543 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4546 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4548 return cfs_rq->avg.runnable_avg;
4551 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4553 return cfs_rq->avg.load_avg;
4556 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4558 static inline unsigned long task_util(struct task_struct *p)
4560 return READ_ONCE(p->se.avg.util_avg);
4563 static inline unsigned long _task_util_est(struct task_struct *p)
4565 struct util_est ue = READ_ONCE(p->se.avg.util_est);
4567 return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4570 static inline unsigned long task_util_est(struct task_struct *p)
4572 return max(task_util(p), _task_util_est(p));
4575 #ifdef CONFIG_UCLAMP_TASK
4576 static inline unsigned long uclamp_task_util(struct task_struct *p,
4577 unsigned long uclamp_min,
4578 unsigned long uclamp_max)
4580 return clamp(task_util_est(p), uclamp_min, uclamp_max);
4583 static inline unsigned long uclamp_task_util(struct task_struct *p,
4584 unsigned long uclamp_min,
4585 unsigned long uclamp_max)
4587 return task_util_est(p);
4591 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4592 struct task_struct *p)
4594 unsigned int enqueued;
4596 if (!sched_feat(UTIL_EST))
4599 /* Update root cfs_rq's estimated utilization */
4600 enqueued = cfs_rq->avg.util_est.enqueued;
4601 enqueued += _task_util_est(p);
4602 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4604 trace_sched_util_est_cfs_tp(cfs_rq);
4607 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4608 struct task_struct *p)
4610 unsigned int enqueued;
4612 if (!sched_feat(UTIL_EST))
4615 /* Update root cfs_rq's estimated utilization */
4616 enqueued = cfs_rq->avg.util_est.enqueued;
4617 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4618 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4620 trace_sched_util_est_cfs_tp(cfs_rq);
4623 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4626 * Check if a (signed) value is within a specified (unsigned) margin,
4627 * based on the observation that:
4629 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4631 * NOTE: this only works when value + margin < INT_MAX.
4633 static inline bool within_margin(int value, int margin)
4635 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4638 static inline void util_est_update(struct cfs_rq *cfs_rq,
4639 struct task_struct *p,
4642 long last_ewma_diff, last_enqueued_diff;
4645 if (!sched_feat(UTIL_EST))
4649 * Skip update of task's estimated utilization when the task has not
4650 * yet completed an activation, e.g. being migrated.
4656 * If the PELT values haven't changed since enqueue time,
4657 * skip the util_est update.
4659 ue = p->se.avg.util_est;
4660 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4663 last_enqueued_diff = ue.enqueued;
4666 * Reset EWMA on utilization increases, the moving average is used only
4667 * to smooth utilization decreases.
4669 ue.enqueued = task_util(p);
4670 if (sched_feat(UTIL_EST_FASTUP)) {
4671 if (ue.ewma < ue.enqueued) {
4672 ue.ewma = ue.enqueued;
4678 * Skip update of task's estimated utilization when its members are
4679 * already ~1% close to its last activation value.
4681 last_ewma_diff = ue.enqueued - ue.ewma;
4682 last_enqueued_diff -= ue.enqueued;
4683 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4684 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4691 * To avoid overestimation of actual task utilization, skip updates if
4692 * we cannot grant there is idle time in this CPU.
4694 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4698 * Update Task's estimated utilization
4700 * When *p completes an activation we can consolidate another sample
4701 * of the task size. This is done by storing the current PELT value
4702 * as ue.enqueued and by using this value to update the Exponential
4703 * Weighted Moving Average (EWMA):
4705 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4706 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4707 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4708 * = w * ( last_ewma_diff ) + ewma(t-1)
4709 * = w * (last_ewma_diff + ewma(t-1) / w)
4711 * Where 'w' is the weight of new samples, which is configured to be
4712 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4714 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4715 ue.ewma += last_ewma_diff;
4716 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4718 ue.enqueued |= UTIL_AVG_UNCHANGED;
4719 WRITE_ONCE(p->se.avg.util_est, ue);
4721 trace_sched_util_est_se_tp(&p->se);
4724 static inline int util_fits_cpu(unsigned long util,
4725 unsigned long uclamp_min,
4726 unsigned long uclamp_max,
4729 unsigned long capacity_orig, capacity_orig_thermal;
4730 unsigned long capacity = capacity_of(cpu);
4731 bool fits, uclamp_max_fits;
4734 * Check if the real util fits without any uclamp boost/cap applied.
4736 fits = fits_capacity(util, capacity);
4738 if (!uclamp_is_used())
4742 * We must use capacity_orig_of() for comparing against uclamp_min and
4743 * uclamp_max. We only care about capacity pressure (by using
4744 * capacity_of()) for comparing against the real util.
4746 * If a task is boosted to 1024 for example, we don't want a tiny
4747 * pressure to skew the check whether it fits a CPU or not.
4749 * Similarly if a task is capped to capacity_orig_of(little_cpu), it
4750 * should fit a little cpu even if there's some pressure.
4752 * Only exception is for thermal pressure since it has a direct impact
4753 * on available OPP of the system.
4755 * We honour it for uclamp_min only as a drop in performance level
4756 * could result in not getting the requested minimum performance level.
4758 * For uclamp_max, we can tolerate a drop in performance level as the
4759 * goal is to cap the task. So it's okay if it's getting less.
4761 capacity_orig = capacity_orig_of(cpu);
4762 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4765 * We want to force a task to fit a cpu as implied by uclamp_max.
4766 * But we do have some corner cases to cater for..
4772 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4775 * | | | | | | | (util somewhere in this region)
4778 * +----------------------------------------
4781 * In the above example if a task is capped to a specific performance
4782 * point, y, then when:
4784 * * util = 80% of x then it does not fit on cpu0 and should migrate
4786 * * util = 80% of y then it is forced to fit on cpu1 to honour
4787 * uclamp_max request.
4789 * which is what we're enforcing here. A task always fits if
4790 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4791 * the normal upmigration rules should withhold still.
4793 * Only exception is when we are on max capacity, then we need to be
4794 * careful not to block overutilized state. This is so because:
4796 * 1. There's no concept of capping at max_capacity! We can't go
4797 * beyond this performance level anyway.
4798 * 2. The system is being saturated when we're operating near
4799 * max capacity, it doesn't make sense to block overutilized.
4801 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4802 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4803 fits = fits || uclamp_max_fits;
4808 * | ___ (region a, capped, util >= uclamp_max)
4810 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4812 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
4813 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4815 * | | | | | | | (region c, boosted, util < uclamp_min)
4816 * +----------------------------------------
4819 * a) If util > uclamp_max, then we're capped, we don't care about
4820 * actual fitness value here. We only care if uclamp_max fits
4821 * capacity without taking margin/pressure into account.
4822 * See comment above.
4824 * b) If uclamp_min <= util <= uclamp_max, then the normal
4825 * fits_capacity() rules apply. Except we need to ensure that we
4826 * enforce we remain within uclamp_max, see comment above.
4828 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
4829 * need to take into account the boosted value fits the CPU without
4830 * taking margin/pressure into account.
4832 * Cases (a) and (b) are handled in the 'fits' variable already. We
4833 * just need to consider an extra check for case (c) after ensuring we
4834 * handle the case uclamp_min > uclamp_max.
4836 uclamp_min = min(uclamp_min, uclamp_max);
4837 if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
4843 static inline int task_fits_cpu(struct task_struct *p, int cpu)
4845 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
4846 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
4847 unsigned long util = task_util_est(p);
4849 * Return true only if the cpu fully fits the task requirements, which
4850 * include the utilization but also the performance hints.
4852 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
4855 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4857 if (!sched_asym_cpucap_active())
4860 if (!p || p->nr_cpus_allowed == 1) {
4861 rq->misfit_task_load = 0;
4865 if (task_fits_cpu(p, cpu_of(rq))) {
4866 rq->misfit_task_load = 0;
4871 * Make sure that misfit_task_load will not be null even if
4872 * task_h_load() returns 0.
4874 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4877 #else /* CONFIG_SMP */
4879 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4884 #define UPDATE_TG 0x0
4885 #define SKIP_AGE_LOAD 0x0
4886 #define DO_ATTACH 0x0
4887 #define DO_DETACH 0x0
4889 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4891 cfs_rq_util_change(cfs_rq, 0);
4894 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4897 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4899 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4901 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4907 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4910 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4913 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4915 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4917 #endif /* CONFIG_SMP */
4920 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4922 u64 vslice = calc_delta_fair(se->slice, se);
4923 u64 vruntime = avg_vruntime(cfs_rq);
4927 * Due to how V is constructed as the weighted average of entities,
4928 * adding tasks with positive lag, or removing tasks with negative lag
4929 * will move 'time' backwards, this can screw around with the lag of
4932 * EEVDF: placement strategy #1 / #2
4934 if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
4935 struct sched_entity *curr = cfs_rq->curr;
4941 * If we want to place a task and preserve lag, we have to
4942 * consider the effect of the new entity on the weighted
4943 * average and compensate for this, otherwise lag can quickly
4946 * Lag is defined as:
4948 * lag_i = S - s_i = w_i * (V - v_i)
4950 * To avoid the 'w_i' term all over the place, we only track
4953 * vl_i = V - v_i <=> v_i = V - vl_i
4955 * And we take V to be the weighted average of all v:
4957 * V = (\Sum w_j*v_j) / W
4959 * Where W is: \Sum w_j
4961 * Then, the weighted average after adding an entity with lag
4964 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
4965 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
4966 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
4967 * = (V*(W + w_i) - w_i*l) / (W + w_i)
4968 * = V - w_i*vl_i / (W + w_i)
4970 * And the actual lag after adding an entity with vl_i is:
4973 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
4974 * = vl_i - w_i*vl_i / (W + w_i)
4976 * Which is strictly less than vl_i. So in order to preserve lag
4977 * we should inflate the lag before placement such that the
4978 * effective lag after placement comes out right.
4980 * As such, invert the above relation for vl'_i to get the vl_i
4981 * we need to use such that the lag after placement is the lag
4982 * we computed before dequeue.
4984 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
4985 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
4987 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
4990 * vl_i = (W + w_i)*vl'_i / W
4992 load = cfs_rq->avg_load;
4993 if (curr && curr->on_rq)
4994 load += scale_load_down(curr->load.weight);
4996 lag *= load + scale_load_down(se->load.weight);
4997 if (WARN_ON_ONCE(!load))
4999 lag = div_s64(lag, load);
5002 se->vruntime = vruntime - lag;
5005 * When joining the competition; the exisiting tasks will be,
5006 * on average, halfway through their slice, as such start tasks
5007 * off with half a slice to ease into the competition.
5009 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5013 * EEVDF: vd_i = ve_i + r_i/w_i
5015 se->deadline = se->vruntime + vslice;
5018 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5019 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5021 static inline bool cfs_bandwidth_used(void);
5024 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5026 bool curr = cfs_rq->curr == se;
5029 * If we're the current task, we must renormalise before calling
5033 place_entity(cfs_rq, se, flags);
5035 update_curr(cfs_rq);
5038 * When enqueuing a sched_entity, we must:
5039 * - Update loads to have both entity and cfs_rq synced with now.
5040 * - For group_entity, update its runnable_weight to reflect the new
5041 * h_nr_running of its group cfs_rq.
5042 * - For group_entity, update its weight to reflect the new share of
5044 * - Add its new weight to cfs_rq->load.weight
5046 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5047 se_update_runnable(se);
5049 * XXX update_load_avg() above will have attached us to the pelt sum;
5050 * but update_cfs_group() here will re-adjust the weight and have to
5051 * undo/redo all that. Seems wasteful.
5053 update_cfs_group(se);
5056 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5057 * we can place the entity.
5060 place_entity(cfs_rq, se, flags);
5062 account_entity_enqueue(cfs_rq, se);
5064 /* Entity has migrated, no longer consider this task hot */
5065 if (flags & ENQUEUE_MIGRATED)
5068 check_schedstat_required();
5069 update_stats_enqueue_fair(cfs_rq, se, flags);
5071 __enqueue_entity(cfs_rq, se);
5074 if (cfs_rq->nr_running == 1) {
5075 check_enqueue_throttle(cfs_rq);
5076 if (!throttled_hierarchy(cfs_rq)) {
5077 list_add_leaf_cfs_rq(cfs_rq);
5079 #ifdef CONFIG_CFS_BANDWIDTH
5080 struct rq *rq = rq_of(cfs_rq);
5082 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5083 cfs_rq->throttled_clock = rq_clock(rq);
5084 if (!cfs_rq->throttled_clock_self)
5085 cfs_rq->throttled_clock_self = rq_clock(rq);
5091 static void __clear_buddies_next(struct sched_entity *se)
5093 for_each_sched_entity(se) {
5094 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5095 if (cfs_rq->next != se)
5098 cfs_rq->next = NULL;
5102 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5104 if (cfs_rq->next == se)
5105 __clear_buddies_next(se);
5108 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5111 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5113 int action = UPDATE_TG;
5115 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5116 action |= DO_DETACH;
5119 * Update run-time statistics of the 'current'.
5121 update_curr(cfs_rq);
5124 * When dequeuing a sched_entity, we must:
5125 * - Update loads to have both entity and cfs_rq synced with now.
5126 * - For group_entity, update its runnable_weight to reflect the new
5127 * h_nr_running of its group cfs_rq.
5128 * - Subtract its previous weight from cfs_rq->load.weight.
5129 * - For group entity, update its weight to reflect the new share
5130 * of its group cfs_rq.
5132 update_load_avg(cfs_rq, se, action);
5133 se_update_runnable(se);
5135 update_stats_dequeue_fair(cfs_rq, se, flags);
5137 clear_buddies(cfs_rq, se);
5139 update_entity_lag(cfs_rq, se);
5140 if (se != cfs_rq->curr)
5141 __dequeue_entity(cfs_rq, se);
5143 account_entity_dequeue(cfs_rq, se);
5145 /* return excess runtime on last dequeue */
5146 return_cfs_rq_runtime(cfs_rq);
5148 update_cfs_group(se);
5151 * Now advance min_vruntime if @se was the entity holding it back,
5152 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5153 * put back on, and if we advance min_vruntime, we'll be placed back
5154 * further than we started -- ie. we'll be penalized.
5156 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5157 update_min_vruntime(cfs_rq);
5159 if (cfs_rq->nr_running == 0)
5160 update_idle_cfs_rq_clock_pelt(cfs_rq);
5164 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5166 clear_buddies(cfs_rq, se);
5168 /* 'current' is not kept within the tree. */
5171 * Any task has to be enqueued before it get to execute on
5172 * a CPU. So account for the time it spent waiting on the
5175 update_stats_wait_end_fair(cfs_rq, se);
5176 __dequeue_entity(cfs_rq, se);
5177 update_load_avg(cfs_rq, se, UPDATE_TG);
5179 * HACK, stash a copy of deadline at the point of pick in vlag,
5180 * which isn't used until dequeue.
5182 se->vlag = se->deadline;
5185 update_stats_curr_start(cfs_rq, se);
5189 * Track our maximum slice length, if the CPU's load is at
5190 * least twice that of our own weight (i.e. dont track it
5191 * when there are only lesser-weight tasks around):
5193 if (schedstat_enabled() &&
5194 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5195 struct sched_statistics *stats;
5197 stats = __schedstats_from_se(se);
5198 __schedstat_set(stats->slice_max,
5199 max((u64)stats->slice_max,
5200 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5203 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5207 * Pick the next process, keeping these things in mind, in this order:
5208 * 1) keep things fair between processes/task groups
5209 * 2) pick the "next" process, since someone really wants that to run
5210 * 3) pick the "last" process, for cache locality
5211 * 4) do not run the "skip" process, if something else is available
5213 static struct sched_entity *
5214 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5217 * Enabling NEXT_BUDDY will affect latency but not fairness.
5219 if (sched_feat(NEXT_BUDDY) &&
5220 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5221 return cfs_rq->next;
5223 return pick_eevdf(cfs_rq);
5226 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5228 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5231 * If still on the runqueue then deactivate_task()
5232 * was not called and update_curr() has to be done:
5235 update_curr(cfs_rq);
5237 /* throttle cfs_rqs exceeding runtime */
5238 check_cfs_rq_runtime(cfs_rq);
5241 update_stats_wait_start_fair(cfs_rq, prev);
5242 /* Put 'current' back into the tree. */
5243 __enqueue_entity(cfs_rq, prev);
5244 /* in !on_rq case, update occurred at dequeue */
5245 update_load_avg(cfs_rq, prev, 0);
5247 cfs_rq->curr = NULL;
5251 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5254 * Update run-time statistics of the 'current'.
5256 update_curr(cfs_rq);
5259 * Ensure that runnable average is periodically updated.
5261 update_load_avg(cfs_rq, curr, UPDATE_TG);
5262 update_cfs_group(curr);
5264 #ifdef CONFIG_SCHED_HRTICK
5266 * queued ticks are scheduled to match the slice, so don't bother
5267 * validating it and just reschedule.
5270 resched_curr(rq_of(cfs_rq));
5274 * don't let the period tick interfere with the hrtick preemption
5276 if (!sched_feat(DOUBLE_TICK) &&
5277 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5283 /**************************************************
5284 * CFS bandwidth control machinery
5287 #ifdef CONFIG_CFS_BANDWIDTH
5289 #ifdef CONFIG_JUMP_LABEL
5290 static struct static_key __cfs_bandwidth_used;
5292 static inline bool cfs_bandwidth_used(void)
5294 return static_key_false(&__cfs_bandwidth_used);
5297 void cfs_bandwidth_usage_inc(void)
5299 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5302 void cfs_bandwidth_usage_dec(void)
5304 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5306 #else /* CONFIG_JUMP_LABEL */
5307 static bool cfs_bandwidth_used(void)
5312 void cfs_bandwidth_usage_inc(void) {}
5313 void cfs_bandwidth_usage_dec(void) {}
5314 #endif /* CONFIG_JUMP_LABEL */
5317 * default period for cfs group bandwidth.
5318 * default: 0.1s, units: nanoseconds
5320 static inline u64 default_cfs_period(void)
5322 return 100000000ULL;
5325 static inline u64 sched_cfs_bandwidth_slice(void)
5327 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5331 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5332 * directly instead of rq->clock to avoid adding additional synchronization
5335 * requires cfs_b->lock
5337 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5341 if (unlikely(cfs_b->quota == RUNTIME_INF))
5344 cfs_b->runtime += cfs_b->quota;
5345 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5347 cfs_b->burst_time += runtime;
5351 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5352 cfs_b->runtime_snap = cfs_b->runtime;
5355 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5357 return &tg->cfs_bandwidth;
5360 /* returns 0 on failure to allocate runtime */
5361 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5362 struct cfs_rq *cfs_rq, u64 target_runtime)
5364 u64 min_amount, amount = 0;
5366 lockdep_assert_held(&cfs_b->lock);
5368 /* note: this is a positive sum as runtime_remaining <= 0 */
5369 min_amount = target_runtime - cfs_rq->runtime_remaining;
5371 if (cfs_b->quota == RUNTIME_INF)
5372 amount = min_amount;
5374 start_cfs_bandwidth(cfs_b);
5376 if (cfs_b->runtime > 0) {
5377 amount = min(cfs_b->runtime, min_amount);
5378 cfs_b->runtime -= amount;
5383 cfs_rq->runtime_remaining += amount;
5385 return cfs_rq->runtime_remaining > 0;
5388 /* returns 0 on failure to allocate runtime */
5389 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5391 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5394 raw_spin_lock(&cfs_b->lock);
5395 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5396 raw_spin_unlock(&cfs_b->lock);
5401 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5403 /* dock delta_exec before expiring quota (as it could span periods) */
5404 cfs_rq->runtime_remaining -= delta_exec;
5406 if (likely(cfs_rq->runtime_remaining > 0))
5409 if (cfs_rq->throttled)
5412 * if we're unable to extend our runtime we resched so that the active
5413 * hierarchy can be throttled
5415 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5416 resched_curr(rq_of(cfs_rq));
5419 static __always_inline
5420 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5422 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5425 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5428 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5430 return cfs_bandwidth_used() && cfs_rq->throttled;
5433 /* check whether cfs_rq, or any parent, is throttled */
5434 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5436 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5440 * Ensure that neither of the group entities corresponding to src_cpu or
5441 * dest_cpu are members of a throttled hierarchy when performing group
5442 * load-balance operations.
5444 static inline int throttled_lb_pair(struct task_group *tg,
5445 int src_cpu, int dest_cpu)
5447 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5449 src_cfs_rq = tg->cfs_rq[src_cpu];
5450 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5452 return throttled_hierarchy(src_cfs_rq) ||
5453 throttled_hierarchy(dest_cfs_rq);
5456 static int tg_unthrottle_up(struct task_group *tg, void *data)
5458 struct rq *rq = data;
5459 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5461 cfs_rq->throttle_count--;
5462 if (!cfs_rq->throttle_count) {
5463 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5464 cfs_rq->throttled_clock_pelt;
5466 /* Add cfs_rq with load or one or more already running entities to the list */
5467 if (!cfs_rq_is_decayed(cfs_rq))
5468 list_add_leaf_cfs_rq(cfs_rq);
5470 if (cfs_rq->throttled_clock_self) {
5471 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5473 cfs_rq->throttled_clock_self = 0;
5475 if (SCHED_WARN_ON((s64)delta < 0))
5478 cfs_rq->throttled_clock_self_time += delta;
5485 static int tg_throttle_down(struct task_group *tg, void *data)
5487 struct rq *rq = data;
5488 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5490 /* group is entering throttled state, stop time */
5491 if (!cfs_rq->throttle_count) {
5492 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5493 list_del_leaf_cfs_rq(cfs_rq);
5495 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5496 if (cfs_rq->nr_running)
5497 cfs_rq->throttled_clock_self = rq_clock(rq);
5499 cfs_rq->throttle_count++;
5504 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5506 struct rq *rq = rq_of(cfs_rq);
5507 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5508 struct sched_entity *se;
5509 long task_delta, idle_task_delta, dequeue = 1;
5511 raw_spin_lock(&cfs_b->lock);
5512 /* This will start the period timer if necessary */
5513 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5515 * We have raced with bandwidth becoming available, and if we
5516 * actually throttled the timer might not unthrottle us for an
5517 * entire period. We additionally needed to make sure that any
5518 * subsequent check_cfs_rq_runtime calls agree not to throttle
5519 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5520 * for 1ns of runtime rather than just check cfs_b.
5524 list_add_tail_rcu(&cfs_rq->throttled_list,
5525 &cfs_b->throttled_cfs_rq);
5527 raw_spin_unlock(&cfs_b->lock);
5530 return false; /* Throttle no longer required. */
5532 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5534 /* freeze hierarchy runnable averages while throttled */
5536 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5539 task_delta = cfs_rq->h_nr_running;
5540 idle_task_delta = cfs_rq->idle_h_nr_running;
5541 for_each_sched_entity(se) {
5542 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5543 /* throttled entity or throttle-on-deactivate */
5547 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5549 if (cfs_rq_is_idle(group_cfs_rq(se)))
5550 idle_task_delta = cfs_rq->h_nr_running;
5552 qcfs_rq->h_nr_running -= task_delta;
5553 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5555 if (qcfs_rq->load.weight) {
5556 /* Avoid re-evaluating load for this entity: */
5557 se = parent_entity(se);
5562 for_each_sched_entity(se) {
5563 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5564 /* throttled entity or throttle-on-deactivate */
5568 update_load_avg(qcfs_rq, se, 0);
5569 se_update_runnable(se);
5571 if (cfs_rq_is_idle(group_cfs_rq(se)))
5572 idle_task_delta = cfs_rq->h_nr_running;
5574 qcfs_rq->h_nr_running -= task_delta;
5575 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5578 /* At this point se is NULL and we are at root level*/
5579 sub_nr_running(rq, task_delta);
5583 * Note: distribution will already see us throttled via the
5584 * throttled-list. rq->lock protects completion.
5586 cfs_rq->throttled = 1;
5587 SCHED_WARN_ON(cfs_rq->throttled_clock);
5588 if (cfs_rq->nr_running)
5589 cfs_rq->throttled_clock = rq_clock(rq);
5593 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5595 struct rq *rq = rq_of(cfs_rq);
5596 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5597 struct sched_entity *se;
5598 long task_delta, idle_task_delta;
5600 se = cfs_rq->tg->se[cpu_of(rq)];
5602 cfs_rq->throttled = 0;
5604 update_rq_clock(rq);
5606 raw_spin_lock(&cfs_b->lock);
5607 if (cfs_rq->throttled_clock) {
5608 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5609 cfs_rq->throttled_clock = 0;
5611 list_del_rcu(&cfs_rq->throttled_list);
5612 raw_spin_unlock(&cfs_b->lock);
5614 /* update hierarchical throttle state */
5615 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5617 if (!cfs_rq->load.weight) {
5618 if (!cfs_rq->on_list)
5621 * Nothing to run but something to decay (on_list)?
5622 * Complete the branch.
5624 for_each_sched_entity(se) {
5625 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5628 goto unthrottle_throttle;
5631 task_delta = cfs_rq->h_nr_running;
5632 idle_task_delta = cfs_rq->idle_h_nr_running;
5633 for_each_sched_entity(se) {
5634 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5638 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5640 if (cfs_rq_is_idle(group_cfs_rq(se)))
5641 idle_task_delta = cfs_rq->h_nr_running;
5643 qcfs_rq->h_nr_running += task_delta;
5644 qcfs_rq->idle_h_nr_running += idle_task_delta;
5646 /* end evaluation on encountering a throttled cfs_rq */
5647 if (cfs_rq_throttled(qcfs_rq))
5648 goto unthrottle_throttle;
5651 for_each_sched_entity(se) {
5652 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5654 update_load_avg(qcfs_rq, se, UPDATE_TG);
5655 se_update_runnable(se);
5657 if (cfs_rq_is_idle(group_cfs_rq(se)))
5658 idle_task_delta = cfs_rq->h_nr_running;
5660 qcfs_rq->h_nr_running += task_delta;
5661 qcfs_rq->idle_h_nr_running += idle_task_delta;
5663 /* end evaluation on encountering a throttled cfs_rq */
5664 if (cfs_rq_throttled(qcfs_rq))
5665 goto unthrottle_throttle;
5668 /* At this point se is NULL and we are at root level*/
5669 add_nr_running(rq, task_delta);
5671 unthrottle_throttle:
5672 assert_list_leaf_cfs_rq(rq);
5674 /* Determine whether we need to wake up potentially idle CPU: */
5675 if (rq->curr == rq->idle && rq->cfs.nr_running)
5680 static void __cfsb_csd_unthrottle(void *arg)
5682 struct cfs_rq *cursor, *tmp;
5683 struct rq *rq = arg;
5689 * Iterating over the list can trigger several call to
5690 * update_rq_clock() in unthrottle_cfs_rq().
5691 * Do it once and skip the potential next ones.
5693 update_rq_clock(rq);
5694 rq_clock_start_loop_update(rq);
5697 * Since we hold rq lock we're safe from concurrent manipulation of
5698 * the CSD list. However, this RCU critical section annotates the
5699 * fact that we pair with sched_free_group_rcu(), so that we cannot
5700 * race with group being freed in the window between removing it
5701 * from the list and advancing to the next entry in the list.
5705 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5706 throttled_csd_list) {
5707 list_del_init(&cursor->throttled_csd_list);
5709 if (cfs_rq_throttled(cursor))
5710 unthrottle_cfs_rq(cursor);
5715 rq_clock_stop_loop_update(rq);
5719 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5721 struct rq *rq = rq_of(cfs_rq);
5724 if (rq == this_rq()) {
5725 unthrottle_cfs_rq(cfs_rq);
5729 /* Already enqueued */
5730 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5733 first = list_empty(&rq->cfsb_csd_list);
5734 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5736 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5739 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5741 unthrottle_cfs_rq(cfs_rq);
5745 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5747 lockdep_assert_rq_held(rq_of(cfs_rq));
5749 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5750 cfs_rq->runtime_remaining <= 0))
5753 __unthrottle_cfs_rq_async(cfs_rq);
5756 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5758 struct cfs_rq *local_unthrottle = NULL;
5759 int this_cpu = smp_processor_id();
5760 u64 runtime, remaining = 1;
5761 bool throttled = false;
5762 struct cfs_rq *cfs_rq;
5767 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5776 rq_lock_irqsave(rq, &rf);
5777 if (!cfs_rq_throttled(cfs_rq))
5781 /* Already queued for async unthrottle */
5782 if (!list_empty(&cfs_rq->throttled_csd_list))
5786 /* By the above checks, this should never be true */
5787 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5789 raw_spin_lock(&cfs_b->lock);
5790 runtime = -cfs_rq->runtime_remaining + 1;
5791 if (runtime > cfs_b->runtime)
5792 runtime = cfs_b->runtime;
5793 cfs_b->runtime -= runtime;
5794 remaining = cfs_b->runtime;
5795 raw_spin_unlock(&cfs_b->lock);
5797 cfs_rq->runtime_remaining += runtime;
5799 /* we check whether we're throttled above */
5800 if (cfs_rq->runtime_remaining > 0) {
5801 if (cpu_of(rq) != this_cpu ||
5802 SCHED_WARN_ON(local_unthrottle))
5803 unthrottle_cfs_rq_async(cfs_rq);
5805 local_unthrottle = cfs_rq;
5811 rq_unlock_irqrestore(rq, &rf);
5815 if (local_unthrottle) {
5816 rq = cpu_rq(this_cpu);
5817 rq_lock_irqsave(rq, &rf);
5818 if (cfs_rq_throttled(local_unthrottle))
5819 unthrottle_cfs_rq(local_unthrottle);
5820 rq_unlock_irqrestore(rq, &rf);
5827 * Responsible for refilling a task_group's bandwidth and unthrottling its
5828 * cfs_rqs as appropriate. If there has been no activity within the last
5829 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5830 * used to track this state.
5832 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5836 /* no need to continue the timer with no bandwidth constraint */
5837 if (cfs_b->quota == RUNTIME_INF)
5838 goto out_deactivate;
5840 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5841 cfs_b->nr_periods += overrun;
5843 /* Refill extra burst quota even if cfs_b->idle */
5844 __refill_cfs_bandwidth_runtime(cfs_b);
5847 * idle depends on !throttled (for the case of a large deficit), and if
5848 * we're going inactive then everything else can be deferred
5850 if (cfs_b->idle && !throttled)
5851 goto out_deactivate;
5854 /* mark as potentially idle for the upcoming period */
5859 /* account preceding periods in which throttling occurred */
5860 cfs_b->nr_throttled += overrun;
5863 * This check is repeated as we release cfs_b->lock while we unthrottle.
5865 while (throttled && cfs_b->runtime > 0) {
5866 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5867 /* we can't nest cfs_b->lock while distributing bandwidth */
5868 throttled = distribute_cfs_runtime(cfs_b);
5869 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5873 * While we are ensured activity in the period following an
5874 * unthrottle, this also covers the case in which the new bandwidth is
5875 * insufficient to cover the existing bandwidth deficit. (Forcing the
5876 * timer to remain active while there are any throttled entities.)
5886 /* a cfs_rq won't donate quota below this amount */
5887 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5888 /* minimum remaining period time to redistribute slack quota */
5889 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5890 /* how long we wait to gather additional slack before distributing */
5891 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5894 * Are we near the end of the current quota period?
5896 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5897 * hrtimer base being cleared by hrtimer_start. In the case of
5898 * migrate_hrtimers, base is never cleared, so we are fine.
5900 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5902 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5905 /* if the call-back is running a quota refresh is already occurring */
5906 if (hrtimer_callback_running(refresh_timer))
5909 /* is a quota refresh about to occur? */
5910 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5911 if (remaining < (s64)min_expire)
5917 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5919 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5921 /* if there's a quota refresh soon don't bother with slack */
5922 if (runtime_refresh_within(cfs_b, min_left))
5925 /* don't push forwards an existing deferred unthrottle */
5926 if (cfs_b->slack_started)
5928 cfs_b->slack_started = true;
5930 hrtimer_start(&cfs_b->slack_timer,
5931 ns_to_ktime(cfs_bandwidth_slack_period),
5935 /* we know any runtime found here is valid as update_curr() precedes return */
5936 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5938 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5939 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5941 if (slack_runtime <= 0)
5944 raw_spin_lock(&cfs_b->lock);
5945 if (cfs_b->quota != RUNTIME_INF) {
5946 cfs_b->runtime += slack_runtime;
5948 /* we are under rq->lock, defer unthrottling using a timer */
5949 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5950 !list_empty(&cfs_b->throttled_cfs_rq))
5951 start_cfs_slack_bandwidth(cfs_b);
5953 raw_spin_unlock(&cfs_b->lock);
5955 /* even if it's not valid for return we don't want to try again */
5956 cfs_rq->runtime_remaining -= slack_runtime;
5959 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5961 if (!cfs_bandwidth_used())
5964 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
5967 __return_cfs_rq_runtime(cfs_rq);
5971 * This is done with a timer (instead of inline with bandwidth return) since
5972 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5974 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5976 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
5977 unsigned long flags;
5979 /* confirm we're still not at a refresh boundary */
5980 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5981 cfs_b->slack_started = false;
5983 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
5984 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5988 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
5989 runtime = cfs_b->runtime;
5991 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5996 distribute_cfs_runtime(cfs_b);
6000 * When a group wakes up we want to make sure that its quota is not already
6001 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6002 * runtime as update_curr() throttling can not trigger until it's on-rq.
6004 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6006 if (!cfs_bandwidth_used())
6009 /* an active group must be handled by the update_curr()->put() path */
6010 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6013 /* ensure the group is not already throttled */
6014 if (cfs_rq_throttled(cfs_rq))
6017 /* update runtime allocation */
6018 account_cfs_rq_runtime(cfs_rq, 0);
6019 if (cfs_rq->runtime_remaining <= 0)
6020 throttle_cfs_rq(cfs_rq);
6023 static void sync_throttle(struct task_group *tg, int cpu)
6025 struct cfs_rq *pcfs_rq, *cfs_rq;
6027 if (!cfs_bandwidth_used())
6033 cfs_rq = tg->cfs_rq[cpu];
6034 pcfs_rq = tg->parent->cfs_rq[cpu];
6036 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6037 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6040 /* conditionally throttle active cfs_rq's from put_prev_entity() */
6041 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6043 if (!cfs_bandwidth_used())
6046 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6050 * it's possible for a throttled entity to be forced into a running
6051 * state (e.g. set_curr_task), in this case we're finished.
6053 if (cfs_rq_throttled(cfs_rq))
6056 return throttle_cfs_rq(cfs_rq);
6059 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6061 struct cfs_bandwidth *cfs_b =
6062 container_of(timer, struct cfs_bandwidth, slack_timer);
6064 do_sched_cfs_slack_timer(cfs_b);
6066 return HRTIMER_NORESTART;
6069 extern const u64 max_cfs_quota_period;
6071 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6073 struct cfs_bandwidth *cfs_b =
6074 container_of(timer, struct cfs_bandwidth, period_timer);
6075 unsigned long flags;
6080 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6082 overrun = hrtimer_forward_now(timer, cfs_b->period);
6086 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6089 u64 new, old = ktime_to_ns(cfs_b->period);
6092 * Grow period by a factor of 2 to avoid losing precision.
6093 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6097 if (new < max_cfs_quota_period) {
6098 cfs_b->period = ns_to_ktime(new);
6102 pr_warn_ratelimited(
6103 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6105 div_u64(new, NSEC_PER_USEC),
6106 div_u64(cfs_b->quota, NSEC_PER_USEC));
6108 pr_warn_ratelimited(
6109 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6111 div_u64(old, NSEC_PER_USEC),
6112 div_u64(cfs_b->quota, NSEC_PER_USEC));
6115 /* reset count so we don't come right back in here */
6120 cfs_b->period_active = 0;
6121 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6123 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6126 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6128 raw_spin_lock_init(&cfs_b->lock);
6130 cfs_b->quota = RUNTIME_INF;
6131 cfs_b->period = ns_to_ktime(default_cfs_period());
6133 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6135 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6136 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6137 cfs_b->period_timer.function = sched_cfs_period_timer;
6139 /* Add a random offset so that timers interleave */
6140 hrtimer_set_expires(&cfs_b->period_timer,
6141 get_random_u32_below(cfs_b->period));
6142 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6143 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6144 cfs_b->slack_started = false;
6147 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6149 cfs_rq->runtime_enabled = 0;
6150 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6152 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6156 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6158 lockdep_assert_held(&cfs_b->lock);
6160 if (cfs_b->period_active)
6163 cfs_b->period_active = 1;
6164 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6165 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6168 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6170 int __maybe_unused i;
6172 /* init_cfs_bandwidth() was not called */
6173 if (!cfs_b->throttled_cfs_rq.next)
6176 hrtimer_cancel(&cfs_b->period_timer);
6177 hrtimer_cancel(&cfs_b->slack_timer);
6180 * It is possible that we still have some cfs_rq's pending on a CSD
6181 * list, though this race is very rare. In order for this to occur, we
6182 * must have raced with the last task leaving the group while there
6183 * exist throttled cfs_rq(s), and the period_timer must have queued the
6184 * CSD item but the remote cpu has not yet processed it. To handle this,
6185 * we can simply flush all pending CSD work inline here. We're
6186 * guaranteed at this point that no additional cfs_rq of this group can
6190 for_each_possible_cpu(i) {
6191 struct rq *rq = cpu_rq(i);
6192 unsigned long flags;
6194 if (list_empty(&rq->cfsb_csd_list))
6197 local_irq_save(flags);
6198 __cfsb_csd_unthrottle(rq);
6199 local_irq_restore(flags);
6205 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6207 * The race is harmless, since modifying bandwidth settings of unhooked group
6208 * bits doesn't do much.
6211 /* cpu online callback */
6212 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6214 struct task_group *tg;
6216 lockdep_assert_rq_held(rq);
6219 list_for_each_entry_rcu(tg, &task_groups, list) {
6220 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6221 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6223 raw_spin_lock(&cfs_b->lock);
6224 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6225 raw_spin_unlock(&cfs_b->lock);
6230 /* cpu offline callback */
6231 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6233 struct task_group *tg;
6235 lockdep_assert_rq_held(rq);
6238 * The rq clock has already been updated in the
6239 * set_rq_offline(), so we should skip updating
6240 * the rq clock again in unthrottle_cfs_rq().
6242 rq_clock_start_loop_update(rq);
6245 list_for_each_entry_rcu(tg, &task_groups, list) {
6246 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6248 if (!cfs_rq->runtime_enabled)
6252 * clock_task is not advancing so we just need to make sure
6253 * there's some valid quota amount
6255 cfs_rq->runtime_remaining = 1;
6257 * Offline rq is schedulable till CPU is completely disabled
6258 * in take_cpu_down(), so we prevent new cfs throttling here.
6260 cfs_rq->runtime_enabled = 0;
6262 if (cfs_rq_throttled(cfs_rq))
6263 unthrottle_cfs_rq(cfs_rq);
6267 rq_clock_stop_loop_update(rq);
6270 bool cfs_task_bw_constrained(struct task_struct *p)
6272 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6274 if (!cfs_bandwidth_used())
6277 if (cfs_rq->runtime_enabled ||
6278 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6284 #ifdef CONFIG_NO_HZ_FULL
6285 /* called from pick_next_task_fair() */
6286 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6288 int cpu = cpu_of(rq);
6290 if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6293 if (!tick_nohz_full_cpu(cpu))
6296 if (rq->nr_running != 1)
6300 * We know there is only one task runnable and we've just picked it. The
6301 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6302 * be otherwise able to stop the tick. Just need to check if we are using
6303 * bandwidth control.
6305 if (cfs_task_bw_constrained(p))
6306 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6310 #else /* CONFIG_CFS_BANDWIDTH */
6312 static inline bool cfs_bandwidth_used(void)
6317 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
6318 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
6319 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
6320 static inline void sync_throttle(struct task_group *tg, int cpu) {}
6321 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6323 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6328 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6333 static inline int throttled_lb_pair(struct task_group *tg,
6334 int src_cpu, int dest_cpu)
6339 #ifdef CONFIG_FAIR_GROUP_SCHED
6340 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
6341 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6344 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6348 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
6349 static inline void update_runtime_enabled(struct rq *rq) {}
6350 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6351 #ifdef CONFIG_CGROUP_SCHED
6352 bool cfs_task_bw_constrained(struct task_struct *p)
6357 #endif /* CONFIG_CFS_BANDWIDTH */
6359 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
6360 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6363 /**************************************************
6364 * CFS operations on tasks:
6367 #ifdef CONFIG_SCHED_HRTICK
6368 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6370 struct sched_entity *se = &p->se;
6372 SCHED_WARN_ON(task_rq(p) != rq);
6374 if (rq->cfs.h_nr_running > 1) {
6375 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6376 u64 slice = se->slice;
6377 s64 delta = slice - ran;
6380 if (task_current(rq, p))
6384 hrtick_start(rq, delta);
6389 * called from enqueue/dequeue and updates the hrtick when the
6390 * current task is from our class and nr_running is low enough
6393 static void hrtick_update(struct rq *rq)
6395 struct task_struct *curr = rq->curr;
6397 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6400 hrtick_start_fair(rq, curr);
6402 #else /* !CONFIG_SCHED_HRTICK */
6404 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6408 static inline void hrtick_update(struct rq *rq)
6414 static inline bool cpu_overutilized(int cpu)
6416 unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6417 unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6419 /* Return true only if the utilization doesn't fit CPU's capacity */
6420 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6423 static inline void update_overutilized_status(struct rq *rq)
6425 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6426 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6427 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6431 static inline void update_overutilized_status(struct rq *rq) { }
6434 /* Runqueue only has SCHED_IDLE tasks enqueued */
6435 static int sched_idle_rq(struct rq *rq)
6437 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6442 static int sched_idle_cpu(int cpu)
6444 return sched_idle_rq(cpu_rq(cpu));
6449 * The enqueue_task method is called before nr_running is
6450 * increased. Here we update the fair scheduling stats and
6451 * then put the task into the rbtree:
6454 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6456 struct cfs_rq *cfs_rq;
6457 struct sched_entity *se = &p->se;
6458 int idle_h_nr_running = task_has_idle_policy(p);
6459 int task_new = !(flags & ENQUEUE_WAKEUP);
6462 * The code below (indirectly) updates schedutil which looks at
6463 * the cfs_rq utilization to select a frequency.
6464 * Let's add the task's estimated utilization to the cfs_rq's
6465 * estimated utilization, before we update schedutil.
6467 util_est_enqueue(&rq->cfs, p);
6470 * If in_iowait is set, the code below may not trigger any cpufreq
6471 * utilization updates, so do it here explicitly with the IOWAIT flag
6475 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6477 for_each_sched_entity(se) {
6480 cfs_rq = cfs_rq_of(se);
6481 enqueue_entity(cfs_rq, se, flags);
6483 cfs_rq->h_nr_running++;
6484 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6486 if (cfs_rq_is_idle(cfs_rq))
6487 idle_h_nr_running = 1;
6489 /* end evaluation on encountering a throttled cfs_rq */
6490 if (cfs_rq_throttled(cfs_rq))
6491 goto enqueue_throttle;
6493 flags = ENQUEUE_WAKEUP;
6496 for_each_sched_entity(se) {
6497 cfs_rq = cfs_rq_of(se);
6499 update_load_avg(cfs_rq, se, UPDATE_TG);
6500 se_update_runnable(se);
6501 update_cfs_group(se);
6503 cfs_rq->h_nr_running++;
6504 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6506 if (cfs_rq_is_idle(cfs_rq))
6507 idle_h_nr_running = 1;
6509 /* end evaluation on encountering a throttled cfs_rq */
6510 if (cfs_rq_throttled(cfs_rq))
6511 goto enqueue_throttle;
6514 /* At this point se is NULL and we are at root level*/
6515 add_nr_running(rq, 1);
6518 * Since new tasks are assigned an initial util_avg equal to
6519 * half of the spare capacity of their CPU, tiny tasks have the
6520 * ability to cross the overutilized threshold, which will
6521 * result in the load balancer ruining all the task placement
6522 * done by EAS. As a way to mitigate that effect, do not account
6523 * for the first enqueue operation of new tasks during the
6524 * overutilized flag detection.
6526 * A better way of solving this problem would be to wait for
6527 * the PELT signals of tasks to converge before taking them
6528 * into account, but that is not straightforward to implement,
6529 * and the following generally works well enough in practice.
6532 update_overutilized_status(rq);
6535 assert_list_leaf_cfs_rq(rq);
6540 static void set_next_buddy(struct sched_entity *se);
6543 * The dequeue_task method is called before nr_running is
6544 * decreased. We remove the task from the rbtree and
6545 * update the fair scheduling stats:
6547 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6549 struct cfs_rq *cfs_rq;
6550 struct sched_entity *se = &p->se;
6551 int task_sleep = flags & DEQUEUE_SLEEP;
6552 int idle_h_nr_running = task_has_idle_policy(p);
6553 bool was_sched_idle = sched_idle_rq(rq);
6555 util_est_dequeue(&rq->cfs, p);
6557 for_each_sched_entity(se) {
6558 cfs_rq = cfs_rq_of(se);
6559 dequeue_entity(cfs_rq, se, flags);
6561 cfs_rq->h_nr_running--;
6562 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6564 if (cfs_rq_is_idle(cfs_rq))
6565 idle_h_nr_running = 1;
6567 /* end evaluation on encountering a throttled cfs_rq */
6568 if (cfs_rq_throttled(cfs_rq))
6569 goto dequeue_throttle;
6571 /* Don't dequeue parent if it has other entities besides us */
6572 if (cfs_rq->load.weight) {
6573 /* Avoid re-evaluating load for this entity: */
6574 se = parent_entity(se);
6576 * Bias pick_next to pick a task from this cfs_rq, as
6577 * p is sleeping when it is within its sched_slice.
6579 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6583 flags |= DEQUEUE_SLEEP;
6586 for_each_sched_entity(se) {
6587 cfs_rq = cfs_rq_of(se);
6589 update_load_avg(cfs_rq, se, UPDATE_TG);
6590 se_update_runnable(se);
6591 update_cfs_group(se);
6593 cfs_rq->h_nr_running--;
6594 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6596 if (cfs_rq_is_idle(cfs_rq))
6597 idle_h_nr_running = 1;
6599 /* end evaluation on encountering a throttled cfs_rq */
6600 if (cfs_rq_throttled(cfs_rq))
6601 goto dequeue_throttle;
6605 /* At this point se is NULL and we are at root level*/
6606 sub_nr_running(rq, 1);
6608 /* balance early to pull high priority tasks */
6609 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6610 rq->next_balance = jiffies;
6613 util_est_update(&rq->cfs, p, task_sleep);
6619 /* Working cpumask for: load_balance, load_balance_newidle. */
6620 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6621 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6622 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6624 #ifdef CONFIG_NO_HZ_COMMON
6627 cpumask_var_t idle_cpus_mask;
6629 int has_blocked; /* Idle CPUS has blocked load */
6630 int needs_update; /* Newly idle CPUs need their next_balance collated */
6631 unsigned long next_balance; /* in jiffy units */
6632 unsigned long next_blocked; /* Next update of blocked load in jiffies */
6633 } nohz ____cacheline_aligned;
6635 #endif /* CONFIG_NO_HZ_COMMON */
6637 static unsigned long cpu_load(struct rq *rq)
6639 return cfs_rq_load_avg(&rq->cfs);
6643 * cpu_load_without - compute CPU load without any contributions from *p
6644 * @cpu: the CPU which load is requested
6645 * @p: the task which load should be discounted
6647 * The load of a CPU is defined by the load of tasks currently enqueued on that
6648 * CPU as well as tasks which are currently sleeping after an execution on that
6651 * This method returns the load of the specified CPU by discounting the load of
6652 * the specified task, whenever the task is currently contributing to the CPU
6655 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6657 struct cfs_rq *cfs_rq;
6660 /* Task has no contribution or is new */
6661 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6662 return cpu_load(rq);
6665 load = READ_ONCE(cfs_rq->avg.load_avg);
6667 /* Discount task's util from CPU's util */
6668 lsub_positive(&load, task_h_load(p));
6673 static unsigned long cpu_runnable(struct rq *rq)
6675 return cfs_rq_runnable_avg(&rq->cfs);
6678 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6680 struct cfs_rq *cfs_rq;
6681 unsigned int runnable;
6683 /* Task has no contribution or is new */
6684 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6685 return cpu_runnable(rq);
6688 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6690 /* Discount task's runnable from CPU's runnable */
6691 lsub_positive(&runnable, p->se.avg.runnable_avg);
6696 static unsigned long capacity_of(int cpu)
6698 return cpu_rq(cpu)->cpu_capacity;
6701 static void record_wakee(struct task_struct *p)
6704 * Only decay a single time; tasks that have less then 1 wakeup per
6705 * jiffy will not have built up many flips.
6707 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6708 current->wakee_flips >>= 1;
6709 current->wakee_flip_decay_ts = jiffies;
6712 if (current->last_wakee != p) {
6713 current->last_wakee = p;
6714 current->wakee_flips++;
6719 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6721 * A waker of many should wake a different task than the one last awakened
6722 * at a frequency roughly N times higher than one of its wakees.
6724 * In order to determine whether we should let the load spread vs consolidating
6725 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6726 * partner, and a factor of lls_size higher frequency in the other.
6728 * With both conditions met, we can be relatively sure that the relationship is
6729 * non-monogamous, with partner count exceeding socket size.
6731 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6732 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6735 static int wake_wide(struct task_struct *p)
6737 unsigned int master = current->wakee_flips;
6738 unsigned int slave = p->wakee_flips;
6739 int factor = __this_cpu_read(sd_llc_size);
6742 swap(master, slave);
6743 if (slave < factor || master < slave * factor)
6749 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6750 * soonest. For the purpose of speed we only consider the waking and previous
6753 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6754 * cache-affine and is (or will be) idle.
6756 * wake_affine_weight() - considers the weight to reflect the average
6757 * scheduling latency of the CPUs. This seems to work
6758 * for the overloaded case.
6761 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6764 * If this_cpu is idle, it implies the wakeup is from interrupt
6765 * context. Only allow the move if cache is shared. Otherwise an
6766 * interrupt intensive workload could force all tasks onto one
6767 * node depending on the IO topology or IRQ affinity settings.
6769 * If the prev_cpu is idle and cache affine then avoid a migration.
6770 * There is no guarantee that the cache hot data from an interrupt
6771 * is more important than cache hot data on the prev_cpu and from
6772 * a cpufreq perspective, it's better to have higher utilisation
6775 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6776 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6778 if (sync && cpu_rq(this_cpu)->nr_running == 1)
6781 if (available_idle_cpu(prev_cpu))
6784 return nr_cpumask_bits;
6788 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6789 int this_cpu, int prev_cpu, int sync)
6791 s64 this_eff_load, prev_eff_load;
6792 unsigned long task_load;
6794 this_eff_load = cpu_load(cpu_rq(this_cpu));
6797 unsigned long current_load = task_h_load(current);
6799 if (current_load > this_eff_load)
6802 this_eff_load -= current_load;
6805 task_load = task_h_load(p);
6807 this_eff_load += task_load;
6808 if (sched_feat(WA_BIAS))
6809 this_eff_load *= 100;
6810 this_eff_load *= capacity_of(prev_cpu);
6812 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
6813 prev_eff_load -= task_load;
6814 if (sched_feat(WA_BIAS))
6815 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
6816 prev_eff_load *= capacity_of(this_cpu);
6819 * If sync, adjust the weight of prev_eff_load such that if
6820 * prev_eff == this_eff that select_idle_sibling() will consider
6821 * stacking the wakee on top of the waker if no other CPU is
6827 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6830 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6831 int this_cpu, int prev_cpu, int sync)
6833 int target = nr_cpumask_bits;
6835 if (sched_feat(WA_IDLE))
6836 target = wake_affine_idle(this_cpu, prev_cpu, sync);
6838 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6839 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6841 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
6842 if (target != this_cpu)
6845 schedstat_inc(sd->ttwu_move_affine);
6846 schedstat_inc(p->stats.nr_wakeups_affine);
6850 static struct sched_group *
6851 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6854 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6857 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6859 unsigned long load, min_load = ULONG_MAX;
6860 unsigned int min_exit_latency = UINT_MAX;
6861 u64 latest_idle_timestamp = 0;
6862 int least_loaded_cpu = this_cpu;
6863 int shallowest_idle_cpu = -1;
6866 /* Check if we have any choice: */
6867 if (group->group_weight == 1)
6868 return cpumask_first(sched_group_span(group));
6870 /* Traverse only the allowed CPUs */
6871 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6872 struct rq *rq = cpu_rq(i);
6874 if (!sched_core_cookie_match(rq, p))
6877 if (sched_idle_cpu(i))
6880 if (available_idle_cpu(i)) {
6881 struct cpuidle_state *idle = idle_get_state(rq);
6882 if (idle && idle->exit_latency < min_exit_latency) {
6884 * We give priority to a CPU whose idle state
6885 * has the smallest exit latency irrespective
6886 * of any idle timestamp.
6888 min_exit_latency = idle->exit_latency;
6889 latest_idle_timestamp = rq->idle_stamp;
6890 shallowest_idle_cpu = i;
6891 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6892 rq->idle_stamp > latest_idle_timestamp) {
6894 * If equal or no active idle state, then
6895 * the most recently idled CPU might have
6898 latest_idle_timestamp = rq->idle_stamp;
6899 shallowest_idle_cpu = i;
6901 } else if (shallowest_idle_cpu == -1) {
6902 load = cpu_load(cpu_rq(i));
6903 if (load < min_load) {
6905 least_loaded_cpu = i;
6910 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6913 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6914 int cpu, int prev_cpu, int sd_flag)
6918 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6922 * We need task's util for cpu_util_without, sync it up to
6923 * prev_cpu's last_update_time.
6925 if (!(sd_flag & SD_BALANCE_FORK))
6926 sync_entity_load_avg(&p->se);
6929 struct sched_group *group;
6930 struct sched_domain *tmp;
6933 if (!(sd->flags & sd_flag)) {
6938 group = find_idlest_group(sd, p, cpu);
6944 new_cpu = find_idlest_group_cpu(group, p, cpu);
6945 if (new_cpu == cpu) {
6946 /* Now try balancing at a lower domain level of 'cpu': */
6951 /* Now try balancing at a lower domain level of 'new_cpu': */
6953 weight = sd->span_weight;
6955 for_each_domain(cpu, tmp) {
6956 if (weight <= tmp->span_weight)
6958 if (tmp->flags & sd_flag)
6966 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
6968 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
6969 sched_cpu_cookie_match(cpu_rq(cpu), p))
6975 #ifdef CONFIG_SCHED_SMT
6976 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6977 EXPORT_SYMBOL_GPL(sched_smt_present);
6979 static inline void set_idle_cores(int cpu, int val)
6981 struct sched_domain_shared *sds;
6983 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6985 WRITE_ONCE(sds->has_idle_cores, val);
6988 static inline bool test_idle_cores(int cpu)
6990 struct sched_domain_shared *sds;
6992 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6994 return READ_ONCE(sds->has_idle_cores);
7000 * Scans the local SMT mask to see if the entire core is idle, and records this
7001 * information in sd_llc_shared->has_idle_cores.
7003 * Since SMT siblings share all cache levels, inspecting this limited remote
7004 * state should be fairly cheap.
7006 void __update_idle_core(struct rq *rq)
7008 int core = cpu_of(rq);
7012 if (test_idle_cores(core))
7015 for_each_cpu(cpu, cpu_smt_mask(core)) {
7019 if (!available_idle_cpu(cpu))
7023 set_idle_cores(core, 1);
7029 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7030 * there are no idle cores left in the system; tracked through
7031 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7033 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7038 for_each_cpu(cpu, cpu_smt_mask(core)) {
7039 if (!available_idle_cpu(cpu)) {
7041 if (*idle_cpu == -1) {
7042 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
7050 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
7057 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7062 * Scan the local SMT mask for idle CPUs.
7064 static int select_idle_smt(struct task_struct *p, int target)
7068 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7071 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7078 #else /* CONFIG_SCHED_SMT */
7080 static inline void set_idle_cores(int cpu, int val)
7084 static inline bool test_idle_cores(int cpu)
7089 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7091 return __select_idle_cpu(core, p);
7094 static inline int select_idle_smt(struct task_struct *p, int target)
7099 #endif /* CONFIG_SCHED_SMT */
7102 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7103 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7104 * average idle time for this rq (as found in rq->avg_idle).
7106 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7108 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7109 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7110 struct sched_domain_shared *sd_share;
7111 struct rq *this_rq = this_rq();
7112 int this = smp_processor_id();
7113 struct sched_domain *this_sd = NULL;
7116 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7118 if (sched_feat(SIS_PROP) && !has_idle_core) {
7119 u64 avg_cost, avg_idle, span_avg;
7120 unsigned long now = jiffies;
7122 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7127 * If we're busy, the assumption that the last idle period
7128 * predicts the future is flawed; age away the remaining
7129 * predicted idle time.
7131 if (unlikely(this_rq->wake_stamp < now)) {
7132 while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7133 this_rq->wake_stamp++;
7134 this_rq->wake_avg_idle >>= 1;
7138 avg_idle = this_rq->wake_avg_idle;
7139 avg_cost = this_sd->avg_scan_cost + 1;
7141 span_avg = sd->span_weight * avg_idle;
7142 if (span_avg > 4*avg_cost)
7143 nr = div_u64(span_avg, avg_cost);
7147 time = cpu_clock(this);
7150 if (sched_feat(SIS_UTIL)) {
7151 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7153 /* because !--nr is the condition to stop scan */
7154 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7155 /* overloaded LLC is unlikely to have idle cpu/core */
7161 for_each_cpu_wrap(cpu, cpus, target + 1) {
7162 if (has_idle_core) {
7163 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7164 if ((unsigned int)i < nr_cpumask_bits)
7170 idle_cpu = __select_idle_cpu(cpu, p);
7171 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7177 set_idle_cores(target, false);
7179 if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7180 time = cpu_clock(this) - time;
7183 * Account for the scan cost of wakeups against the average
7186 this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7188 update_avg(&this_sd->avg_scan_cost, time);
7195 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7196 * the task fits. If no CPU is big enough, but there are idle ones, try to
7197 * maximize capacity.
7200 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7202 unsigned long task_util, util_min, util_max, best_cap = 0;
7203 int fits, best_fits = 0;
7204 int cpu, best_cpu = -1;
7205 struct cpumask *cpus;
7207 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7208 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7210 task_util = task_util_est(p);
7211 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7212 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7214 for_each_cpu_wrap(cpu, cpus, target) {
7215 unsigned long cpu_cap = capacity_of(cpu);
7217 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7220 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7222 /* This CPU fits with all requirements */
7226 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7227 * Look for the CPU with best capacity.
7230 cpu_cap = capacity_orig_of(cpu) - thermal_load_avg(cpu_rq(cpu));
7233 * First, select CPU which fits better (-1 being better than 0).
7234 * Then, select the one with best capacity at same level.
7236 if ((fits < best_fits) ||
7237 ((fits == best_fits) && (cpu_cap > best_cap))) {
7247 static inline bool asym_fits_cpu(unsigned long util,
7248 unsigned long util_min,
7249 unsigned long util_max,
7252 if (sched_asym_cpucap_active())
7254 * Return true only if the cpu fully fits the task requirements
7255 * which include the utilization and the performance hints.
7257 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7263 * Try and locate an idle core/thread in the LLC cache domain.
7265 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7267 bool has_idle_core = false;
7268 struct sched_domain *sd;
7269 unsigned long task_util, util_min, util_max;
7270 int i, recent_used_cpu;
7273 * On asymmetric system, update task utilization because we will check
7274 * that the task fits with cpu's capacity.
7276 if (sched_asym_cpucap_active()) {
7277 sync_entity_load_avg(&p->se);
7278 task_util = task_util_est(p);
7279 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7280 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7284 * per-cpu select_rq_mask usage
7286 lockdep_assert_irqs_disabled();
7288 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7289 asym_fits_cpu(task_util, util_min, util_max, target))
7293 * If the previous CPU is cache affine and idle, don't be stupid:
7295 if (prev != target && cpus_share_cache(prev, target) &&
7296 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7297 asym_fits_cpu(task_util, util_min, util_max, prev))
7301 * Allow a per-cpu kthread to stack with the wakee if the
7302 * kworker thread and the tasks previous CPUs are the same.
7303 * The assumption is that the wakee queued work for the
7304 * per-cpu kthread that is now complete and the wakeup is
7305 * essentially a sync wakeup. An obvious example of this
7306 * pattern is IO completions.
7308 if (is_per_cpu_kthread(current) &&
7310 prev == smp_processor_id() &&
7311 this_rq()->nr_running <= 1 &&
7312 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7316 /* Check a recently used CPU as a potential idle candidate: */
7317 recent_used_cpu = p->recent_used_cpu;
7318 p->recent_used_cpu = prev;
7319 if (recent_used_cpu != prev &&
7320 recent_used_cpu != target &&
7321 cpus_share_cache(recent_used_cpu, target) &&
7322 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7323 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7324 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7325 return recent_used_cpu;
7329 * For asymmetric CPU capacity systems, our domain of interest is
7330 * sd_asym_cpucapacity rather than sd_llc.
7332 if (sched_asym_cpucap_active()) {
7333 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7335 * On an asymmetric CPU capacity system where an exclusive
7336 * cpuset defines a symmetric island (i.e. one unique
7337 * capacity_orig value through the cpuset), the key will be set
7338 * but the CPUs within that cpuset will not have a domain with
7339 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7343 i = select_idle_capacity(p, sd, target);
7344 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7348 sd = rcu_dereference(per_cpu(sd_llc, target));
7352 if (sched_smt_active()) {
7353 has_idle_core = test_idle_cores(target);
7355 if (!has_idle_core && cpus_share_cache(prev, target)) {
7356 i = select_idle_smt(p, prev);
7357 if ((unsigned int)i < nr_cpumask_bits)
7362 i = select_idle_cpu(p, sd, has_idle_core, target);
7363 if ((unsigned)i < nr_cpumask_bits)
7370 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7371 * @cpu: the CPU to get the utilization for
7372 * @p: task for which the CPU utilization should be predicted or NULL
7373 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7374 * @boost: 1 to enable boosting, otherwise 0
7376 * The unit of the return value must be the same as the one of CPU capacity
7377 * so that CPU utilization can be compared with CPU capacity.
7379 * CPU utilization is the sum of running time of runnable tasks plus the
7380 * recent utilization of currently non-runnable tasks on that CPU.
7381 * It represents the amount of CPU capacity currently used by CFS tasks in
7382 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7383 * capacity at f_max.
7385 * The estimated CPU utilization is defined as the maximum between CPU
7386 * utilization and sum of the estimated utilization of the currently
7387 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7388 * previously-executed tasks, which helps better deduce how busy a CPU will
7389 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7390 * of such a task would be significantly decayed at this point of time.
7392 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7393 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7394 * utilization. Boosting is implemented in cpu_util() so that internal
7395 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7396 * latter via cpu_util_cfs_boost().
7398 * CPU utilization can be higher than the current CPU capacity
7399 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7400 * of rounding errors as well as task migrations or wakeups of new tasks.
7401 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7402 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7403 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7404 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7405 * though since this is useful for predicting the CPU capacity required
7406 * after task migrations (scheduler-driven DVFS).
7408 * Return: (Boosted) (estimated) utilization for the specified CPU.
7410 static unsigned long
7411 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7413 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7414 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7415 unsigned long runnable;
7418 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7419 util = max(util, runnable);
7423 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7424 * contribution. If @p migrates from another CPU to @cpu add its
7425 * contribution. In all the other cases @cpu is not impacted by the
7426 * migration so its util_avg is already correct.
7428 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7429 lsub_positive(&util, task_util(p));
7430 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7431 util += task_util(p);
7433 if (sched_feat(UTIL_EST)) {
7434 unsigned long util_est;
7436 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7439 * During wake-up @p isn't enqueued yet and doesn't contribute
7440 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7441 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7442 * has been enqueued.
7444 * During exec (@dst_cpu = -1) @p is enqueued and does
7445 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7446 * Remove it to "simulate" cpu_util without @p's contribution.
7448 * Despite the task_on_rq_queued(@p) check there is still a
7449 * small window for a possible race when an exec
7450 * select_task_rq_fair() races with LB's detach_task().
7454 * p->on_rq = TASK_ON_RQ_MIGRATING;
7455 * -------------------------------- A
7457 * dequeue_task_fair() + Race Time
7458 * util_est_dequeue() /
7459 * -------------------------------- B
7461 * The additional check "current == p" is required to further
7462 * reduce the race window.
7465 util_est += _task_util_est(p);
7466 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7467 lsub_positive(&util_est, _task_util_est(p));
7469 util = max(util, util_est);
7472 return min(util, capacity_orig_of(cpu));
7475 unsigned long cpu_util_cfs(int cpu)
7477 return cpu_util(cpu, NULL, -1, 0);
7480 unsigned long cpu_util_cfs_boost(int cpu)
7482 return cpu_util(cpu, NULL, -1, 1);
7486 * cpu_util_without: compute cpu utilization without any contributions from *p
7487 * @cpu: the CPU which utilization is requested
7488 * @p: the task which utilization should be discounted
7490 * The utilization of a CPU is defined by the utilization of tasks currently
7491 * enqueued on that CPU as well as tasks which are currently sleeping after an
7492 * execution on that CPU.
7494 * This method returns the utilization of the specified CPU by discounting the
7495 * utilization of the specified task, whenever the task is currently
7496 * contributing to the CPU utilization.
7498 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7500 /* Task has no contribution or is new */
7501 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7504 return cpu_util(cpu, p, -1, 0);
7508 * energy_env - Utilization landscape for energy estimation.
7509 * @task_busy_time: Utilization contribution by the task for which we test the
7510 * placement. Given by eenv_task_busy_time().
7511 * @pd_busy_time: Utilization of the whole perf domain without the task
7512 * contribution. Given by eenv_pd_busy_time().
7513 * @cpu_cap: Maximum CPU capacity for the perf domain.
7514 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7517 unsigned long task_busy_time;
7518 unsigned long pd_busy_time;
7519 unsigned long cpu_cap;
7520 unsigned long pd_cap;
7524 * Compute the task busy time for compute_energy(). This time cannot be
7525 * injected directly into effective_cpu_util() because of the IRQ scaling.
7526 * The latter only makes sense with the most recent CPUs where the task has
7529 static inline void eenv_task_busy_time(struct energy_env *eenv,
7530 struct task_struct *p, int prev_cpu)
7532 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7533 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7535 if (unlikely(irq >= max_cap))
7536 busy_time = max_cap;
7538 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7540 eenv->task_busy_time = busy_time;
7544 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7545 * utilization for each @pd_cpus, it however doesn't take into account
7546 * clamping since the ratio (utilization / cpu_capacity) is already enough to
7547 * scale the EM reported power consumption at the (eventually clamped)
7550 * The contribution of the task @p for which we want to estimate the
7551 * energy cost is removed (by cpu_util()) and must be calculated
7552 * separately (see eenv_task_busy_time). This ensures:
7554 * - A stable PD utilization, no matter which CPU of that PD we want to place
7557 * - A fair comparison between CPUs as the task contribution (task_util())
7558 * will always be the same no matter which CPU utilization we rely on
7559 * (util_avg or util_est).
7561 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7562 * exceed @eenv->pd_cap.
7564 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7565 struct cpumask *pd_cpus,
7566 struct task_struct *p)
7568 unsigned long busy_time = 0;
7571 for_each_cpu(cpu, pd_cpus) {
7572 unsigned long util = cpu_util(cpu, p, -1, 0);
7574 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7577 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7581 * Compute the maximum utilization for compute_energy() when the task @p
7582 * is placed on the cpu @dst_cpu.
7584 * Returns the maximum utilization among @eenv->cpus. This utilization can't
7585 * exceed @eenv->cpu_cap.
7587 static inline unsigned long
7588 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7589 struct task_struct *p, int dst_cpu)
7591 unsigned long max_util = 0;
7594 for_each_cpu(cpu, pd_cpus) {
7595 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7596 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7597 unsigned long eff_util;
7600 * Performance domain frequency: utilization clamping
7601 * must be considered since it affects the selection
7602 * of the performance domain frequency.
7603 * NOTE: in case RT tasks are running, by default the
7604 * FREQUENCY_UTIL's utilization can be max OPP.
7606 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7607 max_util = max(max_util, eff_util);
7610 return min(max_util, eenv->cpu_cap);
7614 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7615 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7616 * contribution is ignored.
7618 static inline unsigned long
7619 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7620 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7622 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7623 unsigned long busy_time = eenv->pd_busy_time;
7626 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7628 return em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7632 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7633 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7634 * spare capacity in each performance domain and uses it as a potential
7635 * candidate to execute the task. Then, it uses the Energy Model to figure
7636 * out which of the CPU candidates is the most energy-efficient.
7638 * The rationale for this heuristic is as follows. In a performance domain,
7639 * all the most energy efficient CPU candidates (according to the Energy
7640 * Model) are those for which we'll request a low frequency. When there are
7641 * several CPUs for which the frequency request will be the same, we don't
7642 * have enough data to break the tie between them, because the Energy Model
7643 * only includes active power costs. With this model, if we assume that
7644 * frequency requests follow utilization (e.g. using schedutil), the CPU with
7645 * the maximum spare capacity in a performance domain is guaranteed to be among
7646 * the best candidates of the performance domain.
7648 * In practice, it could be preferable from an energy standpoint to pack
7649 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7650 * but that could also hurt our chances to go cluster idle, and we have no
7651 * ways to tell with the current Energy Model if this is actually a good
7652 * idea or not. So, find_energy_efficient_cpu() basically favors
7653 * cluster-packing, and spreading inside a cluster. That should at least be
7654 * a good thing for latency, and this is consistent with the idea that most
7655 * of the energy savings of EAS come from the asymmetry of the system, and
7656 * not so much from breaking the tie between identical CPUs. That's also the
7657 * reason why EAS is enabled in the topology code only for systems where
7658 * SD_ASYM_CPUCAPACITY is set.
7660 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7661 * they don't have any useful utilization data yet and it's not possible to
7662 * forecast their impact on energy consumption. Consequently, they will be
7663 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7664 * to be energy-inefficient in some use-cases. The alternative would be to
7665 * bias new tasks towards specific types of CPUs first, or to try to infer
7666 * their util_avg from the parent task, but those heuristics could hurt
7667 * other use-cases too. So, until someone finds a better way to solve this,
7668 * let's keep things simple by re-using the existing slow path.
7670 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7672 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7673 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7674 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7675 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7676 struct root_domain *rd = this_rq()->rd;
7677 int cpu, best_energy_cpu, target = -1;
7678 int prev_fits = -1, best_fits = -1;
7679 unsigned long best_thermal_cap = 0;
7680 unsigned long prev_thermal_cap = 0;
7681 struct sched_domain *sd;
7682 struct perf_domain *pd;
7683 struct energy_env eenv;
7686 pd = rcu_dereference(rd->pd);
7687 if (!pd || READ_ONCE(rd->overutilized))
7691 * Energy-aware wake-up happens on the lowest sched_domain starting
7692 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7694 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7695 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7702 sync_entity_load_avg(&p->se);
7703 if (!uclamp_task_util(p, p_util_min, p_util_max))
7706 eenv_task_busy_time(&eenv, p, prev_cpu);
7708 for (; pd; pd = pd->next) {
7709 unsigned long util_min = p_util_min, util_max = p_util_max;
7710 unsigned long cpu_cap, cpu_thermal_cap, util;
7711 unsigned long cur_delta, max_spare_cap = 0;
7712 unsigned long rq_util_min, rq_util_max;
7713 unsigned long prev_spare_cap = 0;
7714 int max_spare_cap_cpu = -1;
7715 unsigned long base_energy;
7716 int fits, max_fits = -1;
7718 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7720 if (cpumask_empty(cpus))
7723 /* Account thermal pressure for the energy estimation */
7724 cpu = cpumask_first(cpus);
7725 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7726 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7728 eenv.cpu_cap = cpu_thermal_cap;
7731 for_each_cpu(cpu, cpus) {
7732 struct rq *rq = cpu_rq(cpu);
7734 eenv.pd_cap += cpu_thermal_cap;
7736 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7739 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7742 util = cpu_util(cpu, p, cpu, 0);
7743 cpu_cap = capacity_of(cpu);
7746 * Skip CPUs that cannot satisfy the capacity request.
7747 * IOW, placing the task there would make the CPU
7748 * overutilized. Take uclamp into account to see how
7749 * much capacity we can get out of the CPU; this is
7750 * aligned with sched_cpu_util().
7752 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7754 * Open code uclamp_rq_util_with() except for
7755 * the clamp() part. Ie: apply max aggregation
7756 * only. util_fits_cpu() logic requires to
7757 * operate on non clamped util but must use the
7758 * max-aggregated uclamp_{min, max}.
7760 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7761 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7763 util_min = max(rq_util_min, p_util_min);
7764 util_max = max(rq_util_max, p_util_max);
7767 fits = util_fits_cpu(util, util_min, util_max, cpu);
7771 lsub_positive(&cpu_cap, util);
7773 if (cpu == prev_cpu) {
7774 /* Always use prev_cpu as a candidate. */
7775 prev_spare_cap = cpu_cap;
7777 } else if ((fits > max_fits) ||
7778 ((fits == max_fits) && (cpu_cap > max_spare_cap))) {
7780 * Find the CPU with the maximum spare capacity
7781 * among the remaining CPUs in the performance
7784 max_spare_cap = cpu_cap;
7785 max_spare_cap_cpu = cpu;
7790 if (max_spare_cap_cpu < 0 && prev_spare_cap == 0)
7793 eenv_pd_busy_time(&eenv, cpus, p);
7794 /* Compute the 'base' energy of the pd, without @p */
7795 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
7797 /* Evaluate the energy impact of using prev_cpu. */
7798 if (prev_spare_cap > 0) {
7799 prev_delta = compute_energy(&eenv, pd, cpus, p,
7801 /* CPU utilization has changed */
7802 if (prev_delta < base_energy)
7804 prev_delta -= base_energy;
7805 prev_thermal_cap = cpu_thermal_cap;
7806 best_delta = min(best_delta, prev_delta);
7809 /* Evaluate the energy impact of using max_spare_cap_cpu. */
7810 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
7811 /* Current best energy cpu fits better */
7812 if (max_fits < best_fits)
7816 * Both don't fit performance hint (i.e. uclamp_min)
7817 * but best energy cpu has better capacity.
7819 if ((max_fits < 0) &&
7820 (cpu_thermal_cap <= best_thermal_cap))
7823 cur_delta = compute_energy(&eenv, pd, cpus, p,
7825 /* CPU utilization has changed */
7826 if (cur_delta < base_energy)
7828 cur_delta -= base_energy;
7831 * Both fit for the task but best energy cpu has lower
7834 if ((max_fits > 0) && (best_fits > 0) &&
7835 (cur_delta >= best_delta))
7838 best_delta = cur_delta;
7839 best_energy_cpu = max_spare_cap_cpu;
7840 best_fits = max_fits;
7841 best_thermal_cap = cpu_thermal_cap;
7846 if ((best_fits > prev_fits) ||
7847 ((best_fits > 0) && (best_delta < prev_delta)) ||
7848 ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
7849 target = best_energy_cpu;
7860 * select_task_rq_fair: Select target runqueue for the waking task in domains
7861 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
7862 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7864 * Balances load by selecting the idlest CPU in the idlest group, or under
7865 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
7867 * Returns the target CPU number.
7870 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
7872 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
7873 struct sched_domain *tmp, *sd = NULL;
7874 int cpu = smp_processor_id();
7875 int new_cpu = prev_cpu;
7876 int want_affine = 0;
7877 /* SD_flags and WF_flags share the first nibble */
7878 int sd_flag = wake_flags & 0xF;
7881 * required for stable ->cpus_allowed
7883 lockdep_assert_held(&p->pi_lock);
7884 if (wake_flags & WF_TTWU) {
7887 if ((wake_flags & WF_CURRENT_CPU) &&
7888 cpumask_test_cpu(cpu, p->cpus_ptr))
7891 if (sched_energy_enabled()) {
7892 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
7898 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
7902 for_each_domain(cpu, tmp) {
7904 * If both 'cpu' and 'prev_cpu' are part of this domain,
7905 * cpu is a valid SD_WAKE_AFFINE target.
7907 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
7908 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
7909 if (cpu != prev_cpu)
7910 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
7912 sd = NULL; /* Prefer wake_affine over balance flags */
7917 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
7918 * usually do not have SD_BALANCE_WAKE set. That means wakeup
7919 * will usually go to the fast path.
7921 if (tmp->flags & sd_flag)
7923 else if (!want_affine)
7929 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
7930 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
7932 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
7940 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
7941 * cfs_rq_of(p) references at time of call are still valid and identify the
7942 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7944 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
7946 struct sched_entity *se = &p->se;
7948 if (!task_on_rq_migrating(p)) {
7949 remove_entity_load_avg(se);
7952 * Here, the task's PELT values have been updated according to
7953 * the current rq's clock. But if that clock hasn't been
7954 * updated in a while, a substantial idle time will be missed,
7955 * leading to an inflation after wake-up on the new rq.
7957 * Estimate the missing time from the cfs_rq last_update_time
7958 * and update sched_avg to improve the PELT continuity after
7961 migrate_se_pelt_lag(se);
7964 /* Tell new CPU we are migrated */
7965 se->avg.last_update_time = 0;
7967 update_scan_period(p, new_cpu);
7970 static void task_dead_fair(struct task_struct *p)
7972 remove_entity_load_avg(&p->se);
7976 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7981 return newidle_balance(rq, rf) != 0;
7983 #endif /* CONFIG_SMP */
7985 static void set_next_buddy(struct sched_entity *se)
7987 for_each_sched_entity(se) {
7988 if (SCHED_WARN_ON(!se->on_rq))
7992 cfs_rq_of(se)->next = se;
7997 * Preempt the current task with a newly woken task if needed:
7999 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
8001 struct task_struct *curr = rq->curr;
8002 struct sched_entity *se = &curr->se, *pse = &p->se;
8003 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8004 int next_buddy_marked = 0;
8005 int cse_is_idle, pse_is_idle;
8007 if (unlikely(se == pse))
8011 * This is possible from callers such as attach_tasks(), in which we
8012 * unconditionally check_preempt_curr() after an enqueue (which may have
8013 * lead to a throttle). This both saves work and prevents false
8014 * next-buddy nomination below.
8016 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8019 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8020 set_next_buddy(pse);
8021 next_buddy_marked = 1;
8025 * We can come here with TIF_NEED_RESCHED already set from new task
8028 * Note: this also catches the edge-case of curr being in a throttled
8029 * group (e.g. via set_curr_task), since update_curr() (in the
8030 * enqueue of curr) will have resulted in resched being set. This
8031 * prevents us from potentially nominating it as a false LAST_BUDDY
8034 if (test_tsk_need_resched(curr))
8037 /* Idle tasks are by definition preempted by non-idle tasks. */
8038 if (unlikely(task_has_idle_policy(curr)) &&
8039 likely(!task_has_idle_policy(p)))
8043 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8044 * is driven by the tick):
8046 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8049 find_matching_se(&se, &pse);
8052 cse_is_idle = se_is_idle(se);
8053 pse_is_idle = se_is_idle(pse);
8056 * Preempt an idle group in favor of a non-idle group (and don't preempt
8057 * in the inverse case).
8059 if (cse_is_idle && !pse_is_idle)
8061 if (cse_is_idle != pse_is_idle)
8064 cfs_rq = cfs_rq_of(se);
8065 update_curr(cfs_rq);
8068 * XXX pick_eevdf(cfs_rq) != se ?
8070 if (pick_eevdf(cfs_rq) == pse)
8080 static struct task_struct *pick_task_fair(struct rq *rq)
8082 struct sched_entity *se;
8083 struct cfs_rq *cfs_rq;
8087 if (!cfs_rq->nr_running)
8091 struct sched_entity *curr = cfs_rq->curr;
8093 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8096 update_curr(cfs_rq);
8100 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8104 se = pick_next_entity(cfs_rq, curr);
8105 cfs_rq = group_cfs_rq(se);
8112 struct task_struct *
8113 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8115 struct cfs_rq *cfs_rq = &rq->cfs;
8116 struct sched_entity *se;
8117 struct task_struct *p;
8121 if (!sched_fair_runnable(rq))
8124 #ifdef CONFIG_FAIR_GROUP_SCHED
8125 if (!prev || prev->sched_class != &fair_sched_class)
8129 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8130 * likely that a next task is from the same cgroup as the current.
8132 * Therefore attempt to avoid putting and setting the entire cgroup
8133 * hierarchy, only change the part that actually changes.
8137 struct sched_entity *curr = cfs_rq->curr;
8140 * Since we got here without doing put_prev_entity() we also
8141 * have to consider cfs_rq->curr. If it is still a runnable
8142 * entity, update_curr() will update its vruntime, otherwise
8143 * forget we've ever seen it.
8147 update_curr(cfs_rq);
8152 * This call to check_cfs_rq_runtime() will do the
8153 * throttle and dequeue its entity in the parent(s).
8154 * Therefore the nr_running test will indeed
8157 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8160 if (!cfs_rq->nr_running)
8167 se = pick_next_entity(cfs_rq, curr);
8168 cfs_rq = group_cfs_rq(se);
8174 * Since we haven't yet done put_prev_entity and if the selected task
8175 * is a different task than we started out with, try and touch the
8176 * least amount of cfs_rqs.
8179 struct sched_entity *pse = &prev->se;
8181 while (!(cfs_rq = is_same_group(se, pse))) {
8182 int se_depth = se->depth;
8183 int pse_depth = pse->depth;
8185 if (se_depth <= pse_depth) {
8186 put_prev_entity(cfs_rq_of(pse), pse);
8187 pse = parent_entity(pse);
8189 if (se_depth >= pse_depth) {
8190 set_next_entity(cfs_rq_of(se), se);
8191 se = parent_entity(se);
8195 put_prev_entity(cfs_rq, pse);
8196 set_next_entity(cfs_rq, se);
8203 put_prev_task(rq, prev);
8206 se = pick_next_entity(cfs_rq, NULL);
8207 set_next_entity(cfs_rq, se);
8208 cfs_rq = group_cfs_rq(se);
8213 done: __maybe_unused;
8216 * Move the next running task to the front of
8217 * the list, so our cfs_tasks list becomes MRU
8220 list_move(&p->se.group_node, &rq->cfs_tasks);
8223 if (hrtick_enabled_fair(rq))
8224 hrtick_start_fair(rq, p);
8226 update_misfit_status(p, rq);
8227 sched_fair_update_stop_tick(rq, p);
8235 new_tasks = newidle_balance(rq, rf);
8238 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8239 * possible for any higher priority task to appear. In that case we
8240 * must re-start the pick_next_entity() loop.
8249 * rq is about to be idle, check if we need to update the
8250 * lost_idle_time of clock_pelt
8252 update_idle_rq_clock_pelt(rq);
8257 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8259 return pick_next_task_fair(rq, NULL, NULL);
8263 * Account for a descheduled task:
8265 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8267 struct sched_entity *se = &prev->se;
8268 struct cfs_rq *cfs_rq;
8270 for_each_sched_entity(se) {
8271 cfs_rq = cfs_rq_of(se);
8272 put_prev_entity(cfs_rq, se);
8277 * sched_yield() is very simple
8279 static void yield_task_fair(struct rq *rq)
8281 struct task_struct *curr = rq->curr;
8282 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8283 struct sched_entity *se = &curr->se;
8286 * Are we the only task in the tree?
8288 if (unlikely(rq->nr_running == 1))
8291 clear_buddies(cfs_rq, se);
8293 update_rq_clock(rq);
8295 * Update run-time statistics of the 'current'.
8297 update_curr(cfs_rq);
8299 * Tell update_rq_clock() that we've just updated,
8300 * so we don't do microscopic update in schedule()
8301 * and double the fastpath cost.
8303 rq_clock_skip_update(rq);
8305 se->deadline += calc_delta_fair(se->slice, se);
8308 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8310 struct sched_entity *se = &p->se;
8312 /* throttled hierarchies are not runnable */
8313 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8316 /* Tell the scheduler that we'd really like pse to run next. */
8319 yield_task_fair(rq);
8325 /**************************************************
8326 * Fair scheduling class load-balancing methods.
8330 * The purpose of load-balancing is to achieve the same basic fairness the
8331 * per-CPU scheduler provides, namely provide a proportional amount of compute
8332 * time to each task. This is expressed in the following equation:
8334 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8336 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8337 * W_i,0 is defined as:
8339 * W_i,0 = \Sum_j w_i,j (2)
8341 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8342 * is derived from the nice value as per sched_prio_to_weight[].
8344 * The weight average is an exponential decay average of the instantaneous
8347 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8349 * C_i is the compute capacity of CPU i, typically it is the
8350 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8351 * can also include other factors [XXX].
8353 * To achieve this balance we define a measure of imbalance which follows
8354 * directly from (1):
8356 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8358 * We them move tasks around to minimize the imbalance. In the continuous
8359 * function space it is obvious this converges, in the discrete case we get
8360 * a few fun cases generally called infeasible weight scenarios.
8363 * - infeasible weights;
8364 * - local vs global optima in the discrete case. ]
8369 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8370 * for all i,j solution, we create a tree of CPUs that follows the hardware
8371 * topology where each level pairs two lower groups (or better). This results
8372 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8373 * tree to only the first of the previous level and we decrease the frequency
8374 * of load-balance at each level inv. proportional to the number of CPUs in
8380 * \Sum { --- * --- * 2^i } = O(n) (5)
8382 * `- size of each group
8383 * | | `- number of CPUs doing load-balance
8385 * `- sum over all levels
8387 * Coupled with a limit on how many tasks we can migrate every balance pass,
8388 * this makes (5) the runtime complexity of the balancer.
8390 * An important property here is that each CPU is still (indirectly) connected
8391 * to every other CPU in at most O(log n) steps:
8393 * The adjacency matrix of the resulting graph is given by:
8396 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8399 * And you'll find that:
8401 * A^(log_2 n)_i,j != 0 for all i,j (7)
8403 * Showing there's indeed a path between every CPU in at most O(log n) steps.
8404 * The task movement gives a factor of O(m), giving a convergence complexity
8407 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8412 * In order to avoid CPUs going idle while there's still work to do, new idle
8413 * balancing is more aggressive and has the newly idle CPU iterate up the domain
8414 * tree itself instead of relying on other CPUs to bring it work.
8416 * This adds some complexity to both (5) and (8) but it reduces the total idle
8424 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8427 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8432 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8434 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8436 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8439 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8440 * rewrite all of this once again.]
8443 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8445 enum fbq_type { regular, remote, all };
8448 * 'group_type' describes the group of CPUs at the moment of load balancing.
8450 * The enum is ordered by pulling priority, with the group with lowest priority
8451 * first so the group_type can simply be compared when selecting the busiest
8452 * group. See update_sd_pick_busiest().
8455 /* The group has spare capacity that can be used to run more tasks. */
8456 group_has_spare = 0,
8458 * The group is fully used and the tasks don't compete for more CPU
8459 * cycles. Nevertheless, some tasks might wait before running.
8463 * One task doesn't fit with CPU's capacity and must be migrated to a
8464 * more powerful CPU.
8468 * Balance SMT group that's fully busy. Can benefit from migration
8469 * a task on SMT with busy sibling to another CPU on idle core.
8473 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8474 * and the task should be migrated to it instead of running on the
8479 * The tasks' affinity constraints previously prevented the scheduler
8480 * from balancing the load across the system.
8484 * The CPU is overloaded and can't provide expected CPU cycles to all
8490 enum migration_type {
8497 #define LBF_ALL_PINNED 0x01
8498 #define LBF_NEED_BREAK 0x02
8499 #define LBF_DST_PINNED 0x04
8500 #define LBF_SOME_PINNED 0x08
8501 #define LBF_ACTIVE_LB 0x10
8504 struct sched_domain *sd;
8512 struct cpumask *dst_grpmask;
8514 enum cpu_idle_type idle;
8516 /* The set of CPUs under consideration for load-balancing */
8517 struct cpumask *cpus;
8522 unsigned int loop_break;
8523 unsigned int loop_max;
8525 enum fbq_type fbq_type;
8526 enum migration_type migration_type;
8527 struct list_head tasks;
8531 * Is this task likely cache-hot:
8533 static int task_hot(struct task_struct *p, struct lb_env *env)
8537 lockdep_assert_rq_held(env->src_rq);
8539 if (p->sched_class != &fair_sched_class)
8542 if (unlikely(task_has_idle_policy(p)))
8545 /* SMT siblings share cache */
8546 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8550 * Buddy candidates are cache hot:
8552 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8553 (&p->se == cfs_rq_of(&p->se)->next))
8556 if (sysctl_sched_migration_cost == -1)
8560 * Don't migrate task if the task's cookie does not match
8561 * with the destination CPU's core cookie.
8563 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8566 if (sysctl_sched_migration_cost == 0)
8569 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8571 return delta < (s64)sysctl_sched_migration_cost;
8574 #ifdef CONFIG_NUMA_BALANCING
8576 * Returns 1, if task migration degrades locality
8577 * Returns 0, if task migration improves locality i.e migration preferred.
8578 * Returns -1, if task migration is not affected by locality.
8580 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8582 struct numa_group *numa_group = rcu_dereference(p->numa_group);
8583 unsigned long src_weight, dst_weight;
8584 int src_nid, dst_nid, dist;
8586 if (!static_branch_likely(&sched_numa_balancing))
8589 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8592 src_nid = cpu_to_node(env->src_cpu);
8593 dst_nid = cpu_to_node(env->dst_cpu);
8595 if (src_nid == dst_nid)
8598 /* Migrating away from the preferred node is always bad. */
8599 if (src_nid == p->numa_preferred_nid) {
8600 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8606 /* Encourage migration to the preferred node. */
8607 if (dst_nid == p->numa_preferred_nid)
8610 /* Leaving a core idle is often worse than degrading locality. */
8611 if (env->idle == CPU_IDLE)
8614 dist = node_distance(src_nid, dst_nid);
8616 src_weight = group_weight(p, src_nid, dist);
8617 dst_weight = group_weight(p, dst_nid, dist);
8619 src_weight = task_weight(p, src_nid, dist);
8620 dst_weight = task_weight(p, dst_nid, dist);
8623 return dst_weight < src_weight;
8627 static inline int migrate_degrades_locality(struct task_struct *p,
8635 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8638 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8642 lockdep_assert_rq_held(env->src_rq);
8645 * We do not migrate tasks that are:
8646 * 1) throttled_lb_pair, or
8647 * 2) cannot be migrated to this CPU due to cpus_ptr, or
8648 * 3) running (obviously), or
8649 * 4) are cache-hot on their current CPU.
8651 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8654 /* Disregard pcpu kthreads; they are where they need to be. */
8655 if (kthread_is_per_cpu(p))
8658 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8661 schedstat_inc(p->stats.nr_failed_migrations_affine);
8663 env->flags |= LBF_SOME_PINNED;
8666 * Remember if this task can be migrated to any other CPU in
8667 * our sched_group. We may want to revisit it if we couldn't
8668 * meet load balance goals by pulling other tasks on src_cpu.
8670 * Avoid computing new_dst_cpu
8672 * - if we have already computed one in current iteration
8673 * - if it's an active balance
8675 if (env->idle == CPU_NEWLY_IDLE ||
8676 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8679 /* Prevent to re-select dst_cpu via env's CPUs: */
8680 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8681 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8682 env->flags |= LBF_DST_PINNED;
8683 env->new_dst_cpu = cpu;
8691 /* Record that we found at least one task that could run on dst_cpu */
8692 env->flags &= ~LBF_ALL_PINNED;
8694 if (task_on_cpu(env->src_rq, p)) {
8695 schedstat_inc(p->stats.nr_failed_migrations_running);
8700 * Aggressive migration if:
8702 * 2) destination numa is preferred
8703 * 3) task is cache cold, or
8704 * 4) too many balance attempts have failed.
8706 if (env->flags & LBF_ACTIVE_LB)
8709 tsk_cache_hot = migrate_degrades_locality(p, env);
8710 if (tsk_cache_hot == -1)
8711 tsk_cache_hot = task_hot(p, env);
8713 if (tsk_cache_hot <= 0 ||
8714 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
8715 if (tsk_cache_hot == 1) {
8716 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
8717 schedstat_inc(p->stats.nr_forced_migrations);
8722 schedstat_inc(p->stats.nr_failed_migrations_hot);
8727 * detach_task() -- detach the task for the migration specified in env
8729 static void detach_task(struct task_struct *p, struct lb_env *env)
8731 lockdep_assert_rq_held(env->src_rq);
8733 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8734 set_task_cpu(p, env->dst_cpu);
8738 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8739 * part of active balancing operations within "domain".
8741 * Returns a task if successful and NULL otherwise.
8743 static struct task_struct *detach_one_task(struct lb_env *env)
8745 struct task_struct *p;
8747 lockdep_assert_rq_held(env->src_rq);
8749 list_for_each_entry_reverse(p,
8750 &env->src_rq->cfs_tasks, se.group_node) {
8751 if (!can_migrate_task(p, env))
8754 detach_task(p, env);
8757 * Right now, this is only the second place where
8758 * lb_gained[env->idle] is updated (other is detach_tasks)
8759 * so we can safely collect stats here rather than
8760 * inside detach_tasks().
8762 schedstat_inc(env->sd->lb_gained[env->idle]);
8769 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8770 * busiest_rq, as part of a balancing operation within domain "sd".
8772 * Returns number of detached tasks if successful and 0 otherwise.
8774 static int detach_tasks(struct lb_env *env)
8776 struct list_head *tasks = &env->src_rq->cfs_tasks;
8777 unsigned long util, load;
8778 struct task_struct *p;
8781 lockdep_assert_rq_held(env->src_rq);
8784 * Source run queue has been emptied by another CPU, clear
8785 * LBF_ALL_PINNED flag as we will not test any task.
8787 if (env->src_rq->nr_running <= 1) {
8788 env->flags &= ~LBF_ALL_PINNED;
8792 if (env->imbalance <= 0)
8795 while (!list_empty(tasks)) {
8797 * We don't want to steal all, otherwise we may be treated likewise,
8798 * which could at worst lead to a livelock crash.
8800 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
8805 * We've more or less seen every task there is, call it quits
8806 * unless we haven't found any movable task yet.
8808 if (env->loop > env->loop_max &&
8809 !(env->flags & LBF_ALL_PINNED))
8812 /* take a breather every nr_migrate tasks */
8813 if (env->loop > env->loop_break) {
8814 env->loop_break += SCHED_NR_MIGRATE_BREAK;
8815 env->flags |= LBF_NEED_BREAK;
8819 p = list_last_entry(tasks, struct task_struct, se.group_node);
8821 if (!can_migrate_task(p, env))
8824 switch (env->migration_type) {
8827 * Depending of the number of CPUs and tasks and the
8828 * cgroup hierarchy, task_h_load() can return a null
8829 * value. Make sure that env->imbalance decreases
8830 * otherwise detach_tasks() will stop only after
8831 * detaching up to loop_max tasks.
8833 load = max_t(unsigned long, task_h_load(p), 1);
8835 if (sched_feat(LB_MIN) &&
8836 load < 16 && !env->sd->nr_balance_failed)
8840 * Make sure that we don't migrate too much load.
8841 * Nevertheless, let relax the constraint if
8842 * scheduler fails to find a good waiting task to
8845 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
8848 env->imbalance -= load;
8852 util = task_util_est(p);
8854 if (util > env->imbalance)
8857 env->imbalance -= util;
8864 case migrate_misfit:
8865 /* This is not a misfit task */
8866 if (task_fits_cpu(p, env->src_cpu))
8873 detach_task(p, env);
8874 list_add(&p->se.group_node, &env->tasks);
8878 #ifdef CONFIG_PREEMPTION
8880 * NEWIDLE balancing is a source of latency, so preemptible
8881 * kernels will stop after the first task is detached to minimize
8882 * the critical section.
8884 if (env->idle == CPU_NEWLY_IDLE)
8889 * We only want to steal up to the prescribed amount of
8892 if (env->imbalance <= 0)
8897 list_move(&p->se.group_node, tasks);
8901 * Right now, this is one of only two places we collect this stat
8902 * so we can safely collect detach_one_task() stats here rather
8903 * than inside detach_one_task().
8905 schedstat_add(env->sd->lb_gained[env->idle], detached);
8911 * attach_task() -- attach the task detached by detach_task() to its new rq.
8913 static void attach_task(struct rq *rq, struct task_struct *p)
8915 lockdep_assert_rq_held(rq);
8917 WARN_ON_ONCE(task_rq(p) != rq);
8918 activate_task(rq, p, ENQUEUE_NOCLOCK);
8919 check_preempt_curr(rq, p, 0);
8923 * attach_one_task() -- attaches the task returned from detach_one_task() to
8926 static void attach_one_task(struct rq *rq, struct task_struct *p)
8931 update_rq_clock(rq);
8937 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8940 static void attach_tasks(struct lb_env *env)
8942 struct list_head *tasks = &env->tasks;
8943 struct task_struct *p;
8946 rq_lock(env->dst_rq, &rf);
8947 update_rq_clock(env->dst_rq);
8949 while (!list_empty(tasks)) {
8950 p = list_first_entry(tasks, struct task_struct, se.group_node);
8951 list_del_init(&p->se.group_node);
8953 attach_task(env->dst_rq, p);
8956 rq_unlock(env->dst_rq, &rf);
8959 #ifdef CONFIG_NO_HZ_COMMON
8960 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
8962 if (cfs_rq->avg.load_avg)
8965 if (cfs_rq->avg.util_avg)
8971 static inline bool others_have_blocked(struct rq *rq)
8973 if (READ_ONCE(rq->avg_rt.util_avg))
8976 if (READ_ONCE(rq->avg_dl.util_avg))
8979 if (thermal_load_avg(rq))
8982 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
8983 if (READ_ONCE(rq->avg_irq.util_avg))
8990 static inline void update_blocked_load_tick(struct rq *rq)
8992 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
8995 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
8998 rq->has_blocked_load = 0;
9001 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
9002 static inline bool others_have_blocked(struct rq *rq) { return false; }
9003 static inline void update_blocked_load_tick(struct rq *rq) {}
9004 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9007 static bool __update_blocked_others(struct rq *rq, bool *done)
9009 const struct sched_class *curr_class;
9010 u64 now = rq_clock_pelt(rq);
9011 unsigned long thermal_pressure;
9015 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9016 * DL and IRQ signals have been updated before updating CFS.
9018 curr_class = rq->curr->sched_class;
9020 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9022 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9023 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9024 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9025 update_irq_load_avg(rq, 0);
9027 if (others_have_blocked(rq))
9033 #ifdef CONFIG_FAIR_GROUP_SCHED
9035 static bool __update_blocked_fair(struct rq *rq, bool *done)
9037 struct cfs_rq *cfs_rq, *pos;
9038 bool decayed = false;
9039 int cpu = cpu_of(rq);
9042 * Iterates the task_group tree in a bottom up fashion, see
9043 * list_add_leaf_cfs_rq() for details.
9045 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9046 struct sched_entity *se;
9048 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9049 update_tg_load_avg(cfs_rq);
9051 if (cfs_rq->nr_running == 0)
9052 update_idle_cfs_rq_clock_pelt(cfs_rq);
9054 if (cfs_rq == &rq->cfs)
9058 /* Propagate pending load changes to the parent, if any: */
9059 se = cfs_rq->tg->se[cpu];
9060 if (se && !skip_blocked_update(se))
9061 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9064 * There can be a lot of idle CPU cgroups. Don't let fully
9065 * decayed cfs_rqs linger on the list.
9067 if (cfs_rq_is_decayed(cfs_rq))
9068 list_del_leaf_cfs_rq(cfs_rq);
9070 /* Don't need periodic decay once load/util_avg are null */
9071 if (cfs_rq_has_blocked(cfs_rq))
9079 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9080 * This needs to be done in a top-down fashion because the load of a child
9081 * group is a fraction of its parents load.
9083 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9085 struct rq *rq = rq_of(cfs_rq);
9086 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9087 unsigned long now = jiffies;
9090 if (cfs_rq->last_h_load_update == now)
9093 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9094 for_each_sched_entity(se) {
9095 cfs_rq = cfs_rq_of(se);
9096 WRITE_ONCE(cfs_rq->h_load_next, se);
9097 if (cfs_rq->last_h_load_update == now)
9102 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9103 cfs_rq->last_h_load_update = now;
9106 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9107 load = cfs_rq->h_load;
9108 load = div64_ul(load * se->avg.load_avg,
9109 cfs_rq_load_avg(cfs_rq) + 1);
9110 cfs_rq = group_cfs_rq(se);
9111 cfs_rq->h_load = load;
9112 cfs_rq->last_h_load_update = now;
9116 static unsigned long task_h_load(struct task_struct *p)
9118 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9120 update_cfs_rq_h_load(cfs_rq);
9121 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9122 cfs_rq_load_avg(cfs_rq) + 1);
9125 static bool __update_blocked_fair(struct rq *rq, bool *done)
9127 struct cfs_rq *cfs_rq = &rq->cfs;
9130 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9131 if (cfs_rq_has_blocked(cfs_rq))
9137 static unsigned long task_h_load(struct task_struct *p)
9139 return p->se.avg.load_avg;
9143 static void update_blocked_averages(int cpu)
9145 bool decayed = false, done = true;
9146 struct rq *rq = cpu_rq(cpu);
9149 rq_lock_irqsave(rq, &rf);
9150 update_blocked_load_tick(rq);
9151 update_rq_clock(rq);
9153 decayed |= __update_blocked_others(rq, &done);
9154 decayed |= __update_blocked_fair(rq, &done);
9156 update_blocked_load_status(rq, !done);
9158 cpufreq_update_util(rq, 0);
9159 rq_unlock_irqrestore(rq, &rf);
9162 /********** Helpers for find_busiest_group ************************/
9165 * sg_lb_stats - stats of a sched_group required for load_balancing
9167 struct sg_lb_stats {
9168 unsigned long avg_load; /*Avg load across the CPUs of the group */
9169 unsigned long group_load; /* Total load over the CPUs of the group */
9170 unsigned long group_capacity;
9171 unsigned long group_util; /* Total utilization over the CPUs of the group */
9172 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9173 unsigned int sum_nr_running; /* Nr of tasks running in the group */
9174 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9175 unsigned int idle_cpus;
9176 unsigned int group_weight;
9177 enum group_type group_type;
9178 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9179 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9180 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9181 #ifdef CONFIG_NUMA_BALANCING
9182 unsigned int nr_numa_running;
9183 unsigned int nr_preferred_running;
9188 * sd_lb_stats - Structure to store the statistics of a sched_domain
9189 * during load balancing.
9191 struct sd_lb_stats {
9192 struct sched_group *busiest; /* Busiest group in this sd */
9193 struct sched_group *local; /* Local group in this sd */
9194 unsigned long total_load; /* Total load of all groups in sd */
9195 unsigned long total_capacity; /* Total capacity of all groups in sd */
9196 unsigned long avg_load; /* Average load across all groups in sd */
9197 unsigned int prefer_sibling; /* tasks should go to sibling first */
9199 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9200 struct sg_lb_stats local_stat; /* Statistics of the local group */
9203 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9206 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9207 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9208 * We must however set busiest_stat::group_type and
9209 * busiest_stat::idle_cpus to the worst busiest group because
9210 * update_sd_pick_busiest() reads these before assignment.
9212 *sds = (struct sd_lb_stats){
9216 .total_capacity = 0UL,
9218 .idle_cpus = UINT_MAX,
9219 .group_type = group_has_spare,
9224 static unsigned long scale_rt_capacity(int cpu)
9226 struct rq *rq = cpu_rq(cpu);
9227 unsigned long max = arch_scale_cpu_capacity(cpu);
9228 unsigned long used, free;
9231 irq = cpu_util_irq(rq);
9233 if (unlikely(irq >= max))
9237 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9238 * (running and not running) with weights 0 and 1024 respectively.
9239 * avg_thermal.load_avg tracks thermal pressure and the weighted
9240 * average uses the actual delta max capacity(load).
9242 used = READ_ONCE(rq->avg_rt.util_avg);
9243 used += READ_ONCE(rq->avg_dl.util_avg);
9244 used += thermal_load_avg(rq);
9246 if (unlikely(used >= max))
9251 return scale_irq_capacity(free, irq, max);
9254 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9256 unsigned long capacity = scale_rt_capacity(cpu);
9257 struct sched_group *sdg = sd->groups;
9259 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
9264 cpu_rq(cpu)->cpu_capacity = capacity;
9265 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9267 sdg->sgc->capacity = capacity;
9268 sdg->sgc->min_capacity = capacity;
9269 sdg->sgc->max_capacity = capacity;
9272 void update_group_capacity(struct sched_domain *sd, int cpu)
9274 struct sched_domain *child = sd->child;
9275 struct sched_group *group, *sdg = sd->groups;
9276 unsigned long capacity, min_capacity, max_capacity;
9277 unsigned long interval;
9279 interval = msecs_to_jiffies(sd->balance_interval);
9280 interval = clamp(interval, 1UL, max_load_balance_interval);
9281 sdg->sgc->next_update = jiffies + interval;
9284 update_cpu_capacity(sd, cpu);
9289 min_capacity = ULONG_MAX;
9292 if (child->flags & SD_OVERLAP) {
9294 * SD_OVERLAP domains cannot assume that child groups
9295 * span the current group.
9298 for_each_cpu(cpu, sched_group_span(sdg)) {
9299 unsigned long cpu_cap = capacity_of(cpu);
9301 capacity += cpu_cap;
9302 min_capacity = min(cpu_cap, min_capacity);
9303 max_capacity = max(cpu_cap, max_capacity);
9307 * !SD_OVERLAP domains can assume that child groups
9308 * span the current group.
9311 group = child->groups;
9313 struct sched_group_capacity *sgc = group->sgc;
9315 capacity += sgc->capacity;
9316 min_capacity = min(sgc->min_capacity, min_capacity);
9317 max_capacity = max(sgc->max_capacity, max_capacity);
9318 group = group->next;
9319 } while (group != child->groups);
9322 sdg->sgc->capacity = capacity;
9323 sdg->sgc->min_capacity = min_capacity;
9324 sdg->sgc->max_capacity = max_capacity;
9328 * Check whether the capacity of the rq has been noticeably reduced by side
9329 * activity. The imbalance_pct is used for the threshold.
9330 * Return true is the capacity is reduced
9333 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9335 return ((rq->cpu_capacity * sd->imbalance_pct) <
9336 (rq->cpu_capacity_orig * 100));
9340 * Check whether a rq has a misfit task and if it looks like we can actually
9341 * help that task: we can migrate the task to a CPU of higher capacity, or
9342 * the task's current CPU is heavily pressured.
9344 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9346 return rq->misfit_task_load &&
9347 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
9348 check_cpu_capacity(rq, sd));
9352 * Group imbalance indicates (and tries to solve) the problem where balancing
9353 * groups is inadequate due to ->cpus_ptr constraints.
9355 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9356 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9359 * { 0 1 2 3 } { 4 5 6 7 }
9362 * If we were to balance group-wise we'd place two tasks in the first group and
9363 * two tasks in the second group. Clearly this is undesired as it will overload
9364 * cpu 3 and leave one of the CPUs in the second group unused.
9366 * The current solution to this issue is detecting the skew in the first group
9367 * by noticing the lower domain failed to reach balance and had difficulty
9368 * moving tasks due to affinity constraints.
9370 * When this is so detected; this group becomes a candidate for busiest; see
9371 * update_sd_pick_busiest(). And calculate_imbalance() and
9372 * find_busiest_group() avoid some of the usual balance conditions to allow it
9373 * to create an effective group imbalance.
9375 * This is a somewhat tricky proposition since the next run might not find the
9376 * group imbalance and decide the groups need to be balanced again. A most
9377 * subtle and fragile situation.
9380 static inline int sg_imbalanced(struct sched_group *group)
9382 return group->sgc->imbalance;
9386 * group_has_capacity returns true if the group has spare capacity that could
9387 * be used by some tasks.
9388 * We consider that a group has spare capacity if the number of task is
9389 * smaller than the number of CPUs or if the utilization is lower than the
9390 * available capacity for CFS tasks.
9391 * For the latter, we use a threshold to stabilize the state, to take into
9392 * account the variance of the tasks' load and to return true if the available
9393 * capacity in meaningful for the load balancer.
9394 * As an example, an available capacity of 1% can appear but it doesn't make
9395 * any benefit for the load balance.
9398 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9400 if (sgs->sum_nr_running < sgs->group_weight)
9403 if ((sgs->group_capacity * imbalance_pct) <
9404 (sgs->group_runnable * 100))
9407 if ((sgs->group_capacity * 100) >
9408 (sgs->group_util * imbalance_pct))
9415 * group_is_overloaded returns true if the group has more tasks than it can
9417 * group_is_overloaded is not equals to !group_has_capacity because a group
9418 * with the exact right number of tasks, has no more spare capacity but is not
9419 * overloaded so both group_has_capacity and group_is_overloaded return
9423 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9425 if (sgs->sum_nr_running <= sgs->group_weight)
9428 if ((sgs->group_capacity * 100) <
9429 (sgs->group_util * imbalance_pct))
9432 if ((sgs->group_capacity * imbalance_pct) <
9433 (sgs->group_runnable * 100))
9440 group_type group_classify(unsigned int imbalance_pct,
9441 struct sched_group *group,
9442 struct sg_lb_stats *sgs)
9444 if (group_is_overloaded(imbalance_pct, sgs))
9445 return group_overloaded;
9447 if (sg_imbalanced(group))
9448 return group_imbalanced;
9450 if (sgs->group_asym_packing)
9451 return group_asym_packing;
9453 if (sgs->group_smt_balance)
9454 return group_smt_balance;
9456 if (sgs->group_misfit_task_load)
9457 return group_misfit_task;
9459 if (!group_has_capacity(imbalance_pct, sgs))
9460 return group_fully_busy;
9462 return group_has_spare;
9466 * sched_use_asym_prio - Check whether asym_packing priority must be used
9467 * @sd: The scheduling domain of the load balancing
9470 * Always use CPU priority when balancing load between SMT siblings. When
9471 * balancing load between cores, it is not sufficient that @cpu is idle. Only
9472 * use CPU priority if the whole core is idle.
9474 * Returns: True if the priority of @cpu must be followed. False otherwise.
9476 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9478 if (!sched_smt_active())
9481 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9485 * sched_asym - Check if the destination CPU can do asym_packing load balance
9486 * @env: The load balancing environment
9487 * @sds: Load-balancing data with statistics of the local group
9488 * @sgs: Load-balancing statistics of the candidate busiest group
9489 * @group: The candidate busiest group
9491 * @env::dst_cpu can do asym_packing if it has higher priority than the
9492 * preferred CPU of @group.
9494 * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9495 * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9496 * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9497 * imbalances in the number of CPUS are dealt with in find_busiest_group().
9499 * If we are balancing load within an SMT core, or at DIE domain level, always
9502 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9506 sched_asym(struct lb_env *env, struct sd_lb_stats *sds, struct sg_lb_stats *sgs,
9507 struct sched_group *group)
9509 /* Ensure that the whole local core is idle, if applicable. */
9510 if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9514 * CPU priorities does not make sense for SMT cores with more than one
9517 if (group->flags & SD_SHARE_CPUCAPACITY) {
9518 if (sgs->group_weight - sgs->idle_cpus != 1)
9522 return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9525 /* One group has more than one SMT CPU while the other group does not */
9526 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9527 struct sched_group *sg2)
9532 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9533 (sg2->flags & SD_SHARE_CPUCAPACITY);
9536 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9537 struct sched_group *group)
9539 if (env->idle == CPU_NOT_IDLE)
9543 * For SMT source group, it is better to move a task
9544 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9545 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9548 if (group->flags & SD_SHARE_CPUCAPACITY &&
9549 sgs->sum_h_nr_running > 1)
9555 static inline long sibling_imbalance(struct lb_env *env,
9556 struct sd_lb_stats *sds,
9557 struct sg_lb_stats *busiest,
9558 struct sg_lb_stats *local)
9560 int ncores_busiest, ncores_local;
9563 if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9566 ncores_busiest = sds->busiest->cores;
9567 ncores_local = sds->local->cores;
9569 if (ncores_busiest == ncores_local) {
9570 imbalance = busiest->sum_nr_running;
9571 lsub_positive(&imbalance, local->sum_nr_running);
9575 /* Balance such that nr_running/ncores ratio are same on both groups */
9576 imbalance = ncores_local * busiest->sum_nr_running;
9577 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9578 /* Normalize imbalance and do rounding on normalization */
9579 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9580 imbalance /= ncores_local + ncores_busiest;
9582 /* Take advantage of resource in an empty sched group */
9583 if (imbalance <= 1 && local->sum_nr_running == 0 &&
9584 busiest->sum_nr_running > 1)
9591 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9594 * When there is more than 1 task, the group_overloaded case already
9595 * takes care of cpu with reduced capacity
9597 if (rq->cfs.h_nr_running != 1)
9600 return check_cpu_capacity(rq, sd);
9604 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9605 * @env: The load balancing environment.
9606 * @sds: Load-balancing data with statistics of the local group.
9607 * @group: sched_group whose statistics are to be updated.
9608 * @sgs: variable to hold the statistics for this group.
9609 * @sg_status: Holds flag indicating the status of the sched_group
9611 static inline void update_sg_lb_stats(struct lb_env *env,
9612 struct sd_lb_stats *sds,
9613 struct sched_group *group,
9614 struct sg_lb_stats *sgs,
9617 int i, nr_running, local_group;
9619 memset(sgs, 0, sizeof(*sgs));
9621 local_group = group == sds->local;
9623 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9624 struct rq *rq = cpu_rq(i);
9625 unsigned long load = cpu_load(rq);
9627 sgs->group_load += load;
9628 sgs->group_util += cpu_util_cfs(i);
9629 sgs->group_runnable += cpu_runnable(rq);
9630 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9632 nr_running = rq->nr_running;
9633 sgs->sum_nr_running += nr_running;
9636 *sg_status |= SG_OVERLOAD;
9638 if (cpu_overutilized(i))
9639 *sg_status |= SG_OVERUTILIZED;
9641 #ifdef CONFIG_NUMA_BALANCING
9642 sgs->nr_numa_running += rq->nr_numa_running;
9643 sgs->nr_preferred_running += rq->nr_preferred_running;
9646 * No need to call idle_cpu() if nr_running is not 0
9648 if (!nr_running && idle_cpu(i)) {
9650 /* Idle cpu can't have misfit task */
9657 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9658 /* Check for a misfit task on the cpu */
9659 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9660 sgs->group_misfit_task_load = rq->misfit_task_load;
9661 *sg_status |= SG_OVERLOAD;
9663 } else if ((env->idle != CPU_NOT_IDLE) &&
9664 sched_reduced_capacity(rq, env->sd)) {
9665 /* Check for a task running on a CPU with reduced capacity */
9666 if (sgs->group_misfit_task_load < load)
9667 sgs->group_misfit_task_load = load;
9671 sgs->group_capacity = group->sgc->capacity;
9673 sgs->group_weight = group->group_weight;
9675 /* Check if dst CPU is idle and preferred to this group */
9676 if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9677 env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9678 sched_asym(env, sds, sgs, group)) {
9679 sgs->group_asym_packing = 1;
9682 /* Check for loaded SMT group to be balanced to dst CPU */
9683 if (!local_group && smt_balance(env, sgs, group))
9684 sgs->group_smt_balance = 1;
9686 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
9688 /* Computing avg_load makes sense only when group is overloaded */
9689 if (sgs->group_type == group_overloaded)
9690 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9691 sgs->group_capacity;
9695 * update_sd_pick_busiest - return 1 on busiest group
9696 * @env: The load balancing environment.
9697 * @sds: sched_domain statistics
9698 * @sg: sched_group candidate to be checked for being the busiest
9699 * @sgs: sched_group statistics
9701 * Determine if @sg is a busier group than the previously selected
9704 * Return: %true if @sg is a busier group than the previously selected
9705 * busiest group. %false otherwise.
9707 static bool update_sd_pick_busiest(struct lb_env *env,
9708 struct sd_lb_stats *sds,
9709 struct sched_group *sg,
9710 struct sg_lb_stats *sgs)
9712 struct sg_lb_stats *busiest = &sds->busiest_stat;
9714 /* Make sure that there is at least one task to pull */
9715 if (!sgs->sum_h_nr_running)
9719 * Don't try to pull misfit tasks we can't help.
9720 * We can use max_capacity here as reduction in capacity on some
9721 * CPUs in the group should either be possible to resolve
9722 * internally or be covered by avg_load imbalance (eventually).
9724 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9725 (sgs->group_type == group_misfit_task) &&
9726 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
9727 sds->local_stat.group_type != group_has_spare))
9730 if (sgs->group_type > busiest->group_type)
9733 if (sgs->group_type < busiest->group_type)
9737 * The candidate and the current busiest group are the same type of
9738 * group. Let check which one is the busiest according to the type.
9741 switch (sgs->group_type) {
9742 case group_overloaded:
9743 /* Select the overloaded group with highest avg_load. */
9744 if (sgs->avg_load <= busiest->avg_load)
9748 case group_imbalanced:
9750 * Select the 1st imbalanced group as we don't have any way to
9751 * choose one more than another.
9755 case group_asym_packing:
9756 /* Prefer to move from lowest priority CPU's work */
9757 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
9761 case group_misfit_task:
9763 * If we have more than one misfit sg go with the biggest
9766 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
9770 case group_smt_balance:
9772 * Check if we have spare CPUs on either SMT group to
9773 * choose has spare or fully busy handling.
9775 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
9780 case group_fully_busy:
9782 * Select the fully busy group with highest avg_load. In
9783 * theory, there is no need to pull task from such kind of
9784 * group because tasks have all compute capacity that they need
9785 * but we can still improve the overall throughput by reducing
9786 * contention when accessing shared HW resources.
9788 * XXX for now avg_load is not computed and always 0 so we
9789 * select the 1st one, except if @sg is composed of SMT
9793 if (sgs->avg_load < busiest->avg_load)
9796 if (sgs->avg_load == busiest->avg_load) {
9798 * SMT sched groups need more help than non-SMT groups.
9799 * If @sg happens to also be SMT, either choice is good.
9801 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
9807 case group_has_spare:
9809 * Do not pick sg with SMT CPUs over sg with pure CPUs,
9810 * as we do not want to pull task off SMT core with one task
9811 * and make the core idle.
9813 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
9814 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
9822 * Select not overloaded group with lowest number of idle cpus
9823 * and highest number of running tasks. We could also compare
9824 * the spare capacity which is more stable but it can end up
9825 * that the group has less spare capacity but finally more idle
9826 * CPUs which means less opportunity to pull tasks.
9828 if (sgs->idle_cpus > busiest->idle_cpus)
9830 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
9831 (sgs->sum_nr_running <= busiest->sum_nr_running))
9838 * Candidate sg has no more than one task per CPU and has higher
9839 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
9840 * throughput. Maximize throughput, power/energy consequences are not
9843 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9844 (sgs->group_type <= group_fully_busy) &&
9845 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
9851 #ifdef CONFIG_NUMA_BALANCING
9852 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9854 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
9856 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
9861 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9863 if (rq->nr_running > rq->nr_numa_running)
9865 if (rq->nr_running > rq->nr_preferred_running)
9870 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9875 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9879 #endif /* CONFIG_NUMA_BALANCING */
9885 * task_running_on_cpu - return 1 if @p is running on @cpu.
9888 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
9890 /* Task has no contribution or is new */
9891 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9894 if (task_on_rq_queued(p))
9901 * idle_cpu_without - would a given CPU be idle without p ?
9902 * @cpu: the processor on which idleness is tested.
9903 * @p: task which should be ignored.
9905 * Return: 1 if the CPU would be idle. 0 otherwise.
9907 static int idle_cpu_without(int cpu, struct task_struct *p)
9909 struct rq *rq = cpu_rq(cpu);
9911 if (rq->curr != rq->idle && rq->curr != p)
9915 * rq->nr_running can't be used but an updated version without the
9916 * impact of p on cpu must be used instead. The updated nr_running
9917 * be computed and tested before calling idle_cpu_without().
9921 if (rq->ttwu_pending)
9929 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
9930 * @sd: The sched_domain level to look for idlest group.
9931 * @group: sched_group whose statistics are to be updated.
9932 * @sgs: variable to hold the statistics for this group.
9933 * @p: The task for which we look for the idlest group/CPU.
9935 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
9936 struct sched_group *group,
9937 struct sg_lb_stats *sgs,
9938 struct task_struct *p)
9942 memset(sgs, 0, sizeof(*sgs));
9944 /* Assume that task can't fit any CPU of the group */
9945 if (sd->flags & SD_ASYM_CPUCAPACITY)
9946 sgs->group_misfit_task_load = 1;
9948 for_each_cpu(i, sched_group_span(group)) {
9949 struct rq *rq = cpu_rq(i);
9952 sgs->group_load += cpu_load_without(rq, p);
9953 sgs->group_util += cpu_util_without(i, p);
9954 sgs->group_runnable += cpu_runnable_without(rq, p);
9955 local = task_running_on_cpu(i, p);
9956 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
9958 nr_running = rq->nr_running - local;
9959 sgs->sum_nr_running += nr_running;
9962 * No need to call idle_cpu_without() if nr_running is not 0
9964 if (!nr_running && idle_cpu_without(i, p))
9967 /* Check if task fits in the CPU */
9968 if (sd->flags & SD_ASYM_CPUCAPACITY &&
9969 sgs->group_misfit_task_load &&
9970 task_fits_cpu(p, i))
9971 sgs->group_misfit_task_load = 0;
9975 sgs->group_capacity = group->sgc->capacity;
9977 sgs->group_weight = group->group_weight;
9979 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
9982 * Computing avg_load makes sense only when group is fully busy or
9985 if (sgs->group_type == group_fully_busy ||
9986 sgs->group_type == group_overloaded)
9987 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9988 sgs->group_capacity;
9991 static bool update_pick_idlest(struct sched_group *idlest,
9992 struct sg_lb_stats *idlest_sgs,
9993 struct sched_group *group,
9994 struct sg_lb_stats *sgs)
9996 if (sgs->group_type < idlest_sgs->group_type)
9999 if (sgs->group_type > idlest_sgs->group_type)
10003 * The candidate and the current idlest group are the same type of
10004 * group. Let check which one is the idlest according to the type.
10007 switch (sgs->group_type) {
10008 case group_overloaded:
10009 case group_fully_busy:
10010 /* Select the group with lowest avg_load. */
10011 if (idlest_sgs->avg_load <= sgs->avg_load)
10015 case group_imbalanced:
10016 case group_asym_packing:
10017 case group_smt_balance:
10018 /* Those types are not used in the slow wakeup path */
10021 case group_misfit_task:
10022 /* Select group with the highest max capacity */
10023 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10027 case group_has_spare:
10028 /* Select group with most idle CPUs */
10029 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10032 /* Select group with lowest group_util */
10033 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10034 idlest_sgs->group_util <= sgs->group_util)
10044 * find_idlest_group() finds and returns the least busy CPU group within the
10047 * Assumes p is allowed on at least one CPU in sd.
10049 static struct sched_group *
10050 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10052 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10053 struct sg_lb_stats local_sgs, tmp_sgs;
10054 struct sg_lb_stats *sgs;
10055 unsigned long imbalance;
10056 struct sg_lb_stats idlest_sgs = {
10057 .avg_load = UINT_MAX,
10058 .group_type = group_overloaded,
10064 /* Skip over this group if it has no CPUs allowed */
10065 if (!cpumask_intersects(sched_group_span(group),
10069 /* Skip over this group if no cookie matched */
10070 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10073 local_group = cpumask_test_cpu(this_cpu,
10074 sched_group_span(group));
10083 update_sg_wakeup_stats(sd, group, sgs, p);
10085 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10090 } while (group = group->next, group != sd->groups);
10093 /* There is no idlest group to push tasks to */
10097 /* The local group has been skipped because of CPU affinity */
10102 * If the local group is idler than the selected idlest group
10103 * don't try and push the task.
10105 if (local_sgs.group_type < idlest_sgs.group_type)
10109 * If the local group is busier than the selected idlest group
10110 * try and push the task.
10112 if (local_sgs.group_type > idlest_sgs.group_type)
10115 switch (local_sgs.group_type) {
10116 case group_overloaded:
10117 case group_fully_busy:
10119 /* Calculate allowed imbalance based on load */
10120 imbalance = scale_load_down(NICE_0_LOAD) *
10121 (sd->imbalance_pct-100) / 100;
10124 * When comparing groups across NUMA domains, it's possible for
10125 * the local domain to be very lightly loaded relative to the
10126 * remote domains but "imbalance" skews the comparison making
10127 * remote CPUs look much more favourable. When considering
10128 * cross-domain, add imbalance to the load on the remote node
10129 * and consider staying local.
10132 if ((sd->flags & SD_NUMA) &&
10133 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10137 * If the local group is less loaded than the selected
10138 * idlest group don't try and push any tasks.
10140 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10143 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10147 case group_imbalanced:
10148 case group_asym_packing:
10149 case group_smt_balance:
10150 /* Those type are not used in the slow wakeup path */
10153 case group_misfit_task:
10154 /* Select group with the highest max capacity */
10155 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10159 case group_has_spare:
10161 if (sd->flags & SD_NUMA) {
10162 int imb_numa_nr = sd->imb_numa_nr;
10163 #ifdef CONFIG_NUMA_BALANCING
10166 * If there is spare capacity at NUMA, try to select
10167 * the preferred node
10169 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10172 idlest_cpu = cpumask_first(sched_group_span(idlest));
10173 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10175 #endif /* CONFIG_NUMA_BALANCING */
10177 * Otherwise, keep the task close to the wakeup source
10178 * and improve locality if the number of running tasks
10179 * would remain below threshold where an imbalance is
10180 * allowed while accounting for the possibility the
10181 * task is pinned to a subset of CPUs. If there is a
10182 * real need of migration, periodic load balance will
10185 if (p->nr_cpus_allowed != NR_CPUS) {
10186 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10188 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10189 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10192 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10193 if (!adjust_numa_imbalance(imbalance,
10194 local_sgs.sum_nr_running + 1,
10199 #endif /* CONFIG_NUMA */
10202 * Select group with highest number of idle CPUs. We could also
10203 * compare the utilization which is more stable but it can end
10204 * up that the group has less spare capacity but finally more
10205 * idle CPUs which means more opportunity to run task.
10207 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10215 static void update_idle_cpu_scan(struct lb_env *env,
10216 unsigned long sum_util)
10218 struct sched_domain_shared *sd_share;
10219 int llc_weight, pct;
10222 * Update the number of CPUs to scan in LLC domain, which could
10223 * be used as a hint in select_idle_cpu(). The update of sd_share
10224 * could be expensive because it is within a shared cache line.
10225 * So the write of this hint only occurs during periodic load
10226 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10227 * can fire way more frequently than the former.
10229 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10232 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10233 if (env->sd->span_weight != llc_weight)
10236 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10241 * The number of CPUs to search drops as sum_util increases, when
10242 * sum_util hits 85% or above, the scan stops.
10243 * The reason to choose 85% as the threshold is because this is the
10244 * imbalance_pct(117) when a LLC sched group is overloaded.
10246 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10247 * and y'= y / SCHED_CAPACITY_SCALE
10249 * x is the ratio of sum_util compared to the CPU capacity:
10250 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10251 * y' is the ratio of CPUs to be scanned in the LLC domain,
10252 * and the number of CPUs to scan is calculated by:
10254 * nr_scan = llc_weight * y' [2]
10256 * When x hits the threshold of overloaded, AKA, when
10257 * x = 100 / pct, y drops to 0. According to [1],
10258 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10260 * Scale x by SCHED_CAPACITY_SCALE:
10261 * x' = sum_util / llc_weight; [3]
10263 * and finally [1] becomes:
10264 * y = SCHED_CAPACITY_SCALE -
10265 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10270 do_div(x, llc_weight);
10273 pct = env->sd->imbalance_pct;
10274 tmp = x * x * pct * pct;
10275 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10276 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10277 y = SCHED_CAPACITY_SCALE - tmp;
10281 do_div(y, SCHED_CAPACITY_SCALE);
10282 if ((int)y != sd_share->nr_idle_scan)
10283 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10287 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10288 * @env: The load balancing environment.
10289 * @sds: variable to hold the statistics for this sched_domain.
10292 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10294 struct sched_group *sg = env->sd->groups;
10295 struct sg_lb_stats *local = &sds->local_stat;
10296 struct sg_lb_stats tmp_sgs;
10297 unsigned long sum_util = 0;
10301 struct sg_lb_stats *sgs = &tmp_sgs;
10304 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10309 if (env->idle != CPU_NEWLY_IDLE ||
10310 time_after_eq(jiffies, sg->sgc->next_update))
10311 update_group_capacity(env->sd, env->dst_cpu);
10314 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10320 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10322 sds->busiest_stat = *sgs;
10326 /* Now, start updating sd_lb_stats */
10327 sds->total_load += sgs->group_load;
10328 sds->total_capacity += sgs->group_capacity;
10330 sum_util += sgs->group_util;
10332 } while (sg != env->sd->groups);
10335 * Indicate that the child domain of the busiest group prefers tasks
10336 * go to a child's sibling domains first. NB the flags of a sched group
10337 * are those of the child domain.
10340 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10343 if (env->sd->flags & SD_NUMA)
10344 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10346 if (!env->sd->parent) {
10347 struct root_domain *rd = env->dst_rq->rd;
10349 /* update overload indicator if we are at root domain */
10350 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10352 /* Update over-utilization (tipping point, U >= 0) indicator */
10353 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10354 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10355 } else if (sg_status & SG_OVERUTILIZED) {
10356 struct root_domain *rd = env->dst_rq->rd;
10358 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10359 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10362 update_idle_cpu_scan(env, sum_util);
10366 * calculate_imbalance - Calculate the amount of imbalance present within the
10367 * groups of a given sched_domain during load balance.
10368 * @env: load balance environment
10369 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10371 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10373 struct sg_lb_stats *local, *busiest;
10375 local = &sds->local_stat;
10376 busiest = &sds->busiest_stat;
10378 if (busiest->group_type == group_misfit_task) {
10379 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10380 /* Set imbalance to allow misfit tasks to be balanced. */
10381 env->migration_type = migrate_misfit;
10382 env->imbalance = 1;
10385 * Set load imbalance to allow moving task from cpu
10386 * with reduced capacity.
10388 env->migration_type = migrate_load;
10389 env->imbalance = busiest->group_misfit_task_load;
10394 if (busiest->group_type == group_asym_packing) {
10396 * In case of asym capacity, we will try to migrate all load to
10397 * the preferred CPU.
10399 env->migration_type = migrate_task;
10400 env->imbalance = busiest->sum_h_nr_running;
10404 if (busiest->group_type == group_smt_balance) {
10405 /* Reduce number of tasks sharing CPU capacity */
10406 env->migration_type = migrate_task;
10407 env->imbalance = 1;
10411 if (busiest->group_type == group_imbalanced) {
10413 * In the group_imb case we cannot rely on group-wide averages
10414 * to ensure CPU-load equilibrium, try to move any task to fix
10415 * the imbalance. The next load balance will take care of
10416 * balancing back the system.
10418 env->migration_type = migrate_task;
10419 env->imbalance = 1;
10424 * Try to use spare capacity of local group without overloading it or
10425 * emptying busiest.
10427 if (local->group_type == group_has_spare) {
10428 if ((busiest->group_type > group_fully_busy) &&
10429 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10431 * If busiest is overloaded, try to fill spare
10432 * capacity. This might end up creating spare capacity
10433 * in busiest or busiest still being overloaded but
10434 * there is no simple way to directly compute the
10435 * amount of load to migrate in order to balance the
10438 env->migration_type = migrate_util;
10439 env->imbalance = max(local->group_capacity, local->group_util) -
10443 * In some cases, the group's utilization is max or even
10444 * higher than capacity because of migrations but the
10445 * local CPU is (newly) idle. There is at least one
10446 * waiting task in this overloaded busiest group. Let's
10449 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10450 env->migration_type = migrate_task;
10451 env->imbalance = 1;
10457 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10459 * When prefer sibling, evenly spread running tasks on
10462 env->migration_type = migrate_task;
10463 env->imbalance = sibling_imbalance(env, sds, busiest, local);
10467 * If there is no overload, we just want to even the number of
10470 env->migration_type = migrate_task;
10471 env->imbalance = max_t(long, 0,
10472 (local->idle_cpus - busiest->idle_cpus));
10476 /* Consider allowing a small imbalance between NUMA groups */
10477 if (env->sd->flags & SD_NUMA) {
10478 env->imbalance = adjust_numa_imbalance(env->imbalance,
10479 local->sum_nr_running + 1,
10480 env->sd->imb_numa_nr);
10484 /* Number of tasks to move to restore balance */
10485 env->imbalance >>= 1;
10491 * Local is fully busy but has to take more load to relieve the
10494 if (local->group_type < group_overloaded) {
10496 * Local will become overloaded so the avg_load metrics are
10500 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10501 local->group_capacity;
10504 * If the local group is more loaded than the selected
10505 * busiest group don't try to pull any tasks.
10507 if (local->avg_load >= busiest->avg_load) {
10508 env->imbalance = 0;
10512 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10513 sds->total_capacity;
10516 * If the local group is more loaded than the average system
10517 * load, don't try to pull any tasks.
10519 if (local->avg_load >= sds->avg_load) {
10520 env->imbalance = 0;
10527 * Both group are or will become overloaded and we're trying to get all
10528 * the CPUs to the average_load, so we don't want to push ourselves
10529 * above the average load, nor do we wish to reduce the max loaded CPU
10530 * below the average load. At the same time, we also don't want to
10531 * reduce the group load below the group capacity. Thus we look for
10532 * the minimum possible imbalance.
10534 env->migration_type = migrate_load;
10535 env->imbalance = min(
10536 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10537 (sds->avg_load - local->avg_load) * local->group_capacity
10538 ) / SCHED_CAPACITY_SCALE;
10541 /******* find_busiest_group() helpers end here *********************/
10544 * Decision matrix according to the local and busiest group type:
10546 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10547 * has_spare nr_idle balanced N/A N/A balanced balanced
10548 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
10549 * misfit_task force N/A N/A N/A N/A N/A
10550 * asym_packing force force N/A N/A force force
10551 * imbalanced force force N/A N/A force force
10552 * overloaded force force N/A N/A force avg_load
10554 * N/A : Not Applicable because already filtered while updating
10556 * balanced : The system is balanced for these 2 groups.
10557 * force : Calculate the imbalance as load migration is probably needed.
10558 * avg_load : Only if imbalance is significant enough.
10559 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
10560 * different in groups.
10564 * find_busiest_group - Returns the busiest group within the sched_domain
10565 * if there is an imbalance.
10566 * @env: The load balancing environment.
10568 * Also calculates the amount of runnable load which should be moved
10569 * to restore balance.
10571 * Return: - The busiest group if imbalance exists.
10573 static struct sched_group *find_busiest_group(struct lb_env *env)
10575 struct sg_lb_stats *local, *busiest;
10576 struct sd_lb_stats sds;
10578 init_sd_lb_stats(&sds);
10581 * Compute the various statistics relevant for load balancing at
10584 update_sd_lb_stats(env, &sds);
10586 /* There is no busy sibling group to pull tasks from */
10590 busiest = &sds.busiest_stat;
10592 /* Misfit tasks should be dealt with regardless of the avg load */
10593 if (busiest->group_type == group_misfit_task)
10594 goto force_balance;
10596 if (sched_energy_enabled()) {
10597 struct root_domain *rd = env->dst_rq->rd;
10599 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10603 /* ASYM feature bypasses nice load balance check */
10604 if (busiest->group_type == group_asym_packing)
10605 goto force_balance;
10608 * If the busiest group is imbalanced the below checks don't
10609 * work because they assume all things are equal, which typically
10610 * isn't true due to cpus_ptr constraints and the like.
10612 if (busiest->group_type == group_imbalanced)
10613 goto force_balance;
10615 local = &sds.local_stat;
10617 * If the local group is busier than the selected busiest group
10618 * don't try and pull any tasks.
10620 if (local->group_type > busiest->group_type)
10624 * When groups are overloaded, use the avg_load to ensure fairness
10627 if (local->group_type == group_overloaded) {
10629 * If the local group is more loaded than the selected
10630 * busiest group don't try to pull any tasks.
10632 if (local->avg_load >= busiest->avg_load)
10635 /* XXX broken for overlapping NUMA groups */
10636 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10637 sds.total_capacity;
10640 * Don't pull any tasks if this group is already above the
10641 * domain average load.
10643 if (local->avg_load >= sds.avg_load)
10647 * If the busiest group is more loaded, use imbalance_pct to be
10650 if (100 * busiest->avg_load <=
10651 env->sd->imbalance_pct * local->avg_load)
10656 * Try to move all excess tasks to a sibling domain of the busiest
10657 * group's child domain.
10659 if (sds.prefer_sibling && local->group_type == group_has_spare &&
10660 sibling_imbalance(env, &sds, busiest, local) > 1)
10661 goto force_balance;
10663 if (busiest->group_type != group_overloaded) {
10664 if (env->idle == CPU_NOT_IDLE) {
10666 * If the busiest group is not overloaded (and as a
10667 * result the local one too) but this CPU is already
10668 * busy, let another idle CPU try to pull task.
10673 if (busiest->group_type == group_smt_balance &&
10674 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10675 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10676 goto force_balance;
10679 if (busiest->group_weight > 1 &&
10680 local->idle_cpus <= (busiest->idle_cpus + 1)) {
10682 * If the busiest group is not overloaded
10683 * and there is no imbalance between this and busiest
10684 * group wrt idle CPUs, it is balanced. The imbalance
10685 * becomes significant if the diff is greater than 1
10686 * otherwise we might end up to just move the imbalance
10687 * on another group. Of course this applies only if
10688 * there is more than 1 CPU per group.
10693 if (busiest->sum_h_nr_running == 1) {
10695 * busiest doesn't have any tasks waiting to run
10702 /* Looks like there is an imbalance. Compute it */
10703 calculate_imbalance(env, &sds);
10704 return env->imbalance ? sds.busiest : NULL;
10707 env->imbalance = 0;
10712 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
10714 static struct rq *find_busiest_queue(struct lb_env *env,
10715 struct sched_group *group)
10717 struct rq *busiest = NULL, *rq;
10718 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
10719 unsigned int busiest_nr = 0;
10722 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10723 unsigned long capacity, load, util;
10724 unsigned int nr_running;
10728 rt = fbq_classify_rq(rq);
10731 * We classify groups/runqueues into three groups:
10732 * - regular: there are !numa tasks
10733 * - remote: there are numa tasks that run on the 'wrong' node
10734 * - all: there is no distinction
10736 * In order to avoid migrating ideally placed numa tasks,
10737 * ignore those when there's better options.
10739 * If we ignore the actual busiest queue to migrate another
10740 * task, the next balance pass can still reduce the busiest
10741 * queue by moving tasks around inside the node.
10743 * If we cannot move enough load due to this classification
10744 * the next pass will adjust the group classification and
10745 * allow migration of more tasks.
10747 * Both cases only affect the total convergence complexity.
10749 if (rt > env->fbq_type)
10752 nr_running = rq->cfs.h_nr_running;
10756 capacity = capacity_of(i);
10759 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
10760 * eventually lead to active_balancing high->low capacity.
10761 * Higher per-CPU capacity is considered better than balancing
10764 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
10765 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
10770 * Make sure we only pull tasks from a CPU of lower priority
10771 * when balancing between SMT siblings.
10773 * If balancing between cores, let lower priority CPUs help
10774 * SMT cores with more than one busy sibling.
10776 if ((env->sd->flags & SD_ASYM_PACKING) &&
10777 sched_use_asym_prio(env->sd, i) &&
10778 sched_asym_prefer(i, env->dst_cpu) &&
10782 switch (env->migration_type) {
10785 * When comparing with load imbalance, use cpu_load()
10786 * which is not scaled with the CPU capacity.
10788 load = cpu_load(rq);
10790 if (nr_running == 1 && load > env->imbalance &&
10791 !check_cpu_capacity(rq, env->sd))
10795 * For the load comparisons with the other CPUs,
10796 * consider the cpu_load() scaled with the CPU
10797 * capacity, so that the load can be moved away
10798 * from the CPU that is potentially running at a
10801 * Thus we're looking for max(load_i / capacity_i),
10802 * crosswise multiplication to rid ourselves of the
10803 * division works out to:
10804 * load_i * capacity_j > load_j * capacity_i;
10805 * where j is our previous maximum.
10807 if (load * busiest_capacity > busiest_load * capacity) {
10808 busiest_load = load;
10809 busiest_capacity = capacity;
10815 util = cpu_util_cfs_boost(i);
10818 * Don't try to pull utilization from a CPU with one
10819 * running task. Whatever its utilization, we will fail
10822 if (nr_running <= 1)
10825 if (busiest_util < util) {
10826 busiest_util = util;
10832 if (busiest_nr < nr_running) {
10833 busiest_nr = nr_running;
10838 case migrate_misfit:
10840 * For ASYM_CPUCAPACITY domains with misfit tasks we
10841 * simply seek the "biggest" misfit task.
10843 if (rq->misfit_task_load > busiest_load) {
10844 busiest_load = rq->misfit_task_load;
10857 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
10858 * so long as it is large enough.
10860 #define MAX_PINNED_INTERVAL 512
10863 asym_active_balance(struct lb_env *env)
10866 * ASYM_PACKING needs to force migrate tasks from busy but lower
10867 * priority CPUs in order to pack all tasks in the highest priority
10868 * CPUs. When done between cores, do it only if the whole core if the
10869 * whole core is idle.
10871 * If @env::src_cpu is an SMT core with busy siblings, let
10872 * the lower priority @env::dst_cpu help it. Do not follow
10875 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
10876 sched_use_asym_prio(env->sd, env->dst_cpu) &&
10877 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
10878 !sched_use_asym_prio(env->sd, env->src_cpu));
10882 imbalanced_active_balance(struct lb_env *env)
10884 struct sched_domain *sd = env->sd;
10887 * The imbalanced case includes the case of pinned tasks preventing a fair
10888 * distribution of the load on the system but also the even distribution of the
10889 * threads on a system with spare capacity
10891 if ((env->migration_type == migrate_task) &&
10892 (sd->nr_balance_failed > sd->cache_nice_tries+2))
10898 static int need_active_balance(struct lb_env *env)
10900 struct sched_domain *sd = env->sd;
10902 if (asym_active_balance(env))
10905 if (imbalanced_active_balance(env))
10909 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
10910 * It's worth migrating the task if the src_cpu's capacity is reduced
10911 * because of other sched_class or IRQs if more capacity stays
10912 * available on dst_cpu.
10914 if ((env->idle != CPU_NOT_IDLE) &&
10915 (env->src_rq->cfs.h_nr_running == 1)) {
10916 if ((check_cpu_capacity(env->src_rq, sd)) &&
10917 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
10921 if (env->migration_type == migrate_misfit)
10927 static int active_load_balance_cpu_stop(void *data);
10929 static int should_we_balance(struct lb_env *env)
10931 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
10932 struct sched_group *sg = env->sd->groups;
10933 int cpu, idle_smt = -1;
10936 * Ensure the balancing environment is consistent; can happen
10937 * when the softirq triggers 'during' hotplug.
10939 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
10943 * In the newly idle case, we will allow all the CPUs
10944 * to do the newly idle load balance.
10946 * However, we bail out if we already have tasks or a wakeup pending,
10947 * to optimize wakeup latency.
10949 if (env->idle == CPU_NEWLY_IDLE) {
10950 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
10955 cpumask_copy(swb_cpus, group_balance_mask(sg));
10956 /* Try to find first idle CPU */
10957 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
10958 if (!idle_cpu(cpu))
10962 * Don't balance to idle SMT in busy core right away when
10963 * balancing cores, but remember the first idle SMT CPU for
10964 * later consideration. Find CPU on an idle core first.
10966 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
10967 if (idle_smt == -1)
10970 * If the core is not idle, and first SMT sibling which is
10971 * idle has been found, then its not needed to check other
10972 * SMT siblings for idleness:
10974 #ifdef CONFIG_SCHED_SMT
10975 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
10980 /* Are we the first idle CPU? */
10981 return cpu == env->dst_cpu;
10984 if (idle_smt == env->dst_cpu)
10987 /* Are we the first CPU of this group ? */
10988 return group_balance_cpu(sg) == env->dst_cpu;
10992 * Check this_cpu to ensure it is balanced within domain. Attempt to move
10993 * tasks if there is an imbalance.
10995 static int load_balance(int this_cpu, struct rq *this_rq,
10996 struct sched_domain *sd, enum cpu_idle_type idle,
10997 int *continue_balancing)
10999 int ld_moved, cur_ld_moved, active_balance = 0;
11000 struct sched_domain *sd_parent = sd->parent;
11001 struct sched_group *group;
11002 struct rq *busiest;
11003 struct rq_flags rf;
11004 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11005 struct lb_env env = {
11007 .dst_cpu = this_cpu,
11009 .dst_grpmask = group_balance_mask(sd->groups),
11011 .loop_break = SCHED_NR_MIGRATE_BREAK,
11014 .tasks = LIST_HEAD_INIT(env.tasks),
11017 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11019 schedstat_inc(sd->lb_count[idle]);
11022 if (!should_we_balance(&env)) {
11023 *continue_balancing = 0;
11027 group = find_busiest_group(&env);
11029 schedstat_inc(sd->lb_nobusyg[idle]);
11033 busiest = find_busiest_queue(&env, group);
11035 schedstat_inc(sd->lb_nobusyq[idle]);
11039 WARN_ON_ONCE(busiest == env.dst_rq);
11041 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11043 env.src_cpu = busiest->cpu;
11044 env.src_rq = busiest;
11047 /* Clear this flag as soon as we find a pullable task */
11048 env.flags |= LBF_ALL_PINNED;
11049 if (busiest->nr_running > 1) {
11051 * Attempt to move tasks. If find_busiest_group has found
11052 * an imbalance but busiest->nr_running <= 1, the group is
11053 * still unbalanced. ld_moved simply stays zero, so it is
11054 * correctly treated as an imbalance.
11056 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11059 rq_lock_irqsave(busiest, &rf);
11060 update_rq_clock(busiest);
11063 * cur_ld_moved - load moved in current iteration
11064 * ld_moved - cumulative load moved across iterations
11066 cur_ld_moved = detach_tasks(&env);
11069 * We've detached some tasks from busiest_rq. Every
11070 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11071 * unlock busiest->lock, and we are able to be sure
11072 * that nobody can manipulate the tasks in parallel.
11073 * See task_rq_lock() family for the details.
11076 rq_unlock(busiest, &rf);
11078 if (cur_ld_moved) {
11079 attach_tasks(&env);
11080 ld_moved += cur_ld_moved;
11083 local_irq_restore(rf.flags);
11085 if (env.flags & LBF_NEED_BREAK) {
11086 env.flags &= ~LBF_NEED_BREAK;
11087 /* Stop if we tried all running tasks */
11088 if (env.loop < busiest->nr_running)
11093 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11094 * us and move them to an alternate dst_cpu in our sched_group
11095 * where they can run. The upper limit on how many times we
11096 * iterate on same src_cpu is dependent on number of CPUs in our
11099 * This changes load balance semantics a bit on who can move
11100 * load to a given_cpu. In addition to the given_cpu itself
11101 * (or a ilb_cpu acting on its behalf where given_cpu is
11102 * nohz-idle), we now have balance_cpu in a position to move
11103 * load to given_cpu. In rare situations, this may cause
11104 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11105 * _independently_ and at _same_ time to move some load to
11106 * given_cpu) causing excess load to be moved to given_cpu.
11107 * This however should not happen so much in practice and
11108 * moreover subsequent load balance cycles should correct the
11109 * excess load moved.
11111 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11113 /* Prevent to re-select dst_cpu via env's CPUs */
11114 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11116 env.dst_rq = cpu_rq(env.new_dst_cpu);
11117 env.dst_cpu = env.new_dst_cpu;
11118 env.flags &= ~LBF_DST_PINNED;
11120 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11123 * Go back to "more_balance" rather than "redo" since we
11124 * need to continue with same src_cpu.
11130 * We failed to reach balance because of affinity.
11133 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11135 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11136 *group_imbalance = 1;
11139 /* All tasks on this runqueue were pinned by CPU affinity */
11140 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11141 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11143 * Attempting to continue load balancing at the current
11144 * sched_domain level only makes sense if there are
11145 * active CPUs remaining as possible busiest CPUs to
11146 * pull load from which are not contained within the
11147 * destination group that is receiving any migrated
11150 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11152 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11155 goto out_all_pinned;
11160 schedstat_inc(sd->lb_failed[idle]);
11162 * Increment the failure counter only on periodic balance.
11163 * We do not want newidle balance, which can be very
11164 * frequent, pollute the failure counter causing
11165 * excessive cache_hot migrations and active balances.
11167 if (idle != CPU_NEWLY_IDLE)
11168 sd->nr_balance_failed++;
11170 if (need_active_balance(&env)) {
11171 unsigned long flags;
11173 raw_spin_rq_lock_irqsave(busiest, flags);
11176 * Don't kick the active_load_balance_cpu_stop,
11177 * if the curr task on busiest CPU can't be
11178 * moved to this_cpu:
11180 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11181 raw_spin_rq_unlock_irqrestore(busiest, flags);
11182 goto out_one_pinned;
11185 /* Record that we found at least one task that could run on this_cpu */
11186 env.flags &= ~LBF_ALL_PINNED;
11189 * ->active_balance synchronizes accesses to
11190 * ->active_balance_work. Once set, it's cleared
11191 * only after active load balance is finished.
11193 if (!busiest->active_balance) {
11194 busiest->active_balance = 1;
11195 busiest->push_cpu = this_cpu;
11196 active_balance = 1;
11198 raw_spin_rq_unlock_irqrestore(busiest, flags);
11200 if (active_balance) {
11201 stop_one_cpu_nowait(cpu_of(busiest),
11202 active_load_balance_cpu_stop, busiest,
11203 &busiest->active_balance_work);
11207 sd->nr_balance_failed = 0;
11210 if (likely(!active_balance) || need_active_balance(&env)) {
11211 /* We were unbalanced, so reset the balancing interval */
11212 sd->balance_interval = sd->min_interval;
11219 * We reach balance although we may have faced some affinity
11220 * constraints. Clear the imbalance flag only if other tasks got
11221 * a chance to move and fix the imbalance.
11223 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11224 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11226 if (*group_imbalance)
11227 *group_imbalance = 0;
11232 * We reach balance because all tasks are pinned at this level so
11233 * we can't migrate them. Let the imbalance flag set so parent level
11234 * can try to migrate them.
11236 schedstat_inc(sd->lb_balanced[idle]);
11238 sd->nr_balance_failed = 0;
11244 * newidle_balance() disregards balance intervals, so we could
11245 * repeatedly reach this code, which would lead to balance_interval
11246 * skyrocketing in a short amount of time. Skip the balance_interval
11247 * increase logic to avoid that.
11249 if (env.idle == CPU_NEWLY_IDLE)
11252 /* tune up the balancing interval */
11253 if ((env.flags & LBF_ALL_PINNED &&
11254 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11255 sd->balance_interval < sd->max_interval)
11256 sd->balance_interval *= 2;
11261 static inline unsigned long
11262 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11264 unsigned long interval = sd->balance_interval;
11267 interval *= sd->busy_factor;
11269 /* scale ms to jiffies */
11270 interval = msecs_to_jiffies(interval);
11273 * Reduce likelihood of busy balancing at higher domains racing with
11274 * balancing at lower domains by preventing their balancing periods
11275 * from being multiples of each other.
11280 interval = clamp(interval, 1UL, max_load_balance_interval);
11286 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11288 unsigned long interval, next;
11290 /* used by idle balance, so cpu_busy = 0 */
11291 interval = get_sd_balance_interval(sd, 0);
11292 next = sd->last_balance + interval;
11294 if (time_after(*next_balance, next))
11295 *next_balance = next;
11299 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11300 * running tasks off the busiest CPU onto idle CPUs. It requires at
11301 * least 1 task to be running on each physical CPU where possible, and
11302 * avoids physical / logical imbalances.
11304 static int active_load_balance_cpu_stop(void *data)
11306 struct rq *busiest_rq = data;
11307 int busiest_cpu = cpu_of(busiest_rq);
11308 int target_cpu = busiest_rq->push_cpu;
11309 struct rq *target_rq = cpu_rq(target_cpu);
11310 struct sched_domain *sd;
11311 struct task_struct *p = NULL;
11312 struct rq_flags rf;
11314 rq_lock_irq(busiest_rq, &rf);
11316 * Between queueing the stop-work and running it is a hole in which
11317 * CPUs can become inactive. We should not move tasks from or to
11320 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11323 /* Make sure the requested CPU hasn't gone down in the meantime: */
11324 if (unlikely(busiest_cpu != smp_processor_id() ||
11325 !busiest_rq->active_balance))
11328 /* Is there any task to move? */
11329 if (busiest_rq->nr_running <= 1)
11333 * This condition is "impossible", if it occurs
11334 * we need to fix it. Originally reported by
11335 * Bjorn Helgaas on a 128-CPU setup.
11337 WARN_ON_ONCE(busiest_rq == target_rq);
11339 /* Search for an sd spanning us and the target CPU. */
11341 for_each_domain(target_cpu, sd) {
11342 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11347 struct lb_env env = {
11349 .dst_cpu = target_cpu,
11350 .dst_rq = target_rq,
11351 .src_cpu = busiest_rq->cpu,
11352 .src_rq = busiest_rq,
11354 .flags = LBF_ACTIVE_LB,
11357 schedstat_inc(sd->alb_count);
11358 update_rq_clock(busiest_rq);
11360 p = detach_one_task(&env);
11362 schedstat_inc(sd->alb_pushed);
11363 /* Active balancing done, reset the failure counter. */
11364 sd->nr_balance_failed = 0;
11366 schedstat_inc(sd->alb_failed);
11371 busiest_rq->active_balance = 0;
11372 rq_unlock(busiest_rq, &rf);
11375 attach_one_task(target_rq, p);
11377 local_irq_enable();
11382 static DEFINE_SPINLOCK(balancing);
11385 * Scale the max load_balance interval with the number of CPUs in the system.
11386 * This trades load-balance latency on larger machines for less cross talk.
11388 void update_max_interval(void)
11390 max_load_balance_interval = HZ*num_online_cpus()/10;
11393 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11395 if (cost > sd->max_newidle_lb_cost) {
11397 * Track max cost of a domain to make sure to not delay the
11398 * next wakeup on the CPU.
11400 sd->max_newidle_lb_cost = cost;
11401 sd->last_decay_max_lb_cost = jiffies;
11402 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11404 * Decay the newidle max times by ~1% per second to ensure that
11405 * it is not outdated and the current max cost is actually
11408 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11409 sd->last_decay_max_lb_cost = jiffies;
11418 * It checks each scheduling domain to see if it is due to be balanced,
11419 * and initiates a balancing operation if so.
11421 * Balancing parameters are set up in init_sched_domains.
11423 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11425 int continue_balancing = 1;
11427 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11428 unsigned long interval;
11429 struct sched_domain *sd;
11430 /* Earliest time when we have to do rebalance again */
11431 unsigned long next_balance = jiffies + 60*HZ;
11432 int update_next_balance = 0;
11433 int need_serialize, need_decay = 0;
11437 for_each_domain(cpu, sd) {
11439 * Decay the newidle max times here because this is a regular
11440 * visit to all the domains.
11442 need_decay = update_newidle_cost(sd, 0);
11443 max_cost += sd->max_newidle_lb_cost;
11446 * Stop the load balance at this level. There is another
11447 * CPU in our sched group which is doing load balancing more
11450 if (!continue_balancing) {
11456 interval = get_sd_balance_interval(sd, busy);
11458 need_serialize = sd->flags & SD_SERIALIZE;
11459 if (need_serialize) {
11460 if (!spin_trylock(&balancing))
11464 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11465 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11467 * The LBF_DST_PINNED logic could have changed
11468 * env->dst_cpu, so we can't know our idle
11469 * state even if we migrated tasks. Update it.
11471 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11472 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11474 sd->last_balance = jiffies;
11475 interval = get_sd_balance_interval(sd, busy);
11477 if (need_serialize)
11478 spin_unlock(&balancing);
11480 if (time_after(next_balance, sd->last_balance + interval)) {
11481 next_balance = sd->last_balance + interval;
11482 update_next_balance = 1;
11487 * Ensure the rq-wide value also decays but keep it at a
11488 * reasonable floor to avoid funnies with rq->avg_idle.
11490 rq->max_idle_balance_cost =
11491 max((u64)sysctl_sched_migration_cost, max_cost);
11496 * next_balance will be updated only when there is a need.
11497 * When the cpu is attached to null domain for ex, it will not be
11500 if (likely(update_next_balance))
11501 rq->next_balance = next_balance;
11505 static inline int on_null_domain(struct rq *rq)
11507 return unlikely(!rcu_dereference_sched(rq->sd));
11510 #ifdef CONFIG_NO_HZ_COMMON
11512 * idle load balancing details
11513 * - When one of the busy CPUs notice that there may be an idle rebalancing
11514 * needed, they will kick the idle load balancer, which then does idle
11515 * load balancing for all the idle CPUs.
11516 * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED not set
11520 static inline int find_new_ilb(void)
11523 const struct cpumask *hk_mask;
11525 hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11527 for_each_cpu_and(ilb, nohz.idle_cpus_mask, hk_mask) {
11529 if (ilb == smp_processor_id())
11540 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
11541 * idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11543 static void kick_ilb(unsigned int flags)
11548 * Increase nohz.next_balance only when if full ilb is triggered but
11549 * not if we only update stats.
11551 if (flags & NOHZ_BALANCE_KICK)
11552 nohz.next_balance = jiffies+1;
11554 ilb_cpu = find_new_ilb();
11556 if (ilb_cpu >= nr_cpu_ids)
11560 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11561 * the first flag owns it; cleared by nohz_csd_func().
11563 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11564 if (flags & NOHZ_KICK_MASK)
11568 * This way we generate an IPI on the target CPU which
11569 * is idle. And the softirq performing nohz idle load balance
11570 * will be run before returning from the IPI.
11572 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11576 * Current decision point for kicking the idle load balancer in the presence
11577 * of idle CPUs in the system.
11579 static void nohz_balancer_kick(struct rq *rq)
11581 unsigned long now = jiffies;
11582 struct sched_domain_shared *sds;
11583 struct sched_domain *sd;
11584 int nr_busy, i, cpu = rq->cpu;
11585 unsigned int flags = 0;
11587 if (unlikely(rq->idle_balance))
11591 * We may be recently in ticked or tickless idle mode. At the first
11592 * busy tick after returning from idle, we will update the busy stats.
11594 nohz_balance_exit_idle(rq);
11597 * None are in tickless mode and hence no need for NOHZ idle load
11600 if (likely(!atomic_read(&nohz.nr_cpus)))
11603 if (READ_ONCE(nohz.has_blocked) &&
11604 time_after(now, READ_ONCE(nohz.next_blocked)))
11605 flags = NOHZ_STATS_KICK;
11607 if (time_before(now, nohz.next_balance))
11610 if (rq->nr_running >= 2) {
11611 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11617 sd = rcu_dereference(rq->sd);
11620 * If there's a CFS task and the current CPU has reduced
11621 * capacity; kick the ILB to see if there's a better CPU to run
11624 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11625 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11630 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11633 * When ASYM_PACKING; see if there's a more preferred CPU
11634 * currently idle; in which case, kick the ILB to move tasks
11637 * When balancing betwen cores, all the SMT siblings of the
11638 * preferred CPU must be idle.
11640 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11641 if (sched_use_asym_prio(sd, i) &&
11642 sched_asym_prefer(i, cpu)) {
11643 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11649 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11652 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11653 * to run the misfit task on.
11655 if (check_misfit_status(rq, sd)) {
11656 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11661 * For asymmetric systems, we do not want to nicely balance
11662 * cache use, instead we want to embrace asymmetry and only
11663 * ensure tasks have enough CPU capacity.
11665 * Skip the LLC logic because it's not relevant in that case.
11670 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11673 * If there is an imbalance between LLC domains (IOW we could
11674 * increase the overall cache use), we need some less-loaded LLC
11675 * domain to pull some load. Likewise, we may need to spread
11676 * load within the current LLC domain (e.g. packed SMT cores but
11677 * other CPUs are idle). We can't really know from here how busy
11678 * the others are - so just get a nohz balance going if it looks
11679 * like this LLC domain has tasks we could move.
11681 nr_busy = atomic_read(&sds->nr_busy_cpus);
11683 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11690 if (READ_ONCE(nohz.needs_update))
11691 flags |= NOHZ_NEXT_KICK;
11697 static void set_cpu_sd_state_busy(int cpu)
11699 struct sched_domain *sd;
11702 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11704 if (!sd || !sd->nohz_idle)
11708 atomic_inc(&sd->shared->nr_busy_cpus);
11713 void nohz_balance_exit_idle(struct rq *rq)
11715 SCHED_WARN_ON(rq != this_rq());
11717 if (likely(!rq->nohz_tick_stopped))
11720 rq->nohz_tick_stopped = 0;
11721 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
11722 atomic_dec(&nohz.nr_cpus);
11724 set_cpu_sd_state_busy(rq->cpu);
11727 static void set_cpu_sd_state_idle(int cpu)
11729 struct sched_domain *sd;
11732 sd = rcu_dereference(per_cpu(sd_llc, cpu));
11734 if (!sd || sd->nohz_idle)
11738 atomic_dec(&sd->shared->nr_busy_cpus);
11744 * This routine will record that the CPU is going idle with tick stopped.
11745 * This info will be used in performing idle load balancing in the future.
11747 void nohz_balance_enter_idle(int cpu)
11749 struct rq *rq = cpu_rq(cpu);
11751 SCHED_WARN_ON(cpu != smp_processor_id());
11753 /* If this CPU is going down, then nothing needs to be done: */
11754 if (!cpu_active(cpu))
11757 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
11758 if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
11762 * Can be set safely without rq->lock held
11763 * If a clear happens, it will have evaluated last additions because
11764 * rq->lock is held during the check and the clear
11766 rq->has_blocked_load = 1;
11769 * The tick is still stopped but load could have been added in the
11770 * meantime. We set the nohz.has_blocked flag to trig a check of the
11771 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
11772 * of nohz.has_blocked can only happen after checking the new load
11774 if (rq->nohz_tick_stopped)
11777 /* If we're a completely isolated CPU, we don't play: */
11778 if (on_null_domain(rq))
11781 rq->nohz_tick_stopped = 1;
11783 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
11784 atomic_inc(&nohz.nr_cpus);
11787 * Ensures that if nohz_idle_balance() fails to observe our
11788 * @idle_cpus_mask store, it must observe the @has_blocked
11789 * and @needs_update stores.
11791 smp_mb__after_atomic();
11793 set_cpu_sd_state_idle(cpu);
11795 WRITE_ONCE(nohz.needs_update, 1);
11798 * Each time a cpu enter idle, we assume that it has blocked load and
11799 * enable the periodic update of the load of idle cpus
11801 WRITE_ONCE(nohz.has_blocked, 1);
11804 static bool update_nohz_stats(struct rq *rq)
11806 unsigned int cpu = rq->cpu;
11808 if (!rq->has_blocked_load)
11811 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
11814 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
11817 update_blocked_averages(cpu);
11819 return rq->has_blocked_load;
11823 * Internal function that runs load balance for all idle cpus. The load balance
11824 * can be a simple update of blocked load or a complete load balance with
11825 * tasks movement depending of flags.
11827 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
11829 /* Earliest time when we have to do rebalance again */
11830 unsigned long now = jiffies;
11831 unsigned long next_balance = now + 60*HZ;
11832 bool has_blocked_load = false;
11833 int update_next_balance = 0;
11834 int this_cpu = this_rq->cpu;
11838 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
11841 * We assume there will be no idle load after this update and clear
11842 * the has_blocked flag. If a cpu enters idle in the mean time, it will
11843 * set the has_blocked flag and trigger another update of idle load.
11844 * Because a cpu that becomes idle, is added to idle_cpus_mask before
11845 * setting the flag, we are sure to not clear the state and not
11846 * check the load of an idle cpu.
11848 * Same applies to idle_cpus_mask vs needs_update.
11850 if (flags & NOHZ_STATS_KICK)
11851 WRITE_ONCE(nohz.has_blocked, 0);
11852 if (flags & NOHZ_NEXT_KICK)
11853 WRITE_ONCE(nohz.needs_update, 0);
11856 * Ensures that if we miss the CPU, we must see the has_blocked
11857 * store from nohz_balance_enter_idle().
11862 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
11863 * chance for other idle cpu to pull load.
11865 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
11866 if (!idle_cpu(balance_cpu))
11870 * If this CPU gets work to do, stop the load balancing
11871 * work being done for other CPUs. Next load
11872 * balancing owner will pick it up.
11874 if (need_resched()) {
11875 if (flags & NOHZ_STATS_KICK)
11876 has_blocked_load = true;
11877 if (flags & NOHZ_NEXT_KICK)
11878 WRITE_ONCE(nohz.needs_update, 1);
11882 rq = cpu_rq(balance_cpu);
11884 if (flags & NOHZ_STATS_KICK)
11885 has_blocked_load |= update_nohz_stats(rq);
11888 * If time for next balance is due,
11891 if (time_after_eq(jiffies, rq->next_balance)) {
11892 struct rq_flags rf;
11894 rq_lock_irqsave(rq, &rf);
11895 update_rq_clock(rq);
11896 rq_unlock_irqrestore(rq, &rf);
11898 if (flags & NOHZ_BALANCE_KICK)
11899 rebalance_domains(rq, CPU_IDLE);
11902 if (time_after(next_balance, rq->next_balance)) {
11903 next_balance = rq->next_balance;
11904 update_next_balance = 1;
11909 * next_balance will be updated only when there is a need.
11910 * When the CPU is attached to null domain for ex, it will not be
11913 if (likely(update_next_balance))
11914 nohz.next_balance = next_balance;
11916 if (flags & NOHZ_STATS_KICK)
11917 WRITE_ONCE(nohz.next_blocked,
11918 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
11921 /* There is still blocked load, enable periodic update */
11922 if (has_blocked_load)
11923 WRITE_ONCE(nohz.has_blocked, 1);
11927 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
11928 * rebalancing for all the cpus for whom scheduler ticks are stopped.
11930 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
11932 unsigned int flags = this_rq->nohz_idle_balance;
11937 this_rq->nohz_idle_balance = 0;
11939 if (idle != CPU_IDLE)
11942 _nohz_idle_balance(this_rq, flags);
11948 * Check if we need to run the ILB for updating blocked load before entering
11951 void nohz_run_idle_balance(int cpu)
11953 unsigned int flags;
11955 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
11958 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
11959 * (ie NOHZ_STATS_KICK set) and will do the same.
11961 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
11962 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
11965 static void nohz_newidle_balance(struct rq *this_rq)
11967 int this_cpu = this_rq->cpu;
11970 * This CPU doesn't want to be disturbed by scheduler
11973 if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
11976 /* Will wake up very soon. No time for doing anything else*/
11977 if (this_rq->avg_idle < sysctl_sched_migration_cost)
11980 /* Don't need to update blocked load of idle CPUs*/
11981 if (!READ_ONCE(nohz.has_blocked) ||
11982 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
11986 * Set the need to trigger ILB in order to update blocked load
11987 * before entering idle state.
11989 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
11992 #else /* !CONFIG_NO_HZ_COMMON */
11993 static inline void nohz_balancer_kick(struct rq *rq) { }
11995 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12000 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12001 #endif /* CONFIG_NO_HZ_COMMON */
12004 * newidle_balance is called by schedule() if this_cpu is about to become
12005 * idle. Attempts to pull tasks from other CPUs.
12008 * < 0 - we released the lock and there are !fair tasks present
12009 * 0 - failed, no new tasks
12010 * > 0 - success, new (fair) tasks present
12012 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12014 unsigned long next_balance = jiffies + HZ;
12015 int this_cpu = this_rq->cpu;
12016 u64 t0, t1, curr_cost = 0;
12017 struct sched_domain *sd;
12018 int pulled_task = 0;
12020 update_misfit_status(NULL, this_rq);
12023 * There is a task waiting to run. No need to search for one.
12024 * Return 0; the task will be enqueued when switching to idle.
12026 if (this_rq->ttwu_pending)
12030 * We must set idle_stamp _before_ calling idle_balance(), such that we
12031 * measure the duration of idle_balance() as idle time.
12033 this_rq->idle_stamp = rq_clock(this_rq);
12036 * Do not pull tasks towards !active CPUs...
12038 if (!cpu_active(this_cpu))
12042 * This is OK, because current is on_cpu, which avoids it being picked
12043 * for load-balance and preemption/IRQs are still disabled avoiding
12044 * further scheduler activity on it and we're being very careful to
12045 * re-start the picking loop.
12047 rq_unpin_lock(this_rq, rf);
12050 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12052 if (!READ_ONCE(this_rq->rd->overload) ||
12053 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12056 update_next_balance(sd, &next_balance);
12063 raw_spin_rq_unlock(this_rq);
12065 t0 = sched_clock_cpu(this_cpu);
12066 update_blocked_averages(this_cpu);
12069 for_each_domain(this_cpu, sd) {
12070 int continue_balancing = 1;
12073 update_next_balance(sd, &next_balance);
12075 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12078 if (sd->flags & SD_BALANCE_NEWIDLE) {
12080 pulled_task = load_balance(this_cpu, this_rq,
12081 sd, CPU_NEWLY_IDLE,
12082 &continue_balancing);
12084 t1 = sched_clock_cpu(this_cpu);
12085 domain_cost = t1 - t0;
12086 update_newidle_cost(sd, domain_cost);
12088 curr_cost += domain_cost;
12093 * Stop searching for tasks to pull if there are
12094 * now runnable tasks on this rq.
12096 if (pulled_task || this_rq->nr_running > 0 ||
12097 this_rq->ttwu_pending)
12102 raw_spin_rq_lock(this_rq);
12104 if (curr_cost > this_rq->max_idle_balance_cost)
12105 this_rq->max_idle_balance_cost = curr_cost;
12108 * While browsing the domains, we released the rq lock, a task could
12109 * have been enqueued in the meantime. Since we're not going idle,
12110 * pretend we pulled a task.
12112 if (this_rq->cfs.h_nr_running && !pulled_task)
12115 /* Is there a task of a high priority class? */
12116 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12120 /* Move the next balance forward */
12121 if (time_after(this_rq->next_balance, next_balance))
12122 this_rq->next_balance = next_balance;
12125 this_rq->idle_stamp = 0;
12127 nohz_newidle_balance(this_rq);
12129 rq_repin_lock(this_rq, rf);
12131 return pulled_task;
12135 * run_rebalance_domains is triggered when needed from the scheduler tick.
12136 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12138 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12140 struct rq *this_rq = this_rq();
12141 enum cpu_idle_type idle = this_rq->idle_balance ?
12142 CPU_IDLE : CPU_NOT_IDLE;
12145 * If this CPU has a pending nohz_balance_kick, then do the
12146 * balancing on behalf of the other idle CPUs whose ticks are
12147 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12148 * give the idle CPUs a chance to load balance. Else we may
12149 * load balance only within the local sched_domain hierarchy
12150 * and abort nohz_idle_balance altogether if we pull some load.
12152 if (nohz_idle_balance(this_rq, idle))
12155 /* normal load balance */
12156 update_blocked_averages(this_rq->cpu);
12157 rebalance_domains(this_rq, idle);
12161 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12163 void trigger_load_balance(struct rq *rq)
12166 * Don't need to rebalance while attached to NULL domain or
12167 * runqueue CPU is not active
12169 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12172 if (time_after_eq(jiffies, rq->next_balance))
12173 raise_softirq(SCHED_SOFTIRQ);
12175 nohz_balancer_kick(rq);
12178 static void rq_online_fair(struct rq *rq)
12182 update_runtime_enabled(rq);
12185 static void rq_offline_fair(struct rq *rq)
12189 /* Ensure any throttled groups are reachable by pick_next_task */
12190 unthrottle_offline_cfs_rqs(rq);
12193 #endif /* CONFIG_SMP */
12195 #ifdef CONFIG_SCHED_CORE
12197 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12199 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12200 u64 slice = se->slice;
12202 return (rtime * min_nr_tasks > slice);
12205 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
12206 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12208 if (!sched_core_enabled(rq))
12212 * If runqueue has only one task which used up its slice and
12213 * if the sibling is forced idle, then trigger schedule to
12214 * give forced idle task a chance.
12216 * sched_slice() considers only this active rq and it gets the
12217 * whole slice. But during force idle, we have siblings acting
12218 * like a single runqueue and hence we need to consider runnable
12219 * tasks on this CPU and the forced idle CPU. Ideally, we should
12220 * go through the forced idle rq, but that would be a perf hit.
12221 * We can assume that the forced idle CPU has at least
12222 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12223 * if we need to give up the CPU.
12225 if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12226 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12231 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12233 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12236 for_each_sched_entity(se) {
12237 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12240 if (cfs_rq->forceidle_seq == fi_seq)
12242 cfs_rq->forceidle_seq = fi_seq;
12245 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12249 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12251 struct sched_entity *se = &p->se;
12253 if (p->sched_class != &fair_sched_class)
12256 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12259 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12262 struct rq *rq = task_rq(a);
12263 const struct sched_entity *sea = &a->se;
12264 const struct sched_entity *seb = &b->se;
12265 struct cfs_rq *cfs_rqa;
12266 struct cfs_rq *cfs_rqb;
12269 SCHED_WARN_ON(task_rq(b)->core != rq->core);
12271 #ifdef CONFIG_FAIR_GROUP_SCHED
12273 * Find an se in the hierarchy for tasks a and b, such that the se's
12274 * are immediate siblings.
12276 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12277 int sea_depth = sea->depth;
12278 int seb_depth = seb->depth;
12280 if (sea_depth >= seb_depth)
12281 sea = parent_entity(sea);
12282 if (sea_depth <= seb_depth)
12283 seb = parent_entity(seb);
12286 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12287 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12289 cfs_rqa = sea->cfs_rq;
12290 cfs_rqb = seb->cfs_rq;
12292 cfs_rqa = &task_rq(a)->cfs;
12293 cfs_rqb = &task_rq(b)->cfs;
12297 * Find delta after normalizing se's vruntime with its cfs_rq's
12298 * min_vruntime_fi, which would have been updated in prior calls
12299 * to se_fi_update().
12301 delta = (s64)(sea->vruntime - seb->vruntime) +
12302 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12307 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12309 struct cfs_rq *cfs_rq;
12311 #ifdef CONFIG_FAIR_GROUP_SCHED
12312 cfs_rq = task_group(p)->cfs_rq[cpu];
12314 cfs_rq = &cpu_rq(cpu)->cfs;
12316 return throttled_hierarchy(cfs_rq);
12319 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12323 * scheduler tick hitting a task of our scheduling class.
12325 * NOTE: This function can be called remotely by the tick offload that
12326 * goes along full dynticks. Therefore no local assumption can be made
12327 * and everything must be accessed through the @rq and @curr passed in
12330 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12332 struct cfs_rq *cfs_rq;
12333 struct sched_entity *se = &curr->se;
12335 for_each_sched_entity(se) {
12336 cfs_rq = cfs_rq_of(se);
12337 entity_tick(cfs_rq, se, queued);
12340 if (static_branch_unlikely(&sched_numa_balancing))
12341 task_tick_numa(rq, curr);
12343 update_misfit_status(curr, rq);
12344 update_overutilized_status(task_rq(curr));
12346 task_tick_core(rq, curr);
12350 * called on fork with the child task as argument from the parent's context
12351 * - child not yet on the tasklist
12352 * - preemption disabled
12354 static void task_fork_fair(struct task_struct *p)
12356 struct sched_entity *se = &p->se, *curr;
12357 struct cfs_rq *cfs_rq;
12358 struct rq *rq = this_rq();
12359 struct rq_flags rf;
12362 update_rq_clock(rq);
12364 cfs_rq = task_cfs_rq(current);
12365 curr = cfs_rq->curr;
12367 update_curr(cfs_rq);
12368 place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12369 rq_unlock(rq, &rf);
12373 * Priority of the task has changed. Check to see if we preempt
12374 * the current task.
12377 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12379 if (!task_on_rq_queued(p))
12382 if (rq->cfs.nr_running == 1)
12386 * Reschedule if we are currently running on this runqueue and
12387 * our priority decreased, or if we are not currently running on
12388 * this runqueue and our priority is higher than the current's
12390 if (task_current(rq, p)) {
12391 if (p->prio > oldprio)
12394 check_preempt_curr(rq, p, 0);
12397 #ifdef CONFIG_FAIR_GROUP_SCHED
12399 * Propagate the changes of the sched_entity across the tg tree to make it
12400 * visible to the root
12402 static void propagate_entity_cfs_rq(struct sched_entity *se)
12404 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12406 if (cfs_rq_throttled(cfs_rq))
12409 if (!throttled_hierarchy(cfs_rq))
12410 list_add_leaf_cfs_rq(cfs_rq);
12412 /* Start to propagate at parent */
12415 for_each_sched_entity(se) {
12416 cfs_rq = cfs_rq_of(se);
12418 update_load_avg(cfs_rq, se, UPDATE_TG);
12420 if (cfs_rq_throttled(cfs_rq))
12423 if (!throttled_hierarchy(cfs_rq))
12424 list_add_leaf_cfs_rq(cfs_rq);
12428 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12431 static void detach_entity_cfs_rq(struct sched_entity *se)
12433 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12437 * In case the task sched_avg hasn't been attached:
12438 * - A forked task which hasn't been woken up by wake_up_new_task().
12439 * - A task which has been woken up by try_to_wake_up() but is
12440 * waiting for actually being woken up by sched_ttwu_pending().
12442 if (!se->avg.last_update_time)
12446 /* Catch up with the cfs_rq and remove our load when we leave */
12447 update_load_avg(cfs_rq, se, 0);
12448 detach_entity_load_avg(cfs_rq, se);
12449 update_tg_load_avg(cfs_rq);
12450 propagate_entity_cfs_rq(se);
12453 static void attach_entity_cfs_rq(struct sched_entity *se)
12455 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12457 /* Synchronize entity with its cfs_rq */
12458 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12459 attach_entity_load_avg(cfs_rq, se);
12460 update_tg_load_avg(cfs_rq);
12461 propagate_entity_cfs_rq(se);
12464 static void detach_task_cfs_rq(struct task_struct *p)
12466 struct sched_entity *se = &p->se;
12468 detach_entity_cfs_rq(se);
12471 static void attach_task_cfs_rq(struct task_struct *p)
12473 struct sched_entity *se = &p->se;
12475 attach_entity_cfs_rq(se);
12478 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12480 detach_task_cfs_rq(p);
12483 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12485 attach_task_cfs_rq(p);
12487 if (task_on_rq_queued(p)) {
12489 * We were most likely switched from sched_rt, so
12490 * kick off the schedule if running, otherwise just see
12491 * if we can still preempt the current task.
12493 if (task_current(rq, p))
12496 check_preempt_curr(rq, p, 0);
12500 /* Account for a task changing its policy or group.
12502 * This routine is mostly called to set cfs_rq->curr field when a task
12503 * migrates between groups/classes.
12505 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12507 struct sched_entity *se = &p->se;
12510 if (task_on_rq_queued(p)) {
12512 * Move the next running task to the front of the list, so our
12513 * cfs_tasks list becomes MRU one.
12515 list_move(&se->group_node, &rq->cfs_tasks);
12519 for_each_sched_entity(se) {
12520 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12522 set_next_entity(cfs_rq, se);
12523 /* ensure bandwidth has been allocated on our new cfs_rq */
12524 account_cfs_rq_runtime(cfs_rq, 0);
12528 void init_cfs_rq(struct cfs_rq *cfs_rq)
12530 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12531 u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12533 raw_spin_lock_init(&cfs_rq->removed.lock);
12537 #ifdef CONFIG_FAIR_GROUP_SCHED
12538 static void task_change_group_fair(struct task_struct *p)
12541 * We couldn't detach or attach a forked task which
12542 * hasn't been woken up by wake_up_new_task().
12544 if (READ_ONCE(p->__state) == TASK_NEW)
12547 detach_task_cfs_rq(p);
12550 /* Tell se's cfs_rq has been changed -- migrated */
12551 p->se.avg.last_update_time = 0;
12553 set_task_rq(p, task_cpu(p));
12554 attach_task_cfs_rq(p);
12557 void free_fair_sched_group(struct task_group *tg)
12561 for_each_possible_cpu(i) {
12563 kfree(tg->cfs_rq[i]);
12572 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12574 struct sched_entity *se;
12575 struct cfs_rq *cfs_rq;
12578 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12581 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12585 tg->shares = NICE_0_LOAD;
12587 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12589 for_each_possible_cpu(i) {
12590 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12591 GFP_KERNEL, cpu_to_node(i));
12595 se = kzalloc_node(sizeof(struct sched_entity_stats),
12596 GFP_KERNEL, cpu_to_node(i));
12600 init_cfs_rq(cfs_rq);
12601 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12602 init_entity_runnable_average(se);
12613 void online_fair_sched_group(struct task_group *tg)
12615 struct sched_entity *se;
12616 struct rq_flags rf;
12620 for_each_possible_cpu(i) {
12623 rq_lock_irq(rq, &rf);
12624 update_rq_clock(rq);
12625 attach_entity_cfs_rq(se);
12626 sync_throttle(tg, i);
12627 rq_unlock_irq(rq, &rf);
12631 void unregister_fair_sched_group(struct task_group *tg)
12633 unsigned long flags;
12637 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12639 for_each_possible_cpu(cpu) {
12641 remove_entity_load_avg(tg->se[cpu]);
12644 * Only empty task groups can be destroyed; so we can speculatively
12645 * check on_list without danger of it being re-added.
12647 if (!tg->cfs_rq[cpu]->on_list)
12652 raw_spin_rq_lock_irqsave(rq, flags);
12653 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12654 raw_spin_rq_unlock_irqrestore(rq, flags);
12658 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12659 struct sched_entity *se, int cpu,
12660 struct sched_entity *parent)
12662 struct rq *rq = cpu_rq(cpu);
12666 init_cfs_rq_runtime(cfs_rq);
12668 tg->cfs_rq[cpu] = cfs_rq;
12671 /* se could be NULL for root_task_group */
12676 se->cfs_rq = &rq->cfs;
12679 se->cfs_rq = parent->my_q;
12680 se->depth = parent->depth + 1;
12684 /* guarantee group entities always have weight */
12685 update_load_set(&se->load, NICE_0_LOAD);
12686 se->parent = parent;
12689 static DEFINE_MUTEX(shares_mutex);
12691 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
12695 lockdep_assert_held(&shares_mutex);
12698 * We can't change the weight of the root cgroup.
12703 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
12705 if (tg->shares == shares)
12708 tg->shares = shares;
12709 for_each_possible_cpu(i) {
12710 struct rq *rq = cpu_rq(i);
12711 struct sched_entity *se = tg->se[i];
12712 struct rq_flags rf;
12714 /* Propagate contribution to hierarchy */
12715 rq_lock_irqsave(rq, &rf);
12716 update_rq_clock(rq);
12717 for_each_sched_entity(se) {
12718 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
12719 update_cfs_group(se);
12721 rq_unlock_irqrestore(rq, &rf);
12727 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
12731 mutex_lock(&shares_mutex);
12732 if (tg_is_idle(tg))
12735 ret = __sched_group_set_shares(tg, shares);
12736 mutex_unlock(&shares_mutex);
12741 int sched_group_set_idle(struct task_group *tg, long idle)
12745 if (tg == &root_task_group)
12748 if (idle < 0 || idle > 1)
12751 mutex_lock(&shares_mutex);
12753 if (tg->idle == idle) {
12754 mutex_unlock(&shares_mutex);
12760 for_each_possible_cpu(i) {
12761 struct rq *rq = cpu_rq(i);
12762 struct sched_entity *se = tg->se[i];
12763 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
12764 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
12765 long idle_task_delta;
12766 struct rq_flags rf;
12768 rq_lock_irqsave(rq, &rf);
12770 grp_cfs_rq->idle = idle;
12771 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
12775 parent_cfs_rq = cfs_rq_of(se);
12776 if (cfs_rq_is_idle(grp_cfs_rq))
12777 parent_cfs_rq->idle_nr_running++;
12779 parent_cfs_rq->idle_nr_running--;
12782 idle_task_delta = grp_cfs_rq->h_nr_running -
12783 grp_cfs_rq->idle_h_nr_running;
12784 if (!cfs_rq_is_idle(grp_cfs_rq))
12785 idle_task_delta *= -1;
12787 for_each_sched_entity(se) {
12788 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12793 cfs_rq->idle_h_nr_running += idle_task_delta;
12795 /* Already accounted at parent level and above. */
12796 if (cfs_rq_is_idle(cfs_rq))
12801 rq_unlock_irqrestore(rq, &rf);
12804 /* Idle groups have minimum weight. */
12805 if (tg_is_idle(tg))
12806 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
12808 __sched_group_set_shares(tg, NICE_0_LOAD);
12810 mutex_unlock(&shares_mutex);
12814 #else /* CONFIG_FAIR_GROUP_SCHED */
12816 void free_fair_sched_group(struct task_group *tg) { }
12818 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12823 void online_fair_sched_group(struct task_group *tg) { }
12825 void unregister_fair_sched_group(struct task_group *tg) { }
12827 #endif /* CONFIG_FAIR_GROUP_SCHED */
12830 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
12832 struct sched_entity *se = &task->se;
12833 unsigned int rr_interval = 0;
12836 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
12839 if (rq->cfs.load.weight)
12840 rr_interval = NS_TO_JIFFIES(se->slice);
12842 return rr_interval;
12846 * All the scheduling class methods:
12848 DEFINE_SCHED_CLASS(fair) = {
12850 .enqueue_task = enqueue_task_fair,
12851 .dequeue_task = dequeue_task_fair,
12852 .yield_task = yield_task_fair,
12853 .yield_to_task = yield_to_task_fair,
12855 .check_preempt_curr = check_preempt_wakeup,
12857 .pick_next_task = __pick_next_task_fair,
12858 .put_prev_task = put_prev_task_fair,
12859 .set_next_task = set_next_task_fair,
12862 .balance = balance_fair,
12863 .pick_task = pick_task_fair,
12864 .select_task_rq = select_task_rq_fair,
12865 .migrate_task_rq = migrate_task_rq_fair,
12867 .rq_online = rq_online_fair,
12868 .rq_offline = rq_offline_fair,
12870 .task_dead = task_dead_fair,
12871 .set_cpus_allowed = set_cpus_allowed_common,
12874 .task_tick = task_tick_fair,
12875 .task_fork = task_fork_fair,
12877 .prio_changed = prio_changed_fair,
12878 .switched_from = switched_from_fair,
12879 .switched_to = switched_to_fair,
12881 .get_rr_interval = get_rr_interval_fair,
12883 .update_curr = update_curr_fair,
12885 #ifdef CONFIG_FAIR_GROUP_SCHED
12886 .task_change_group = task_change_group_fair,
12889 #ifdef CONFIG_SCHED_CORE
12890 .task_is_throttled = task_is_throttled_fair,
12893 #ifdef CONFIG_UCLAMP_TASK
12894 .uclamp_enabled = 1,
12898 #ifdef CONFIG_SCHED_DEBUG
12899 void print_cfs_stats(struct seq_file *m, int cpu)
12901 struct cfs_rq *cfs_rq, *pos;
12904 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
12905 print_cfs_rq(m, cpu, cfs_rq);
12909 #ifdef CONFIG_NUMA_BALANCING
12910 void show_numa_stats(struct task_struct *p, struct seq_file *m)
12913 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
12914 struct numa_group *ng;
12917 ng = rcu_dereference(p->numa_group);
12918 for_each_online_node(node) {
12919 if (p->numa_faults) {
12920 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
12921 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
12924 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
12925 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
12927 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
12931 #endif /* CONFIG_NUMA_BALANCING */
12932 #endif /* CONFIG_SCHED_DEBUG */
12934 __init void init_sched_fair_class(void)
12939 for_each_possible_cpu(i) {
12940 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
12941 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
12942 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
12943 GFP_KERNEL, cpu_to_node(i));
12945 #ifdef CONFIG_CFS_BANDWIDTH
12946 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
12947 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
12951 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
12953 #ifdef CONFIG_NO_HZ_COMMON
12954 nohz.next_balance = jiffies;
12955 nohz.next_blocked = jiffies;
12956 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);