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
26 * Targeted preemption latency for CPU-bound tasks:
28 * NOTE: this latency value is not the same as the concept of
29 * 'timeslice length' - timeslices in CFS are of variable length
30 * and have no persistent notion like in traditional, time-slice
31 * based scheduling concepts.
33 * (to see the precise effective timeslice length of your workload,
34 * run vmstat and monitor the context-switches (cs) field)
36 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
38 unsigned int sysctl_sched_latency = 6000000ULL;
39 static unsigned int normalized_sysctl_sched_latency = 6000000ULL;
42 * The initial- and re-scaling of tunables is configurable
46 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
47 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
48 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
50 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
52 enum sched_tunable_scaling sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
55 * Minimal preemption granularity for CPU-bound tasks:
57 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
59 unsigned int sysctl_sched_min_granularity = 750000ULL;
60 static unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
63 * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
65 static unsigned int sched_nr_latency = 8;
68 * After fork, child runs first. If set to 0 (default) then
69 * parent will (try to) run first.
71 unsigned int sysctl_sched_child_runs_first __read_mostly;
74 * SCHED_OTHER wake-up granularity.
76 * This option delays the preemption effects of decoupled workloads
77 * and reduces their over-scheduling. Synchronous workloads will still
78 * have immediate wakeup/sleep latencies.
80 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
82 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
83 static unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
85 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
87 int sched_thermal_decay_shift;
88 static int __init setup_sched_thermal_decay_shift(char *str)
92 if (kstrtoint(str, 0, &_shift))
93 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
95 sched_thermal_decay_shift = clamp(_shift, 0, 10);
98 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
102 * For asym packing, by default the lower numbered CPU has higher priority.
104 int __weak arch_asym_cpu_priority(int cpu)
110 * The margin used when comparing utilization with CPU capacity.
114 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
118 #ifdef CONFIG_CFS_BANDWIDTH
120 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
121 * each time a cfs_rq requests quota.
123 * Note: in the case that the slice exceeds the runtime remaining (either due
124 * to consumption or the quota being specified to be smaller than the slice)
125 * we will always only issue the remaining available time.
127 * (default: 5 msec, units: microseconds)
129 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
132 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
138 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
144 static inline void update_load_set(struct load_weight *lw, unsigned long w)
151 * Increase the granularity value when there are more CPUs,
152 * because with more CPUs the 'effective latency' as visible
153 * to users decreases. But the relationship is not linear,
154 * so pick a second-best guess by going with the log2 of the
157 * This idea comes from the SD scheduler of Con Kolivas:
159 static unsigned int get_update_sysctl_factor(void)
161 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
164 switch (sysctl_sched_tunable_scaling) {
165 case SCHED_TUNABLESCALING_NONE:
168 case SCHED_TUNABLESCALING_LINEAR:
171 case SCHED_TUNABLESCALING_LOG:
173 factor = 1 + ilog2(cpus);
180 static void update_sysctl(void)
182 unsigned int factor = get_update_sysctl_factor();
184 #define SET_SYSCTL(name) \
185 (sysctl_##name = (factor) * normalized_sysctl_##name)
186 SET_SYSCTL(sched_min_granularity);
187 SET_SYSCTL(sched_latency);
188 SET_SYSCTL(sched_wakeup_granularity);
192 void __init sched_init_granularity(void)
197 #define WMULT_CONST (~0U)
198 #define WMULT_SHIFT 32
200 static void __update_inv_weight(struct load_weight *lw)
204 if (likely(lw->inv_weight))
207 w = scale_load_down(lw->weight);
209 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
211 else if (unlikely(!w))
212 lw->inv_weight = WMULT_CONST;
214 lw->inv_weight = WMULT_CONST / w;
218 * delta_exec * weight / lw.weight
220 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
222 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
223 * we're guaranteed shift stays positive because inv_weight is guaranteed to
224 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
226 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
227 * weight/lw.weight <= 1, and therefore our shift will also be positive.
229 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
231 u64 fact = scale_load_down(weight);
232 int shift = WMULT_SHIFT;
234 __update_inv_weight(lw);
236 if (unlikely(fact >> 32)) {
243 fact = mul_u32_u32(fact, lw->inv_weight);
250 return mul_u64_u32_shr(delta_exec, fact, shift);
254 const struct sched_class fair_sched_class;
256 /**************************************************************
257 * CFS operations on generic schedulable entities:
260 #ifdef CONFIG_FAIR_GROUP_SCHED
261 static inline struct task_struct *task_of(struct sched_entity *se)
263 SCHED_WARN_ON(!entity_is_task(se));
264 return container_of(se, struct task_struct, se);
267 /* Walk up scheduling entities hierarchy */
268 #define for_each_sched_entity(se) \
269 for (; se; se = se->parent)
271 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
276 /* runqueue on which this entity is (to be) queued */
277 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
282 /* runqueue "owned" by this group */
283 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
288 static inline void cfs_rq_tg_path(struct cfs_rq *cfs_rq, char *path, int len)
293 if (cfs_rq && task_group_is_autogroup(cfs_rq->tg))
294 autogroup_path(cfs_rq->tg, path, len);
295 else if (cfs_rq && cfs_rq->tg->css.cgroup)
296 cgroup_path(cfs_rq->tg->css.cgroup, path, len);
298 strlcpy(path, "(null)", len);
301 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
303 struct rq *rq = rq_of(cfs_rq);
304 int cpu = cpu_of(rq);
307 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
312 * Ensure we either appear before our parent (if already
313 * enqueued) or force our parent to appear after us when it is
314 * enqueued. The fact that we always enqueue bottom-up
315 * reduces this to two cases and a special case for the root
316 * cfs_rq. Furthermore, it also means that we will always reset
317 * tmp_alone_branch either when the branch is connected
318 * to a tree or when we reach the top of the tree
320 if (cfs_rq->tg->parent &&
321 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
323 * If parent is already on the list, we add the child
324 * just before. Thanks to circular linked property of
325 * the list, this means to put the child at the tail
326 * of the list that starts by parent.
328 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
329 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
331 * The branch is now connected to its tree so we can
332 * reset tmp_alone_branch to the beginning of the
335 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
339 if (!cfs_rq->tg->parent) {
341 * cfs rq without parent should be put
342 * at the tail of the list.
344 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
345 &rq->leaf_cfs_rq_list);
347 * We have reach the top of a tree so we can reset
348 * tmp_alone_branch to the beginning of the list.
350 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
355 * The parent has not already been added so we want to
356 * make sure that it will be put after us.
357 * tmp_alone_branch points to the begin of the branch
358 * where we will add parent.
360 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
362 * update tmp_alone_branch to points to the new begin
365 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
369 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
371 if (cfs_rq->on_list) {
372 struct rq *rq = rq_of(cfs_rq);
375 * With cfs_rq being unthrottled/throttled during an enqueue,
376 * it can happen the tmp_alone_branch points the a leaf that
377 * we finally want to del. In this case, tmp_alone_branch moves
378 * to the prev element but it will point to rq->leaf_cfs_rq_list
379 * at the end of the enqueue.
381 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
382 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
384 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
389 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
391 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
394 /* Iterate thr' all leaf cfs_rq's on a runqueue */
395 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
396 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
399 /* Do the two (enqueued) entities belong to the same group ? */
400 static inline struct cfs_rq *
401 is_same_group(struct sched_entity *se, struct sched_entity *pse)
403 if (se->cfs_rq == pse->cfs_rq)
409 static inline struct sched_entity *parent_entity(struct sched_entity *se)
415 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
417 int se_depth, pse_depth;
420 * preemption test can be made between sibling entities who are in the
421 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
422 * both tasks until we find their ancestors who are siblings of common
426 /* First walk up until both entities are at same depth */
427 se_depth = (*se)->depth;
428 pse_depth = (*pse)->depth;
430 while (se_depth > pse_depth) {
432 *se = parent_entity(*se);
435 while (pse_depth > se_depth) {
437 *pse = parent_entity(*pse);
440 while (!is_same_group(*se, *pse)) {
441 *se = parent_entity(*se);
442 *pse = parent_entity(*pse);
446 #else /* !CONFIG_FAIR_GROUP_SCHED */
448 static inline struct task_struct *task_of(struct sched_entity *se)
450 return container_of(se, struct task_struct, se);
453 #define for_each_sched_entity(se) \
454 for (; se; se = NULL)
456 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
458 return &task_rq(p)->cfs;
461 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
463 struct task_struct *p = task_of(se);
464 struct rq *rq = task_rq(p);
469 /* runqueue "owned" by this group */
470 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
475 static inline void cfs_rq_tg_path(struct cfs_rq *cfs_rq, char *path, int len)
478 strlcpy(path, "(null)", len);
481 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
486 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
490 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
494 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
495 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
497 static inline struct sched_entity *parent_entity(struct sched_entity *se)
503 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
507 #endif /* CONFIG_FAIR_GROUP_SCHED */
509 static __always_inline
510 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
512 /**************************************************************
513 * Scheduling class tree data structure manipulation methods:
516 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
518 s64 delta = (s64)(vruntime - max_vruntime);
520 max_vruntime = vruntime;
525 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
527 s64 delta = (s64)(vruntime - min_vruntime);
529 min_vruntime = vruntime;
534 static inline bool entity_before(struct sched_entity *a,
535 struct sched_entity *b)
537 return (s64)(a->vruntime - b->vruntime) < 0;
540 #define __node_2_se(node) \
541 rb_entry((node), struct sched_entity, run_node)
543 static void update_min_vruntime(struct cfs_rq *cfs_rq)
545 struct sched_entity *curr = cfs_rq->curr;
546 struct rb_node *leftmost = rb_first_cached(&cfs_rq->tasks_timeline);
548 u64 vruntime = cfs_rq->min_vruntime;
552 vruntime = curr->vruntime;
557 if (leftmost) { /* non-empty tree */
558 struct sched_entity *se = __node_2_se(leftmost);
561 vruntime = se->vruntime;
563 vruntime = min_vruntime(vruntime, se->vruntime);
566 /* ensure we never gain time by being placed backwards. */
567 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
570 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
574 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
576 return entity_before(__node_2_se(a), __node_2_se(b));
580 * Enqueue an entity into the rb-tree:
582 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
584 rb_add_cached(&se->run_node, &cfs_rq->tasks_timeline, __entity_less);
587 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
589 rb_erase_cached(&se->run_node, &cfs_rq->tasks_timeline);
592 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
594 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
599 return __node_2_se(left);
602 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
604 struct rb_node *next = rb_next(&se->run_node);
609 return __node_2_se(next);
612 #ifdef CONFIG_SCHED_DEBUG
613 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
615 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
620 return __node_2_se(last);
623 /**************************************************************
624 * Scheduling class statistics methods:
627 int sched_proc_update_handler(struct ctl_table *table, int write,
628 void *buffer, size_t *lenp, loff_t *ppos)
630 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
631 unsigned int factor = get_update_sysctl_factor();
636 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
637 sysctl_sched_min_granularity);
639 #define WRT_SYSCTL(name) \
640 (normalized_sysctl_##name = sysctl_##name / (factor))
641 WRT_SYSCTL(sched_min_granularity);
642 WRT_SYSCTL(sched_latency);
643 WRT_SYSCTL(sched_wakeup_granularity);
653 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
655 if (unlikely(se->load.weight != NICE_0_LOAD))
656 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
662 * The idea is to set a period in which each task runs once.
664 * When there are too many tasks (sched_nr_latency) we have to stretch
665 * this period because otherwise the slices get too small.
667 * p = (nr <= nl) ? l : l*nr/nl
669 static u64 __sched_period(unsigned long nr_running)
671 if (unlikely(nr_running > sched_nr_latency))
672 return nr_running * sysctl_sched_min_granularity;
674 return sysctl_sched_latency;
678 * We calculate the wall-time slice from the period by taking a part
679 * proportional to the weight.
683 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
685 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
687 for_each_sched_entity(se) {
688 struct load_weight *load;
689 struct load_weight lw;
691 cfs_rq = cfs_rq_of(se);
692 load = &cfs_rq->load;
694 if (unlikely(!se->on_rq)) {
697 update_load_add(&lw, se->load.weight);
700 slice = __calc_delta(slice, se->load.weight, load);
706 * We calculate the vruntime slice of a to-be-inserted task.
710 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
712 return calc_delta_fair(sched_slice(cfs_rq, se), se);
718 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
719 static unsigned long task_h_load(struct task_struct *p);
720 static unsigned long capacity_of(int cpu);
722 /* Give new sched_entity start runnable values to heavy its load in infant time */
723 void init_entity_runnable_average(struct sched_entity *se)
725 struct sched_avg *sa = &se->avg;
727 memset(sa, 0, sizeof(*sa));
730 * Tasks are initialized with full load to be seen as heavy tasks until
731 * they get a chance to stabilize to their real load level.
732 * Group entities are initialized with zero load to reflect the fact that
733 * nothing has been attached to the task group yet.
735 if (entity_is_task(se))
736 sa->load_avg = scale_load_down(se->load.weight);
738 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
741 static void attach_entity_cfs_rq(struct sched_entity *se);
744 * With new tasks being created, their initial util_avgs are extrapolated
745 * based on the cfs_rq's current util_avg:
747 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
749 * However, in many cases, the above util_avg does not give a desired
750 * value. Moreover, the sum of the util_avgs may be divergent, such
751 * as when the series is a harmonic series.
753 * To solve this problem, we also cap the util_avg of successive tasks to
754 * only 1/2 of the left utilization budget:
756 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
758 * where n denotes the nth task and cpu_scale the CPU capacity.
760 * For example, for a CPU with 1024 of capacity, a simplest series from
761 * the beginning would be like:
763 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
764 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
766 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
767 * if util_avg > util_avg_cap.
769 void post_init_entity_util_avg(struct task_struct *p)
771 struct sched_entity *se = &p->se;
772 struct cfs_rq *cfs_rq = cfs_rq_of(se);
773 struct sched_avg *sa = &se->avg;
774 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
775 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
778 if (cfs_rq->avg.util_avg != 0) {
779 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
780 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
782 if (sa->util_avg > cap)
789 sa->runnable_avg = sa->util_avg;
791 if (p->sched_class != &fair_sched_class) {
793 * For !fair tasks do:
795 update_cfs_rq_load_avg(now, cfs_rq);
796 attach_entity_load_avg(cfs_rq, se);
797 switched_from_fair(rq, p);
799 * such that the next switched_to_fair() has the
802 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
806 attach_entity_cfs_rq(se);
809 #else /* !CONFIG_SMP */
810 void init_entity_runnable_average(struct sched_entity *se)
813 void post_init_entity_util_avg(struct task_struct *p)
816 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
819 #endif /* CONFIG_SMP */
822 * Update the current task's runtime statistics.
824 static void update_curr(struct cfs_rq *cfs_rq)
826 struct sched_entity *curr = cfs_rq->curr;
827 u64 now = rq_clock_task(rq_of(cfs_rq));
833 delta_exec = now - curr->exec_start;
834 if (unlikely((s64)delta_exec <= 0))
837 curr->exec_start = now;
839 schedstat_set(curr->statistics.exec_max,
840 max(delta_exec, curr->statistics.exec_max));
842 curr->sum_exec_runtime += delta_exec;
843 schedstat_add(cfs_rq->exec_clock, delta_exec);
845 curr->vruntime += calc_delta_fair(delta_exec, curr);
846 update_min_vruntime(cfs_rq);
848 if (entity_is_task(curr)) {
849 struct task_struct *curtask = task_of(curr);
851 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
852 cgroup_account_cputime(curtask, delta_exec);
853 account_group_exec_runtime(curtask, delta_exec);
856 account_cfs_rq_runtime(cfs_rq, delta_exec);
859 static void update_curr_fair(struct rq *rq)
861 update_curr(cfs_rq_of(&rq->curr->se));
865 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
867 u64 wait_start, prev_wait_start;
869 if (!schedstat_enabled())
872 wait_start = rq_clock(rq_of(cfs_rq));
873 prev_wait_start = schedstat_val(se->statistics.wait_start);
875 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
876 likely(wait_start > prev_wait_start))
877 wait_start -= prev_wait_start;
879 __schedstat_set(se->statistics.wait_start, wait_start);
883 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
885 struct task_struct *p;
888 if (!schedstat_enabled())
892 * When the sched_schedstat changes from 0 to 1, some sched se
893 * maybe already in the runqueue, the se->statistics.wait_start
894 * will be 0.So it will let the delta wrong. We need to avoid this
897 if (unlikely(!schedstat_val(se->statistics.wait_start)))
900 delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
902 if (entity_is_task(se)) {
904 if (task_on_rq_migrating(p)) {
906 * Preserve migrating task's wait time so wait_start
907 * time stamp can be adjusted to accumulate wait time
908 * prior to migration.
910 __schedstat_set(se->statistics.wait_start, delta);
913 trace_sched_stat_wait(p, delta);
916 __schedstat_set(se->statistics.wait_max,
917 max(schedstat_val(se->statistics.wait_max), delta));
918 __schedstat_inc(se->statistics.wait_count);
919 __schedstat_add(se->statistics.wait_sum, delta);
920 __schedstat_set(se->statistics.wait_start, 0);
924 update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
926 struct task_struct *tsk = NULL;
927 u64 sleep_start, block_start;
929 if (!schedstat_enabled())
932 sleep_start = schedstat_val(se->statistics.sleep_start);
933 block_start = schedstat_val(se->statistics.block_start);
935 if (entity_is_task(se))
939 u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
944 if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
945 __schedstat_set(se->statistics.sleep_max, delta);
947 __schedstat_set(se->statistics.sleep_start, 0);
948 __schedstat_add(se->statistics.sum_sleep_runtime, delta);
951 account_scheduler_latency(tsk, delta >> 10, 1);
952 trace_sched_stat_sleep(tsk, delta);
956 u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
961 if (unlikely(delta > schedstat_val(se->statistics.block_max)))
962 __schedstat_set(se->statistics.block_max, delta);
964 __schedstat_set(se->statistics.block_start, 0);
965 __schedstat_add(se->statistics.sum_sleep_runtime, delta);
968 if (tsk->in_iowait) {
969 __schedstat_add(se->statistics.iowait_sum, delta);
970 __schedstat_inc(se->statistics.iowait_count);
971 trace_sched_stat_iowait(tsk, delta);
974 trace_sched_stat_blocked(tsk, delta);
977 * Blocking time is in units of nanosecs, so shift by
978 * 20 to get a milliseconds-range estimation of the
979 * amount of time that the task spent sleeping:
981 if (unlikely(prof_on == SLEEP_PROFILING)) {
982 profile_hits(SLEEP_PROFILING,
983 (void *)get_wchan(tsk),
986 account_scheduler_latency(tsk, delta >> 10, 0);
992 * Task is being enqueued - update stats:
995 update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
997 if (!schedstat_enabled())
1001 * Are we enqueueing a waiting task? (for current tasks
1002 * a dequeue/enqueue event is a NOP)
1004 if (se != cfs_rq->curr)
1005 update_stats_wait_start(cfs_rq, se);
1007 if (flags & ENQUEUE_WAKEUP)
1008 update_stats_enqueue_sleeper(cfs_rq, se);
1012 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1015 if (!schedstat_enabled())
1019 * Mark the end of the wait period if dequeueing a
1022 if (se != cfs_rq->curr)
1023 update_stats_wait_end(cfs_rq, se);
1025 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1026 struct task_struct *tsk = task_of(se);
1028 if (tsk->state & TASK_INTERRUPTIBLE)
1029 __schedstat_set(se->statistics.sleep_start,
1030 rq_clock(rq_of(cfs_rq)));
1031 if (tsk->state & TASK_UNINTERRUPTIBLE)
1032 __schedstat_set(se->statistics.block_start,
1033 rq_clock(rq_of(cfs_rq)));
1038 * We are picking a new current task - update its stats:
1041 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1044 * We are starting a new run period:
1046 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1049 /**************************************************
1050 * Scheduling class queueing methods:
1053 #ifdef CONFIG_NUMA_BALANCING
1055 * Approximate time to scan a full NUMA task in ms. The task scan period is
1056 * calculated based on the tasks virtual memory size and
1057 * numa_balancing_scan_size.
1059 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1060 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1062 /* Portion of address space to scan in MB */
1063 unsigned int sysctl_numa_balancing_scan_size = 256;
1065 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1066 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1069 refcount_t refcount;
1071 spinlock_t lock; /* nr_tasks, tasks */
1076 struct rcu_head rcu;
1077 unsigned long total_faults;
1078 unsigned long max_faults_cpu;
1080 * Faults_cpu is used to decide whether memory should move
1081 * towards the CPU. As a consequence, these stats are weighted
1082 * more by CPU use than by memory faults.
1084 unsigned long *faults_cpu;
1085 unsigned long faults[];
1089 * For functions that can be called in multiple contexts that permit reading
1090 * ->numa_group (see struct task_struct for locking rules).
1092 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1094 return rcu_dereference_check(p->numa_group, p == current ||
1095 (lockdep_is_held(&task_rq(p)->lock) && !READ_ONCE(p->on_cpu)));
1098 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1100 return rcu_dereference_protected(p->numa_group, p == current);
1103 static inline unsigned long group_faults_priv(struct numa_group *ng);
1104 static inline unsigned long group_faults_shared(struct numa_group *ng);
1106 static unsigned int task_nr_scan_windows(struct task_struct *p)
1108 unsigned long rss = 0;
1109 unsigned long nr_scan_pages;
1112 * Calculations based on RSS as non-present and empty pages are skipped
1113 * by the PTE scanner and NUMA hinting faults should be trapped based
1116 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1117 rss = get_mm_rss(p->mm);
1119 rss = nr_scan_pages;
1121 rss = round_up(rss, nr_scan_pages);
1122 return rss / nr_scan_pages;
1125 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1126 #define MAX_SCAN_WINDOW 2560
1128 static unsigned int task_scan_min(struct task_struct *p)
1130 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1131 unsigned int scan, floor;
1132 unsigned int windows = 1;
1134 if (scan_size < MAX_SCAN_WINDOW)
1135 windows = MAX_SCAN_WINDOW / scan_size;
1136 floor = 1000 / windows;
1138 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1139 return max_t(unsigned int, floor, scan);
1142 static unsigned int task_scan_start(struct task_struct *p)
1144 unsigned long smin = task_scan_min(p);
1145 unsigned long period = smin;
1146 struct numa_group *ng;
1148 /* Scale the maximum scan period with the amount of shared memory. */
1150 ng = rcu_dereference(p->numa_group);
1152 unsigned long shared = group_faults_shared(ng);
1153 unsigned long private = group_faults_priv(ng);
1155 period *= refcount_read(&ng->refcount);
1156 period *= shared + 1;
1157 period /= private + shared + 1;
1161 return max(smin, period);
1164 static unsigned int task_scan_max(struct task_struct *p)
1166 unsigned long smin = task_scan_min(p);
1168 struct numa_group *ng;
1170 /* Watch for min being lower than max due to floor calculations */
1171 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1173 /* Scale the maximum scan period with the amount of shared memory. */
1174 ng = deref_curr_numa_group(p);
1176 unsigned long shared = group_faults_shared(ng);
1177 unsigned long private = group_faults_priv(ng);
1178 unsigned long period = smax;
1180 period *= refcount_read(&ng->refcount);
1181 period *= shared + 1;
1182 period /= private + shared + 1;
1184 smax = max(smax, period);
1187 return max(smin, smax);
1190 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1192 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1193 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1196 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1198 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1199 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1202 /* Shared or private faults. */
1203 #define NR_NUMA_HINT_FAULT_TYPES 2
1205 /* Memory and CPU locality */
1206 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1208 /* Averaged statistics, and temporary buffers. */
1209 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1211 pid_t task_numa_group_id(struct task_struct *p)
1213 struct numa_group *ng;
1217 ng = rcu_dereference(p->numa_group);
1226 * The averaged statistics, shared & private, memory & CPU,
1227 * occupy the first half of the array. The second half of the
1228 * array is for current counters, which are averaged into the
1229 * first set by task_numa_placement.
1231 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1233 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1236 static inline unsigned long task_faults(struct task_struct *p, int nid)
1238 if (!p->numa_faults)
1241 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1242 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1245 static inline unsigned long group_faults(struct task_struct *p, int nid)
1247 struct numa_group *ng = deref_task_numa_group(p);
1252 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1253 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1256 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1258 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
1259 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
1262 static inline unsigned long group_faults_priv(struct numa_group *ng)
1264 unsigned long faults = 0;
1267 for_each_online_node(node) {
1268 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1274 static inline unsigned long group_faults_shared(struct numa_group *ng)
1276 unsigned long faults = 0;
1279 for_each_online_node(node) {
1280 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1287 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1288 * considered part of a numa group's pseudo-interleaving set. Migrations
1289 * between these nodes are slowed down, to allow things to settle down.
1291 #define ACTIVE_NODE_FRACTION 3
1293 static bool numa_is_active_node(int nid, struct numa_group *ng)
1295 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1298 /* Handle placement on systems where not all nodes are directly connected. */
1299 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1300 int maxdist, bool task)
1302 unsigned long score = 0;
1306 * All nodes are directly connected, and the same distance
1307 * from each other. No need for fancy placement algorithms.
1309 if (sched_numa_topology_type == NUMA_DIRECT)
1313 * This code is called for each node, introducing N^2 complexity,
1314 * which should be ok given the number of nodes rarely exceeds 8.
1316 for_each_online_node(node) {
1317 unsigned long faults;
1318 int dist = node_distance(nid, node);
1321 * The furthest away nodes in the system are not interesting
1322 * for placement; nid was already counted.
1324 if (dist == sched_max_numa_distance || node == nid)
1328 * On systems with a backplane NUMA topology, compare groups
1329 * of nodes, and move tasks towards the group with the most
1330 * memory accesses. When comparing two nodes at distance
1331 * "hoplimit", only nodes closer by than "hoplimit" are part
1332 * of each group. Skip other nodes.
1334 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1338 /* Add up the faults from nearby nodes. */
1340 faults = task_faults(p, node);
1342 faults = group_faults(p, node);
1345 * On systems with a glueless mesh NUMA topology, there are
1346 * no fixed "groups of nodes". Instead, nodes that are not
1347 * directly connected bounce traffic through intermediate
1348 * nodes; a numa_group can occupy any set of nodes.
1349 * The further away a node is, the less the faults count.
1350 * This seems to result in good task placement.
1352 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1353 faults *= (sched_max_numa_distance - dist);
1354 faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
1364 * These return the fraction of accesses done by a particular task, or
1365 * task group, on a particular numa node. The group weight is given a
1366 * larger multiplier, in order to group tasks together that are almost
1367 * evenly spread out between numa nodes.
1369 static inline unsigned long task_weight(struct task_struct *p, int nid,
1372 unsigned long faults, total_faults;
1374 if (!p->numa_faults)
1377 total_faults = p->total_numa_faults;
1382 faults = task_faults(p, nid);
1383 faults += score_nearby_nodes(p, nid, dist, true);
1385 return 1000 * faults / total_faults;
1388 static inline unsigned long group_weight(struct task_struct *p, int nid,
1391 struct numa_group *ng = deref_task_numa_group(p);
1392 unsigned long faults, total_faults;
1397 total_faults = ng->total_faults;
1402 faults = group_faults(p, nid);
1403 faults += score_nearby_nodes(p, nid, dist, false);
1405 return 1000 * faults / total_faults;
1408 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1409 int src_nid, int dst_cpu)
1411 struct numa_group *ng = deref_curr_numa_group(p);
1412 int dst_nid = cpu_to_node(dst_cpu);
1413 int last_cpupid, this_cpupid;
1415 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1416 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1419 * Allow first faults or private faults to migrate immediately early in
1420 * the lifetime of a task. The magic number 4 is based on waiting for
1421 * two full passes of the "multi-stage node selection" test that is
1424 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1425 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1429 * Multi-stage node selection is used in conjunction with a periodic
1430 * migration fault to build a temporal task<->page relation. By using
1431 * a two-stage filter we remove short/unlikely relations.
1433 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1434 * a task's usage of a particular page (n_p) per total usage of this
1435 * page (n_t) (in a given time-span) to a probability.
1437 * Our periodic faults will sample this probability and getting the
1438 * same result twice in a row, given these samples are fully
1439 * independent, is then given by P(n)^2, provided our sample period
1440 * is sufficiently short compared to the usage pattern.
1442 * This quadric squishes small probabilities, making it less likely we
1443 * act on an unlikely task<->page relation.
1445 if (!cpupid_pid_unset(last_cpupid) &&
1446 cpupid_to_nid(last_cpupid) != dst_nid)
1449 /* Always allow migrate on private faults */
1450 if (cpupid_match_pid(p, last_cpupid))
1453 /* A shared fault, but p->numa_group has not been set up yet. */
1458 * Destination node is much more heavily used than the source
1459 * node? Allow migration.
1461 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1462 ACTIVE_NODE_FRACTION)
1466 * Distribute memory according to CPU & memory use on each node,
1467 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1469 * faults_cpu(dst) 3 faults_cpu(src)
1470 * --------------- * - > ---------------
1471 * faults_mem(dst) 4 faults_mem(src)
1473 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1474 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1478 * 'numa_type' describes the node at the moment of load balancing.
1481 /* The node has spare capacity that can be used to run more tasks. */
1484 * The node is fully used and the tasks don't compete for more CPU
1485 * cycles. Nevertheless, some tasks might wait before running.
1489 * The node is overloaded and can't provide expected CPU cycles to all
1495 /* Cached statistics for all CPUs within a node */
1498 unsigned long runnable;
1500 /* Total compute capacity of CPUs on a node */
1501 unsigned long compute_capacity;
1502 unsigned int nr_running;
1503 unsigned int weight;
1504 enum numa_type node_type;
1508 static inline bool is_core_idle(int cpu)
1510 #ifdef CONFIG_SCHED_SMT
1513 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1525 struct task_numa_env {
1526 struct task_struct *p;
1528 int src_cpu, src_nid;
1529 int dst_cpu, dst_nid;
1531 struct numa_stats src_stats, dst_stats;
1536 struct task_struct *best_task;
1541 static unsigned long cpu_load(struct rq *rq);
1542 static unsigned long cpu_runnable(struct rq *rq);
1543 static unsigned long cpu_util(int cpu);
1544 static inline long adjust_numa_imbalance(int imbalance,
1545 int dst_running, int dst_weight);
1548 numa_type numa_classify(unsigned int imbalance_pct,
1549 struct numa_stats *ns)
1551 if ((ns->nr_running > ns->weight) &&
1552 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
1553 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
1554 return node_overloaded;
1556 if ((ns->nr_running < ns->weight) ||
1557 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
1558 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
1559 return node_has_spare;
1561 return node_fully_busy;
1564 #ifdef CONFIG_SCHED_SMT
1565 /* Forward declarations of select_idle_sibling helpers */
1566 static inline bool test_idle_cores(int cpu, bool def);
1567 static inline int numa_idle_core(int idle_core, int cpu)
1569 if (!static_branch_likely(&sched_smt_present) ||
1570 idle_core >= 0 || !test_idle_cores(cpu, false))
1574 * Prefer cores instead of packing HT siblings
1575 * and triggering future load balancing.
1577 if (is_core_idle(cpu))
1583 static inline int numa_idle_core(int idle_core, int cpu)
1590 * Gather all necessary information to make NUMA balancing placement
1591 * decisions that are compatible with standard load balancer. This
1592 * borrows code and logic from update_sg_lb_stats but sharing a
1593 * common implementation is impractical.
1595 static void update_numa_stats(struct task_numa_env *env,
1596 struct numa_stats *ns, int nid,
1599 int cpu, idle_core = -1;
1601 memset(ns, 0, sizeof(*ns));
1605 for_each_cpu(cpu, cpumask_of_node(nid)) {
1606 struct rq *rq = cpu_rq(cpu);
1608 ns->load += cpu_load(rq);
1609 ns->runnable += cpu_runnable(rq);
1610 ns->util += cpu_util(cpu);
1611 ns->nr_running += rq->cfs.h_nr_running;
1612 ns->compute_capacity += capacity_of(cpu);
1614 if (find_idle && !rq->nr_running && idle_cpu(cpu)) {
1615 if (READ_ONCE(rq->numa_migrate_on) ||
1616 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
1619 if (ns->idle_cpu == -1)
1622 idle_core = numa_idle_core(idle_core, cpu);
1627 ns->weight = cpumask_weight(cpumask_of_node(nid));
1629 ns->node_type = numa_classify(env->imbalance_pct, ns);
1632 ns->idle_cpu = idle_core;
1635 static void task_numa_assign(struct task_numa_env *env,
1636 struct task_struct *p, long imp)
1638 struct rq *rq = cpu_rq(env->dst_cpu);
1640 /* Check if run-queue part of active NUMA balance. */
1641 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
1643 int start = env->dst_cpu;
1645 /* Find alternative idle CPU. */
1646 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start) {
1647 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
1648 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
1653 rq = cpu_rq(env->dst_cpu);
1654 if (!xchg(&rq->numa_migrate_on, 1))
1658 /* Failed to find an alternative idle CPU */
1664 * Clear previous best_cpu/rq numa-migrate flag, since task now
1665 * found a better CPU to move/swap.
1667 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
1668 rq = cpu_rq(env->best_cpu);
1669 WRITE_ONCE(rq->numa_migrate_on, 0);
1673 put_task_struct(env->best_task);
1678 env->best_imp = imp;
1679 env->best_cpu = env->dst_cpu;
1682 static bool load_too_imbalanced(long src_load, long dst_load,
1683 struct task_numa_env *env)
1686 long orig_src_load, orig_dst_load;
1687 long src_capacity, dst_capacity;
1690 * The load is corrected for the CPU capacity available on each node.
1693 * ------------ vs ---------
1694 * src_capacity dst_capacity
1696 src_capacity = env->src_stats.compute_capacity;
1697 dst_capacity = env->dst_stats.compute_capacity;
1699 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
1701 orig_src_load = env->src_stats.load;
1702 orig_dst_load = env->dst_stats.load;
1704 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
1706 /* Would this change make things worse? */
1707 return (imb > old_imb);
1711 * Maximum NUMA importance can be 1998 (2*999);
1712 * SMALLIMP @ 30 would be close to 1998/64.
1713 * Used to deter task migration.
1718 * This checks if the overall compute and NUMA accesses of the system would
1719 * be improved if the source tasks was migrated to the target dst_cpu taking
1720 * into account that it might be best if task running on the dst_cpu should
1721 * be exchanged with the source task
1723 static bool task_numa_compare(struct task_numa_env *env,
1724 long taskimp, long groupimp, bool maymove)
1726 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
1727 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1728 long imp = p_ng ? groupimp : taskimp;
1729 struct task_struct *cur;
1730 long src_load, dst_load;
1731 int dist = env->dist;
1734 bool stopsearch = false;
1736 if (READ_ONCE(dst_rq->numa_migrate_on))
1740 cur = rcu_dereference(dst_rq->curr);
1741 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
1745 * Because we have preemption enabled we can get migrated around and
1746 * end try selecting ourselves (current == env->p) as a swap candidate.
1748 if (cur == env->p) {
1754 if (maymove && moveimp >= env->best_imp)
1760 /* Skip this swap candidate if cannot move to the source cpu. */
1761 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
1765 * Skip this swap candidate if it is not moving to its preferred
1766 * node and the best task is.
1768 if (env->best_task &&
1769 env->best_task->numa_preferred_nid == env->src_nid &&
1770 cur->numa_preferred_nid != env->src_nid) {
1775 * "imp" is the fault differential for the source task between the
1776 * source and destination node. Calculate the total differential for
1777 * the source task and potential destination task. The more negative
1778 * the value is, the more remote accesses that would be expected to
1779 * be incurred if the tasks were swapped.
1781 * If dst and source tasks are in the same NUMA group, or not
1782 * in any group then look only at task weights.
1784 cur_ng = rcu_dereference(cur->numa_group);
1785 if (cur_ng == p_ng) {
1786 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1787 task_weight(cur, env->dst_nid, dist);
1789 * Add some hysteresis to prevent swapping the
1790 * tasks within a group over tiny differences.
1796 * Compare the group weights. If a task is all by itself
1797 * (not part of a group), use the task weight instead.
1800 imp += group_weight(cur, env->src_nid, dist) -
1801 group_weight(cur, env->dst_nid, dist);
1803 imp += task_weight(cur, env->src_nid, dist) -
1804 task_weight(cur, env->dst_nid, dist);
1807 /* Discourage picking a task already on its preferred node */
1808 if (cur->numa_preferred_nid == env->dst_nid)
1812 * Encourage picking a task that moves to its preferred node.
1813 * This potentially makes imp larger than it's maximum of
1814 * 1998 (see SMALLIMP and task_weight for why) but in this
1815 * case, it does not matter.
1817 if (cur->numa_preferred_nid == env->src_nid)
1820 if (maymove && moveimp > imp && moveimp > env->best_imp) {
1827 * Prefer swapping with a task moving to its preferred node over a
1830 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
1831 env->best_task->numa_preferred_nid != env->src_nid) {
1836 * If the NUMA importance is less than SMALLIMP,
1837 * task migration might only result in ping pong
1838 * of tasks and also hurt performance due to cache
1841 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
1845 * In the overloaded case, try and keep the load balanced.
1847 load = task_h_load(env->p) - task_h_load(cur);
1851 dst_load = env->dst_stats.load + load;
1852 src_load = env->src_stats.load - load;
1854 if (load_too_imbalanced(src_load, dst_load, env))
1858 /* Evaluate an idle CPU for a task numa move. */
1860 int cpu = env->dst_stats.idle_cpu;
1862 /* Nothing cached so current CPU went idle since the search. */
1867 * If the CPU is no longer truly idle and the previous best CPU
1868 * is, keep using it.
1870 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
1871 idle_cpu(env->best_cpu)) {
1872 cpu = env->best_cpu;
1878 task_numa_assign(env, cur, imp);
1881 * If a move to idle is allowed because there is capacity or load
1882 * balance improves then stop the search. While a better swap
1883 * candidate may exist, a search is not free.
1885 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
1889 * If a swap candidate must be identified and the current best task
1890 * moves its preferred node then stop the search.
1892 if (!maymove && env->best_task &&
1893 env->best_task->numa_preferred_nid == env->src_nid) {
1902 static void task_numa_find_cpu(struct task_numa_env *env,
1903 long taskimp, long groupimp)
1905 bool maymove = false;
1909 * If dst node has spare capacity, then check if there is an
1910 * imbalance that would be overruled by the load balancer.
1912 if (env->dst_stats.node_type == node_has_spare) {
1913 unsigned int imbalance;
1914 int src_running, dst_running;
1917 * Would movement cause an imbalance? Note that if src has
1918 * more running tasks that the imbalance is ignored as the
1919 * move improves the imbalance from the perspective of the
1920 * CPU load balancer.
1922 src_running = env->src_stats.nr_running - 1;
1923 dst_running = env->dst_stats.nr_running + 1;
1924 imbalance = max(0, dst_running - src_running);
1925 imbalance = adjust_numa_imbalance(imbalance, dst_running,
1926 env->dst_stats.weight);
1928 /* Use idle CPU if there is no imbalance */
1931 if (env->dst_stats.idle_cpu >= 0) {
1932 env->dst_cpu = env->dst_stats.idle_cpu;
1933 task_numa_assign(env, NULL, 0);
1938 long src_load, dst_load, load;
1940 * If the improvement from just moving env->p direction is better
1941 * than swapping tasks around, check if a move is possible.
1943 load = task_h_load(env->p);
1944 dst_load = env->dst_stats.load + load;
1945 src_load = env->src_stats.load - load;
1946 maymove = !load_too_imbalanced(src_load, dst_load, env);
1949 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1950 /* Skip this CPU if the source task cannot migrate */
1951 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
1955 if (task_numa_compare(env, taskimp, groupimp, maymove))
1960 static int task_numa_migrate(struct task_struct *p)
1962 struct task_numa_env env = {
1965 .src_cpu = task_cpu(p),
1966 .src_nid = task_node(p),
1968 .imbalance_pct = 112,
1974 unsigned long taskweight, groupweight;
1975 struct sched_domain *sd;
1976 long taskimp, groupimp;
1977 struct numa_group *ng;
1982 * Pick the lowest SD_NUMA domain, as that would have the smallest
1983 * imbalance and would be the first to start moving tasks about.
1985 * And we want to avoid any moving of tasks about, as that would create
1986 * random movement of tasks -- counter the numa conditions we're trying
1990 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
1992 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
1996 * Cpusets can break the scheduler domain tree into smaller
1997 * balance domains, some of which do not cross NUMA boundaries.
1998 * Tasks that are "trapped" in such domains cannot be migrated
1999 * elsewhere, so there is no point in (re)trying.
2001 if (unlikely(!sd)) {
2002 sched_setnuma(p, task_node(p));
2006 env.dst_nid = p->numa_preferred_nid;
2007 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2008 taskweight = task_weight(p, env.src_nid, dist);
2009 groupweight = group_weight(p, env.src_nid, dist);
2010 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2011 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2012 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2013 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2015 /* Try to find a spot on the preferred nid. */
2016 task_numa_find_cpu(&env, taskimp, groupimp);
2019 * Look at other nodes in these cases:
2020 * - there is no space available on the preferred_nid
2021 * - the task is part of a numa_group that is interleaved across
2022 * multiple NUMA nodes; in order to better consolidate the group,
2023 * we need to check other locations.
2025 ng = deref_curr_numa_group(p);
2026 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2027 for_each_online_node(nid) {
2028 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2031 dist = node_distance(env.src_nid, env.dst_nid);
2032 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2034 taskweight = task_weight(p, env.src_nid, dist);
2035 groupweight = group_weight(p, env.src_nid, dist);
2038 /* Only consider nodes where both task and groups benefit */
2039 taskimp = task_weight(p, nid, dist) - taskweight;
2040 groupimp = group_weight(p, nid, dist) - groupweight;
2041 if (taskimp < 0 && groupimp < 0)
2046 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2047 task_numa_find_cpu(&env, taskimp, groupimp);
2052 * If the task is part of a workload that spans multiple NUMA nodes,
2053 * and is migrating into one of the workload's active nodes, remember
2054 * this node as the task's preferred numa node, so the workload can
2056 * A task that migrated to a second choice node will be better off
2057 * trying for a better one later. Do not set the preferred node here.
2060 if (env.best_cpu == -1)
2063 nid = cpu_to_node(env.best_cpu);
2065 if (nid != p->numa_preferred_nid)
2066 sched_setnuma(p, nid);
2069 /* No better CPU than the current one was found. */
2070 if (env.best_cpu == -1) {
2071 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2075 best_rq = cpu_rq(env.best_cpu);
2076 if (env.best_task == NULL) {
2077 ret = migrate_task_to(p, env.best_cpu);
2078 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2080 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2084 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2085 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2088 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2089 put_task_struct(env.best_task);
2093 /* Attempt to migrate a task to a CPU on the preferred node. */
2094 static void numa_migrate_preferred(struct task_struct *p)
2096 unsigned long interval = HZ;
2098 /* This task has no NUMA fault statistics yet */
2099 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2102 /* Periodically retry migrating the task to the preferred node */
2103 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2104 p->numa_migrate_retry = jiffies + interval;
2106 /* Success if task is already running on preferred CPU */
2107 if (task_node(p) == p->numa_preferred_nid)
2110 /* Otherwise, try migrate to a CPU on the preferred node */
2111 task_numa_migrate(p);
2115 * Find out how many nodes on the workload is actively running on. Do this by
2116 * tracking the nodes from which NUMA hinting faults are triggered. This can
2117 * be different from the set of nodes where the workload's memory is currently
2120 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2122 unsigned long faults, max_faults = 0;
2123 int nid, active_nodes = 0;
2125 for_each_online_node(nid) {
2126 faults = group_faults_cpu(numa_group, nid);
2127 if (faults > max_faults)
2128 max_faults = faults;
2131 for_each_online_node(nid) {
2132 faults = group_faults_cpu(numa_group, nid);
2133 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2137 numa_group->max_faults_cpu = max_faults;
2138 numa_group->active_nodes = active_nodes;
2142 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2143 * increments. The more local the fault statistics are, the higher the scan
2144 * period will be for the next scan window. If local/(local+remote) ratio is
2145 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2146 * the scan period will decrease. Aim for 70% local accesses.
2148 #define NUMA_PERIOD_SLOTS 10
2149 #define NUMA_PERIOD_THRESHOLD 7
2152 * Increase the scan period (slow down scanning) if the majority of
2153 * our memory is already on our local node, or if the majority of
2154 * the page accesses are shared with other processes.
2155 * Otherwise, decrease the scan period.
2157 static void update_task_scan_period(struct task_struct *p,
2158 unsigned long shared, unsigned long private)
2160 unsigned int period_slot;
2161 int lr_ratio, ps_ratio;
2164 unsigned long remote = p->numa_faults_locality[0];
2165 unsigned long local = p->numa_faults_locality[1];
2168 * If there were no record hinting faults then either the task is
2169 * completely idle or all activity is areas that are not of interest
2170 * to automatic numa balancing. Related to that, if there were failed
2171 * migration then it implies we are migrating too quickly or the local
2172 * node is overloaded. In either case, scan slower
2174 if (local + shared == 0 || p->numa_faults_locality[2]) {
2175 p->numa_scan_period = min(p->numa_scan_period_max,
2176 p->numa_scan_period << 1);
2178 p->mm->numa_next_scan = jiffies +
2179 msecs_to_jiffies(p->numa_scan_period);
2185 * Prepare to scale scan period relative to the current period.
2186 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2187 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2188 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2190 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2191 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2192 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2194 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2196 * Most memory accesses are local. There is no need to
2197 * do fast NUMA scanning, since memory is already local.
2199 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2202 diff = slot * period_slot;
2203 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2205 * Most memory accesses are shared with other tasks.
2206 * There is no point in continuing fast NUMA scanning,
2207 * since other tasks may just move the memory elsewhere.
2209 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2212 diff = slot * period_slot;
2215 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2216 * yet they are not on the local NUMA node. Speed up
2217 * NUMA scanning to get the memory moved over.
2219 int ratio = max(lr_ratio, ps_ratio);
2220 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2223 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2224 task_scan_min(p), task_scan_max(p));
2225 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2229 * Get the fraction of time the task has been running since the last
2230 * NUMA placement cycle. The scheduler keeps similar statistics, but
2231 * decays those on a 32ms period, which is orders of magnitude off
2232 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2233 * stats only if the task is so new there are no NUMA statistics yet.
2235 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2237 u64 runtime, delta, now;
2238 /* Use the start of this time slice to avoid calculations. */
2239 now = p->se.exec_start;
2240 runtime = p->se.sum_exec_runtime;
2242 if (p->last_task_numa_placement) {
2243 delta = runtime - p->last_sum_exec_runtime;
2244 *period = now - p->last_task_numa_placement;
2246 /* Avoid time going backwards, prevent potential divide error: */
2247 if (unlikely((s64)*period < 0))
2250 delta = p->se.avg.load_sum;
2251 *period = LOAD_AVG_MAX;
2254 p->last_sum_exec_runtime = runtime;
2255 p->last_task_numa_placement = now;
2261 * Determine the preferred nid for a task in a numa_group. This needs to
2262 * be done in a way that produces consistent results with group_weight,
2263 * otherwise workloads might not converge.
2265 static int preferred_group_nid(struct task_struct *p, int nid)
2270 /* Direct connections between all NUMA nodes. */
2271 if (sched_numa_topology_type == NUMA_DIRECT)
2275 * On a system with glueless mesh NUMA topology, group_weight
2276 * scores nodes according to the number of NUMA hinting faults on
2277 * both the node itself, and on nearby nodes.
2279 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2280 unsigned long score, max_score = 0;
2281 int node, max_node = nid;
2283 dist = sched_max_numa_distance;
2285 for_each_online_node(node) {
2286 score = group_weight(p, node, dist);
2287 if (score > max_score) {
2296 * Finding the preferred nid in a system with NUMA backplane
2297 * interconnect topology is more involved. The goal is to locate
2298 * tasks from numa_groups near each other in the system, and
2299 * untangle workloads from different sides of the system. This requires
2300 * searching down the hierarchy of node groups, recursively searching
2301 * inside the highest scoring group of nodes. The nodemask tricks
2302 * keep the complexity of the search down.
2304 nodes = node_online_map;
2305 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2306 unsigned long max_faults = 0;
2307 nodemask_t max_group = NODE_MASK_NONE;
2310 /* Are there nodes at this distance from each other? */
2311 if (!find_numa_distance(dist))
2314 for_each_node_mask(a, nodes) {
2315 unsigned long faults = 0;
2316 nodemask_t this_group;
2317 nodes_clear(this_group);
2319 /* Sum group's NUMA faults; includes a==b case. */
2320 for_each_node_mask(b, nodes) {
2321 if (node_distance(a, b) < dist) {
2322 faults += group_faults(p, b);
2323 node_set(b, this_group);
2324 node_clear(b, nodes);
2328 /* Remember the top group. */
2329 if (faults > max_faults) {
2330 max_faults = faults;
2331 max_group = this_group;
2333 * subtle: at the smallest distance there is
2334 * just one node left in each "group", the
2335 * winner is the preferred nid.
2340 /* Next round, evaluate the nodes within max_group. */
2348 static void task_numa_placement(struct task_struct *p)
2350 int seq, nid, max_nid = NUMA_NO_NODE;
2351 unsigned long max_faults = 0;
2352 unsigned long fault_types[2] = { 0, 0 };
2353 unsigned long total_faults;
2354 u64 runtime, period;
2355 spinlock_t *group_lock = NULL;
2356 struct numa_group *ng;
2359 * The p->mm->numa_scan_seq field gets updated without
2360 * exclusive access. Use READ_ONCE() here to ensure
2361 * that the field is read in a single access:
2363 seq = READ_ONCE(p->mm->numa_scan_seq);
2364 if (p->numa_scan_seq == seq)
2366 p->numa_scan_seq = seq;
2367 p->numa_scan_period_max = task_scan_max(p);
2369 total_faults = p->numa_faults_locality[0] +
2370 p->numa_faults_locality[1];
2371 runtime = numa_get_avg_runtime(p, &period);
2373 /* If the task is part of a group prevent parallel updates to group stats */
2374 ng = deref_curr_numa_group(p);
2376 group_lock = &ng->lock;
2377 spin_lock_irq(group_lock);
2380 /* Find the node with the highest number of faults */
2381 for_each_online_node(nid) {
2382 /* Keep track of the offsets in numa_faults array */
2383 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2384 unsigned long faults = 0, group_faults = 0;
2387 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2388 long diff, f_diff, f_weight;
2390 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2391 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2392 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2393 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2395 /* Decay existing window, copy faults since last scan */
2396 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2397 fault_types[priv] += p->numa_faults[membuf_idx];
2398 p->numa_faults[membuf_idx] = 0;
2401 * Normalize the faults_from, so all tasks in a group
2402 * count according to CPU use, instead of by the raw
2403 * number of faults. Tasks with little runtime have
2404 * little over-all impact on throughput, and thus their
2405 * faults are less important.
2407 f_weight = div64_u64(runtime << 16, period + 1);
2408 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2410 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2411 p->numa_faults[cpubuf_idx] = 0;
2413 p->numa_faults[mem_idx] += diff;
2414 p->numa_faults[cpu_idx] += f_diff;
2415 faults += p->numa_faults[mem_idx];
2416 p->total_numa_faults += diff;
2419 * safe because we can only change our own group
2421 * mem_idx represents the offset for a given
2422 * nid and priv in a specific region because it
2423 * is at the beginning of the numa_faults array.
2425 ng->faults[mem_idx] += diff;
2426 ng->faults_cpu[mem_idx] += f_diff;
2427 ng->total_faults += diff;
2428 group_faults += ng->faults[mem_idx];
2433 if (faults > max_faults) {
2434 max_faults = faults;
2437 } else if (group_faults > max_faults) {
2438 max_faults = group_faults;
2444 numa_group_count_active_nodes(ng);
2445 spin_unlock_irq(group_lock);
2446 max_nid = preferred_group_nid(p, max_nid);
2450 /* Set the new preferred node */
2451 if (max_nid != p->numa_preferred_nid)
2452 sched_setnuma(p, max_nid);
2455 update_task_scan_period(p, fault_types[0], fault_types[1]);
2458 static inline int get_numa_group(struct numa_group *grp)
2460 return refcount_inc_not_zero(&grp->refcount);
2463 static inline void put_numa_group(struct numa_group *grp)
2465 if (refcount_dec_and_test(&grp->refcount))
2466 kfree_rcu(grp, rcu);
2469 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2472 struct numa_group *grp, *my_grp;
2473 struct task_struct *tsk;
2475 int cpu = cpupid_to_cpu(cpupid);
2478 if (unlikely(!deref_curr_numa_group(p))) {
2479 unsigned int size = sizeof(struct numa_group) +
2480 4*nr_node_ids*sizeof(unsigned long);
2482 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2486 refcount_set(&grp->refcount, 1);
2487 grp->active_nodes = 1;
2488 grp->max_faults_cpu = 0;
2489 spin_lock_init(&grp->lock);
2491 /* Second half of the array tracks nids where faults happen */
2492 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2495 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2496 grp->faults[i] = p->numa_faults[i];
2498 grp->total_faults = p->total_numa_faults;
2501 rcu_assign_pointer(p->numa_group, grp);
2505 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2507 if (!cpupid_match_pid(tsk, cpupid))
2510 grp = rcu_dereference(tsk->numa_group);
2514 my_grp = deref_curr_numa_group(p);
2519 * Only join the other group if its bigger; if we're the bigger group,
2520 * the other task will join us.
2522 if (my_grp->nr_tasks > grp->nr_tasks)
2526 * Tie-break on the grp address.
2528 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2531 /* Always join threads in the same process. */
2532 if (tsk->mm == current->mm)
2535 /* Simple filter to avoid false positives due to PID collisions */
2536 if (flags & TNF_SHARED)
2539 /* Update priv based on whether false sharing was detected */
2542 if (join && !get_numa_group(grp))
2550 BUG_ON(irqs_disabled());
2551 double_lock_irq(&my_grp->lock, &grp->lock);
2553 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2554 my_grp->faults[i] -= p->numa_faults[i];
2555 grp->faults[i] += p->numa_faults[i];
2557 my_grp->total_faults -= p->total_numa_faults;
2558 grp->total_faults += p->total_numa_faults;
2563 spin_unlock(&my_grp->lock);
2564 spin_unlock_irq(&grp->lock);
2566 rcu_assign_pointer(p->numa_group, grp);
2568 put_numa_group(my_grp);
2577 * Get rid of NUMA staticstics associated with a task (either current or dead).
2578 * If @final is set, the task is dead and has reached refcount zero, so we can
2579 * safely free all relevant data structures. Otherwise, there might be
2580 * concurrent reads from places like load balancing and procfs, and we should
2581 * reset the data back to default state without freeing ->numa_faults.
2583 void task_numa_free(struct task_struct *p, bool final)
2585 /* safe: p either is current or is being freed by current */
2586 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
2587 unsigned long *numa_faults = p->numa_faults;
2588 unsigned long flags;
2595 spin_lock_irqsave(&grp->lock, flags);
2596 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2597 grp->faults[i] -= p->numa_faults[i];
2598 grp->total_faults -= p->total_numa_faults;
2601 spin_unlock_irqrestore(&grp->lock, flags);
2602 RCU_INIT_POINTER(p->numa_group, NULL);
2603 put_numa_group(grp);
2607 p->numa_faults = NULL;
2610 p->total_numa_faults = 0;
2611 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2617 * Got a PROT_NONE fault for a page on @node.
2619 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2621 struct task_struct *p = current;
2622 bool migrated = flags & TNF_MIGRATED;
2623 int cpu_node = task_node(current);
2624 int local = !!(flags & TNF_FAULT_LOCAL);
2625 struct numa_group *ng;
2628 if (!static_branch_likely(&sched_numa_balancing))
2631 /* for example, ksmd faulting in a user's mm */
2635 /* Allocate buffer to track faults on a per-node basis */
2636 if (unlikely(!p->numa_faults)) {
2637 int size = sizeof(*p->numa_faults) *
2638 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2640 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2641 if (!p->numa_faults)
2644 p->total_numa_faults = 0;
2645 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2649 * First accesses are treated as private, otherwise consider accesses
2650 * to be private if the accessing pid has not changed
2652 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2655 priv = cpupid_match_pid(p, last_cpupid);
2656 if (!priv && !(flags & TNF_NO_GROUP))
2657 task_numa_group(p, last_cpupid, flags, &priv);
2661 * If a workload spans multiple NUMA nodes, a shared fault that
2662 * occurs wholly within the set of nodes that the workload is
2663 * actively using should be counted as local. This allows the
2664 * scan rate to slow down when a workload has settled down.
2666 ng = deref_curr_numa_group(p);
2667 if (!priv && !local && ng && ng->active_nodes > 1 &&
2668 numa_is_active_node(cpu_node, ng) &&
2669 numa_is_active_node(mem_node, ng))
2673 * Retry to migrate task to preferred node periodically, in case it
2674 * previously failed, or the scheduler moved us.
2676 if (time_after(jiffies, p->numa_migrate_retry)) {
2677 task_numa_placement(p);
2678 numa_migrate_preferred(p);
2682 p->numa_pages_migrated += pages;
2683 if (flags & TNF_MIGRATE_FAIL)
2684 p->numa_faults_locality[2] += pages;
2686 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2687 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2688 p->numa_faults_locality[local] += pages;
2691 static void reset_ptenuma_scan(struct task_struct *p)
2694 * We only did a read acquisition of the mmap sem, so
2695 * p->mm->numa_scan_seq is written to without exclusive access
2696 * and the update is not guaranteed to be atomic. That's not
2697 * much of an issue though, since this is just used for
2698 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2699 * expensive, to avoid any form of compiler optimizations:
2701 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
2702 p->mm->numa_scan_offset = 0;
2706 * The expensive part of numa migration is done from task_work context.
2707 * Triggered from task_tick_numa().
2709 static void task_numa_work(struct callback_head *work)
2711 unsigned long migrate, next_scan, now = jiffies;
2712 struct task_struct *p = current;
2713 struct mm_struct *mm = p->mm;
2714 u64 runtime = p->se.sum_exec_runtime;
2715 struct vm_area_struct *vma;
2716 unsigned long start, end;
2717 unsigned long nr_pte_updates = 0;
2718 long pages, virtpages;
2720 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
2724 * Who cares about NUMA placement when they're dying.
2726 * NOTE: make sure not to dereference p->mm before this check,
2727 * exit_task_work() happens _after_ exit_mm() so we could be called
2728 * without p->mm even though we still had it when we enqueued this
2731 if (p->flags & PF_EXITING)
2734 if (!mm->numa_next_scan) {
2735 mm->numa_next_scan = now +
2736 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2740 * Enforce maximal scan/migration frequency..
2742 migrate = mm->numa_next_scan;
2743 if (time_before(now, migrate))
2746 if (p->numa_scan_period == 0) {
2747 p->numa_scan_period_max = task_scan_max(p);
2748 p->numa_scan_period = task_scan_start(p);
2751 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2752 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2756 * Delay this task enough that another task of this mm will likely win
2757 * the next time around.
2759 p->node_stamp += 2 * TICK_NSEC;
2761 start = mm->numa_scan_offset;
2762 pages = sysctl_numa_balancing_scan_size;
2763 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2764 virtpages = pages * 8; /* Scan up to this much virtual space */
2769 if (!mmap_read_trylock(mm))
2771 vma = find_vma(mm, start);
2773 reset_ptenuma_scan(p);
2777 for (; vma; vma = vma->vm_next) {
2778 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
2779 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
2784 * Shared library pages mapped by multiple processes are not
2785 * migrated as it is expected they are cache replicated. Avoid
2786 * hinting faults in read-only file-backed mappings or the vdso
2787 * as migrating the pages will be of marginal benefit.
2790 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2794 * Skip inaccessible VMAs to avoid any confusion between
2795 * PROT_NONE and NUMA hinting ptes
2797 if (!vma_is_accessible(vma))
2801 start = max(start, vma->vm_start);
2802 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2803 end = min(end, vma->vm_end);
2804 nr_pte_updates = change_prot_numa(vma, start, end);
2807 * Try to scan sysctl_numa_balancing_size worth of
2808 * hpages that have at least one present PTE that
2809 * is not already pte-numa. If the VMA contains
2810 * areas that are unused or already full of prot_numa
2811 * PTEs, scan up to virtpages, to skip through those
2815 pages -= (end - start) >> PAGE_SHIFT;
2816 virtpages -= (end - start) >> PAGE_SHIFT;
2819 if (pages <= 0 || virtpages <= 0)
2823 } while (end != vma->vm_end);
2828 * It is possible to reach the end of the VMA list but the last few
2829 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2830 * would find the !migratable VMA on the next scan but not reset the
2831 * scanner to the start so check it now.
2834 mm->numa_scan_offset = start;
2836 reset_ptenuma_scan(p);
2837 mmap_read_unlock(mm);
2840 * Make sure tasks use at least 32x as much time to run other code
2841 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2842 * Usually update_task_scan_period slows down scanning enough; on an
2843 * overloaded system we need to limit overhead on a per task basis.
2845 if (unlikely(p->se.sum_exec_runtime != runtime)) {
2846 u64 diff = p->se.sum_exec_runtime - runtime;
2847 p->node_stamp += 32 * diff;
2851 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
2854 struct mm_struct *mm = p->mm;
2857 mm_users = atomic_read(&mm->mm_users);
2858 if (mm_users == 1) {
2859 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2860 mm->numa_scan_seq = 0;
2864 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
2865 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
2866 /* Protect against double add, see task_tick_numa and task_numa_work */
2867 p->numa_work.next = &p->numa_work;
2868 p->numa_faults = NULL;
2869 RCU_INIT_POINTER(p->numa_group, NULL);
2870 p->last_task_numa_placement = 0;
2871 p->last_sum_exec_runtime = 0;
2873 init_task_work(&p->numa_work, task_numa_work);
2875 /* New address space, reset the preferred nid */
2876 if (!(clone_flags & CLONE_VM)) {
2877 p->numa_preferred_nid = NUMA_NO_NODE;
2882 * New thread, keep existing numa_preferred_nid which should be copied
2883 * already by arch_dup_task_struct but stagger when scans start.
2888 delay = min_t(unsigned int, task_scan_max(current),
2889 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
2890 delay += 2 * TICK_NSEC;
2891 p->node_stamp = delay;
2896 * Drive the periodic memory faults..
2898 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2900 struct callback_head *work = &curr->numa_work;
2904 * We don't care about NUMA placement if we don't have memory.
2906 if ((curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
2910 * Using runtime rather than walltime has the dual advantage that
2911 * we (mostly) drive the selection from busy threads and that the
2912 * task needs to have done some actual work before we bother with
2915 now = curr->se.sum_exec_runtime;
2916 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2918 if (now > curr->node_stamp + period) {
2919 if (!curr->node_stamp)
2920 curr->numa_scan_period = task_scan_start(curr);
2921 curr->node_stamp += period;
2923 if (!time_before(jiffies, curr->mm->numa_next_scan))
2924 task_work_add(curr, work, TWA_RESUME);
2928 static void update_scan_period(struct task_struct *p, int new_cpu)
2930 int src_nid = cpu_to_node(task_cpu(p));
2931 int dst_nid = cpu_to_node(new_cpu);
2933 if (!static_branch_likely(&sched_numa_balancing))
2936 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
2939 if (src_nid == dst_nid)
2943 * Allow resets if faults have been trapped before one scan
2944 * has completed. This is most likely due to a new task that
2945 * is pulled cross-node due to wakeups or load balancing.
2947 if (p->numa_scan_seq) {
2949 * Avoid scan adjustments if moving to the preferred
2950 * node or if the task was not previously running on
2951 * the preferred node.
2953 if (dst_nid == p->numa_preferred_nid ||
2954 (p->numa_preferred_nid != NUMA_NO_NODE &&
2955 src_nid != p->numa_preferred_nid))
2959 p->numa_scan_period = task_scan_start(p);
2963 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2967 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2971 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2975 static inline void update_scan_period(struct task_struct *p, int new_cpu)
2979 #endif /* CONFIG_NUMA_BALANCING */
2982 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2984 update_load_add(&cfs_rq->load, se->load.weight);
2986 if (entity_is_task(se)) {
2987 struct rq *rq = rq_of(cfs_rq);
2989 account_numa_enqueue(rq, task_of(se));
2990 list_add(&se->group_node, &rq->cfs_tasks);
2993 cfs_rq->nr_running++;
2997 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2999 update_load_sub(&cfs_rq->load, se->load.weight);
3001 if (entity_is_task(se)) {
3002 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3003 list_del_init(&se->group_node);
3006 cfs_rq->nr_running--;
3010 * Signed add and clamp on underflow.
3012 * Explicitly do a load-store to ensure the intermediate value never hits
3013 * memory. This allows lockless observations without ever seeing the negative
3016 #define add_positive(_ptr, _val) do { \
3017 typeof(_ptr) ptr = (_ptr); \
3018 typeof(_val) val = (_val); \
3019 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3023 if (val < 0 && res > var) \
3026 WRITE_ONCE(*ptr, res); \
3030 * Unsigned subtract and clamp on underflow.
3032 * Explicitly do a load-store to ensure the intermediate value never hits
3033 * memory. This allows lockless observations without ever seeing the negative
3036 #define sub_positive(_ptr, _val) do { \
3037 typeof(_ptr) ptr = (_ptr); \
3038 typeof(*ptr) val = (_val); \
3039 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3043 WRITE_ONCE(*ptr, res); \
3047 * Remove and clamp on negative, from a local variable.
3049 * A variant of sub_positive(), which does not use explicit load-store
3050 * and is thus optimized for local variable updates.
3052 #define lsub_positive(_ptr, _val) do { \
3053 typeof(_ptr) ptr = (_ptr); \
3054 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3059 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3061 cfs_rq->avg.load_avg += se->avg.load_avg;
3062 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3066 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3068 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3069 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3073 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3075 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3078 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3079 unsigned long weight)
3082 /* commit outstanding execution time */
3083 if (cfs_rq->curr == se)
3084 update_curr(cfs_rq);
3085 update_load_sub(&cfs_rq->load, se->load.weight);
3087 dequeue_load_avg(cfs_rq, se);
3089 update_load_set(&se->load, weight);
3093 u32 divider = get_pelt_divider(&se->avg);
3095 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3099 enqueue_load_avg(cfs_rq, se);
3101 update_load_add(&cfs_rq->load, se->load.weight);
3105 void reweight_task(struct task_struct *p, int prio)
3107 struct sched_entity *se = &p->se;
3108 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3109 struct load_weight *load = &se->load;
3110 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3112 reweight_entity(cfs_rq, se, weight);
3113 load->inv_weight = sched_prio_to_wmult[prio];
3116 #ifdef CONFIG_FAIR_GROUP_SCHED
3119 * All this does is approximate the hierarchical proportion which includes that
3120 * global sum we all love to hate.
3122 * That is, the weight of a group entity, is the proportional share of the
3123 * group weight based on the group runqueue weights. That is:
3125 * tg->weight * grq->load.weight
3126 * ge->load.weight = ----------------------------- (1)
3127 * \Sum grq->load.weight
3129 * Now, because computing that sum is prohibitively expensive to compute (been
3130 * there, done that) we approximate it with this average stuff. The average
3131 * moves slower and therefore the approximation is cheaper and more stable.
3133 * So instead of the above, we substitute:
3135 * grq->load.weight -> grq->avg.load_avg (2)
3137 * which yields the following:
3139 * tg->weight * grq->avg.load_avg
3140 * ge->load.weight = ------------------------------ (3)
3143 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3145 * That is shares_avg, and it is right (given the approximation (2)).
3147 * The problem with it is that because the average is slow -- it was designed
3148 * to be exactly that of course -- this leads to transients in boundary
3149 * conditions. In specific, the case where the group was idle and we start the
3150 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3151 * yielding bad latency etc..
3153 * Now, in that special case (1) reduces to:
3155 * tg->weight * grq->load.weight
3156 * ge->load.weight = ----------------------------- = tg->weight (4)
3159 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3161 * So what we do is modify our approximation (3) to approach (4) in the (near)
3166 * tg->weight * grq->load.weight
3167 * --------------------------------------------------- (5)
3168 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3170 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3171 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3174 * tg->weight * grq->load.weight
3175 * ge->load.weight = ----------------------------- (6)
3180 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3181 * max(grq->load.weight, grq->avg.load_avg)
3183 * And that is shares_weight and is icky. In the (near) UP case it approaches
3184 * (4) while in the normal case it approaches (3). It consistently
3185 * overestimates the ge->load.weight and therefore:
3187 * \Sum ge->load.weight >= tg->weight
3191 static long calc_group_shares(struct cfs_rq *cfs_rq)
3193 long tg_weight, tg_shares, load, shares;
3194 struct task_group *tg = cfs_rq->tg;
3196 tg_shares = READ_ONCE(tg->shares);
3198 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3200 tg_weight = atomic_long_read(&tg->load_avg);
3202 /* Ensure tg_weight >= load */
3203 tg_weight -= cfs_rq->tg_load_avg_contrib;
3206 shares = (tg_shares * load);
3208 shares /= tg_weight;
3211 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3212 * of a group with small tg->shares value. It is a floor value which is
3213 * assigned as a minimum load.weight to the sched_entity representing
3214 * the group on a CPU.
3216 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3217 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3218 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3219 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3222 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3224 #endif /* CONFIG_SMP */
3226 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3229 * Recomputes the group entity based on the current state of its group
3232 static void update_cfs_group(struct sched_entity *se)
3234 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3240 if (throttled_hierarchy(gcfs_rq))
3244 shares = READ_ONCE(gcfs_rq->tg->shares);
3246 if (likely(se->load.weight == shares))
3249 shares = calc_group_shares(gcfs_rq);
3252 reweight_entity(cfs_rq_of(se), se, shares);
3255 #else /* CONFIG_FAIR_GROUP_SCHED */
3256 static inline void update_cfs_group(struct sched_entity *se)
3259 #endif /* CONFIG_FAIR_GROUP_SCHED */
3261 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3263 struct rq *rq = rq_of(cfs_rq);
3265 if (&rq->cfs == cfs_rq) {
3267 * There are a few boundary cases this might miss but it should
3268 * get called often enough that that should (hopefully) not be
3271 * It will not get called when we go idle, because the idle
3272 * thread is a different class (!fair), nor will the utilization
3273 * number include things like RT tasks.
3275 * As is, the util number is not freq-invariant (we'd have to
3276 * implement arch_scale_freq_capacity() for that).
3280 cpufreq_update_util(rq, flags);
3285 #ifdef CONFIG_FAIR_GROUP_SCHED
3287 * update_tg_load_avg - update the tg's load avg
3288 * @cfs_rq: the cfs_rq whose avg changed
3290 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3291 * However, because tg->load_avg is a global value there are performance
3294 * In order to avoid having to look at the other cfs_rq's, we use a
3295 * differential update where we store the last value we propagated. This in
3296 * turn allows skipping updates if the differential is 'small'.
3298 * Updating tg's load_avg is necessary before update_cfs_share().
3300 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
3302 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3305 * No need to update load_avg for root_task_group as it is not used.
3307 if (cfs_rq->tg == &root_task_group)
3310 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3311 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3312 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3317 * Called within set_task_rq() right before setting a task's CPU. The
3318 * caller only guarantees p->pi_lock is held; no other assumptions,
3319 * including the state of rq->lock, should be made.
3321 void set_task_rq_fair(struct sched_entity *se,
3322 struct cfs_rq *prev, struct cfs_rq *next)
3324 u64 p_last_update_time;
3325 u64 n_last_update_time;
3327 if (!sched_feat(ATTACH_AGE_LOAD))
3331 * We are supposed to update the task to "current" time, then its up to
3332 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3333 * getting what current time is, so simply throw away the out-of-date
3334 * time. This will result in the wakee task is less decayed, but giving
3335 * the wakee more load sounds not bad.
3337 if (!(se->avg.last_update_time && prev))
3340 #ifndef CONFIG_64BIT
3342 u64 p_last_update_time_copy;
3343 u64 n_last_update_time_copy;
3346 p_last_update_time_copy = prev->load_last_update_time_copy;
3347 n_last_update_time_copy = next->load_last_update_time_copy;
3351 p_last_update_time = prev->avg.last_update_time;
3352 n_last_update_time = next->avg.last_update_time;
3354 } while (p_last_update_time != p_last_update_time_copy ||
3355 n_last_update_time != n_last_update_time_copy);
3358 p_last_update_time = prev->avg.last_update_time;
3359 n_last_update_time = next->avg.last_update_time;
3361 __update_load_avg_blocked_se(p_last_update_time, se);
3362 se->avg.last_update_time = n_last_update_time;
3367 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3368 * propagate its contribution. The key to this propagation is the invariant
3369 * that for each group:
3371 * ge->avg == grq->avg (1)
3373 * _IFF_ we look at the pure running and runnable sums. Because they
3374 * represent the very same entity, just at different points in the hierarchy.
3376 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
3377 * and simply copies the running/runnable sum over (but still wrong, because
3378 * the group entity and group rq do not have their PELT windows aligned).
3380 * However, update_tg_cfs_load() is more complex. So we have:
3382 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
3384 * And since, like util, the runnable part should be directly transferable,
3385 * the following would _appear_ to be the straight forward approach:
3387 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
3389 * And per (1) we have:
3391 * ge->avg.runnable_avg == grq->avg.runnable_avg
3395 * ge->load.weight * grq->avg.load_avg
3396 * ge->avg.load_avg = ----------------------------------- (4)
3399 * Except that is wrong!
3401 * Because while for entities historical weight is not important and we
3402 * really only care about our future and therefore can consider a pure
3403 * runnable sum, runqueues can NOT do this.
3405 * We specifically want runqueues to have a load_avg that includes
3406 * historical weights. Those represent the blocked load, the load we expect
3407 * to (shortly) return to us. This only works by keeping the weights as
3408 * integral part of the sum. We therefore cannot decompose as per (3).
3410 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
3411 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
3412 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
3413 * runnable section of these tasks overlap (or not). If they were to perfectly
3414 * align the rq as a whole would be runnable 2/3 of the time. If however we
3415 * always have at least 1 runnable task, the rq as a whole is always runnable.
3417 * So we'll have to approximate.. :/
3419 * Given the constraint:
3421 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
3423 * We can construct a rule that adds runnable to a rq by assuming minimal
3426 * On removal, we'll assume each task is equally runnable; which yields:
3428 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
3430 * XXX: only do this for the part of runnable > running ?
3435 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3437 long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
3440 /* Nothing to update */
3445 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3446 * See ___update_load_avg() for details.
3448 divider = get_pelt_divider(&cfs_rq->avg);
3450 /* Set new sched_entity's utilization */
3451 se->avg.util_avg = gcfs_rq->avg.util_avg;
3452 se->avg.util_sum = se->avg.util_avg * divider;
3454 /* Update parent cfs_rq utilization */
3455 add_positive(&cfs_rq->avg.util_avg, delta);
3456 cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * divider;
3460 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3462 long delta = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
3465 /* Nothing to update */
3470 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3471 * See ___update_load_avg() for details.
3473 divider = get_pelt_divider(&cfs_rq->avg);
3475 /* Set new sched_entity's runnable */
3476 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
3477 se->avg.runnable_sum = se->avg.runnable_avg * divider;
3479 /* Update parent cfs_rq runnable */
3480 add_positive(&cfs_rq->avg.runnable_avg, delta);
3481 cfs_rq->avg.runnable_sum = cfs_rq->avg.runnable_avg * divider;
3485 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3487 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
3488 unsigned long load_avg;
3496 gcfs_rq->prop_runnable_sum = 0;
3499 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3500 * See ___update_load_avg() for details.
3502 divider = get_pelt_divider(&cfs_rq->avg);
3504 if (runnable_sum >= 0) {
3506 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
3507 * the CPU is saturated running == runnable.
3509 runnable_sum += se->avg.load_sum;
3510 runnable_sum = min_t(long, runnable_sum, divider);
3513 * Estimate the new unweighted runnable_sum of the gcfs_rq by
3514 * assuming all tasks are equally runnable.
3516 if (scale_load_down(gcfs_rq->load.weight)) {
3517 load_sum = div_s64(gcfs_rq->avg.load_sum,
3518 scale_load_down(gcfs_rq->load.weight));
3521 /* But make sure to not inflate se's runnable */
3522 runnable_sum = min(se->avg.load_sum, load_sum);
3526 * runnable_sum can't be lower than running_sum
3527 * Rescale running sum to be in the same range as runnable sum
3528 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
3529 * runnable_sum is in [0 : LOAD_AVG_MAX]
3531 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
3532 runnable_sum = max(runnable_sum, running_sum);
3534 load_sum = (s64)se_weight(se) * runnable_sum;
3535 load_avg = div_s64(load_sum, divider);
3537 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
3538 delta_avg = load_avg - se->avg.load_avg;
3540 se->avg.load_sum = runnable_sum;
3541 se->avg.load_avg = load_avg;
3542 add_positive(&cfs_rq->avg.load_avg, delta_avg);
3543 add_positive(&cfs_rq->avg.load_sum, delta_sum);
3546 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
3548 cfs_rq->propagate = 1;
3549 cfs_rq->prop_runnable_sum += runnable_sum;
3552 /* Update task and its cfs_rq load average */
3553 static inline int propagate_entity_load_avg(struct sched_entity *se)
3555 struct cfs_rq *cfs_rq, *gcfs_rq;
3557 if (entity_is_task(se))
3560 gcfs_rq = group_cfs_rq(se);
3561 if (!gcfs_rq->propagate)
3564 gcfs_rq->propagate = 0;
3566 cfs_rq = cfs_rq_of(se);
3568 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
3570 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
3571 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
3572 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
3574 trace_pelt_cfs_tp(cfs_rq);
3575 trace_pelt_se_tp(se);
3581 * Check if we need to update the load and the utilization of a blocked
3584 static inline bool skip_blocked_update(struct sched_entity *se)
3586 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3589 * If sched_entity still have not zero load or utilization, we have to
3592 if (se->avg.load_avg || se->avg.util_avg)
3596 * If there is a pending propagation, we have to update the load and
3597 * the utilization of the sched_entity:
3599 if (gcfs_rq->propagate)
3603 * Otherwise, the load and the utilization of the sched_entity is
3604 * already zero and there is no pending propagation, so it will be a
3605 * waste of time to try to decay it:
3610 #else /* CONFIG_FAIR_GROUP_SCHED */
3612 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
3614 static inline int propagate_entity_load_avg(struct sched_entity *se)
3619 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
3621 #endif /* CONFIG_FAIR_GROUP_SCHED */
3624 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3625 * @now: current time, as per cfs_rq_clock_pelt()
3626 * @cfs_rq: cfs_rq to update
3628 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3629 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3630 * post_init_entity_util_avg().
3632 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3634 * Returns true if the load decayed or we removed load.
3636 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3637 * call update_tg_load_avg() when this function returns true.
3640 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
3642 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
3643 struct sched_avg *sa = &cfs_rq->avg;
3646 if (cfs_rq->removed.nr) {
3648 u32 divider = get_pelt_divider(&cfs_rq->avg);
3650 raw_spin_lock(&cfs_rq->removed.lock);
3651 swap(cfs_rq->removed.util_avg, removed_util);
3652 swap(cfs_rq->removed.load_avg, removed_load);
3653 swap(cfs_rq->removed.runnable_avg, removed_runnable);
3654 cfs_rq->removed.nr = 0;
3655 raw_spin_unlock(&cfs_rq->removed.lock);
3658 sub_positive(&sa->load_avg, r);
3659 sub_positive(&sa->load_sum, r * divider);
3662 sub_positive(&sa->util_avg, r);
3663 sub_positive(&sa->util_sum, r * divider);
3665 r = removed_runnable;
3666 sub_positive(&sa->runnable_avg, r);
3667 sub_positive(&sa->runnable_sum, r * divider);
3670 * removed_runnable is the unweighted version of removed_load so we
3671 * can use it to estimate removed_load_sum.
3673 add_tg_cfs_propagate(cfs_rq,
3674 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
3679 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
3681 #ifndef CONFIG_64BIT
3683 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3690 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3691 * @cfs_rq: cfs_rq to attach to
3692 * @se: sched_entity to attach
3694 * Must call update_cfs_rq_load_avg() before this, since we rely on
3695 * cfs_rq->avg.last_update_time being current.
3697 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3700 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
3701 * See ___update_load_avg() for details.
3703 u32 divider = get_pelt_divider(&cfs_rq->avg);
3706 * When we attach the @se to the @cfs_rq, we must align the decay
3707 * window because without that, really weird and wonderful things can
3712 se->avg.last_update_time = cfs_rq->avg.last_update_time;
3713 se->avg.period_contrib = cfs_rq->avg.period_contrib;
3716 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
3717 * period_contrib. This isn't strictly correct, but since we're
3718 * entirely outside of the PELT hierarchy, nobody cares if we truncate
3721 se->avg.util_sum = se->avg.util_avg * divider;
3723 se->avg.runnable_sum = se->avg.runnable_avg * divider;
3725 se->avg.load_sum = divider;
3726 if (se_weight(se)) {
3728 div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
3731 enqueue_load_avg(cfs_rq, se);
3732 cfs_rq->avg.util_avg += se->avg.util_avg;
3733 cfs_rq->avg.util_sum += se->avg.util_sum;
3734 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
3735 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
3737 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
3739 cfs_rq_util_change(cfs_rq, 0);
3741 trace_pelt_cfs_tp(cfs_rq);
3745 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3746 * @cfs_rq: cfs_rq to detach from
3747 * @se: sched_entity to detach
3749 * Must call update_cfs_rq_load_avg() before this, since we rely on
3750 * cfs_rq->avg.last_update_time being current.
3752 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3754 dequeue_load_avg(cfs_rq, se);
3755 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3756 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
3757 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
3758 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
3760 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
3762 cfs_rq_util_change(cfs_rq, 0);
3764 trace_pelt_cfs_tp(cfs_rq);
3768 * Optional action to be done while updating the load average
3770 #define UPDATE_TG 0x1
3771 #define SKIP_AGE_LOAD 0x2
3772 #define DO_ATTACH 0x4
3774 /* Update task and its cfs_rq load average */
3775 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3777 u64 now = cfs_rq_clock_pelt(cfs_rq);
3781 * Track task load average for carrying it to new CPU after migrated, and
3782 * track group sched_entity load average for task_h_load calc in migration
3784 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
3785 __update_load_avg_se(now, cfs_rq, se);
3787 decayed = update_cfs_rq_load_avg(now, cfs_rq);
3788 decayed |= propagate_entity_load_avg(se);
3790 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
3793 * DO_ATTACH means we're here from enqueue_entity().
3794 * !last_update_time means we've passed through
3795 * migrate_task_rq_fair() indicating we migrated.
3797 * IOW we're enqueueing a task on a new CPU.
3799 attach_entity_load_avg(cfs_rq, se);
3800 update_tg_load_avg(cfs_rq);
3802 } else if (decayed) {
3803 cfs_rq_util_change(cfs_rq, 0);
3805 if (flags & UPDATE_TG)
3806 update_tg_load_avg(cfs_rq);
3810 #ifndef CONFIG_64BIT
3811 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3813 u64 last_update_time_copy;
3814 u64 last_update_time;
3817 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3819 last_update_time = cfs_rq->avg.last_update_time;
3820 } while (last_update_time != last_update_time_copy);
3822 return last_update_time;
3825 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3827 return cfs_rq->avg.last_update_time;
3832 * Synchronize entity load avg of dequeued entity without locking
3835 static void sync_entity_load_avg(struct sched_entity *se)
3837 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3838 u64 last_update_time;
3840 last_update_time = cfs_rq_last_update_time(cfs_rq);
3841 __update_load_avg_blocked_se(last_update_time, se);
3845 * Task first catches up with cfs_rq, and then subtract
3846 * itself from the cfs_rq (task must be off the queue now).
3848 static void remove_entity_load_avg(struct sched_entity *se)
3850 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3851 unsigned long flags;
3854 * tasks cannot exit without having gone through wake_up_new_task() ->
3855 * post_init_entity_util_avg() which will have added things to the
3856 * cfs_rq, so we can remove unconditionally.
3859 sync_entity_load_avg(se);
3861 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
3862 ++cfs_rq->removed.nr;
3863 cfs_rq->removed.util_avg += se->avg.util_avg;
3864 cfs_rq->removed.load_avg += se->avg.load_avg;
3865 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
3866 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
3869 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
3871 return cfs_rq->avg.runnable_avg;
3874 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3876 return cfs_rq->avg.load_avg;
3879 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
3881 static inline unsigned long task_util(struct task_struct *p)
3883 return READ_ONCE(p->se.avg.util_avg);
3886 static inline unsigned long _task_util_est(struct task_struct *p)
3888 struct util_est ue = READ_ONCE(p->se.avg.util_est);
3890 return (max(ue.ewma, ue.enqueued) | UTIL_AVG_UNCHANGED);
3893 static inline unsigned long task_util_est(struct task_struct *p)
3895 return max(task_util(p), _task_util_est(p));
3898 #ifdef CONFIG_UCLAMP_TASK
3899 static inline unsigned long uclamp_task_util(struct task_struct *p)
3901 return clamp(task_util_est(p),
3902 uclamp_eff_value(p, UCLAMP_MIN),
3903 uclamp_eff_value(p, UCLAMP_MAX));
3906 static inline unsigned long uclamp_task_util(struct task_struct *p)
3908 return task_util_est(p);
3912 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
3913 struct task_struct *p)
3915 unsigned int enqueued;
3917 if (!sched_feat(UTIL_EST))
3920 /* Update root cfs_rq's estimated utilization */
3921 enqueued = cfs_rq->avg.util_est.enqueued;
3922 enqueued += _task_util_est(p);
3923 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3925 trace_sched_util_est_cfs_tp(cfs_rq);
3928 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
3929 struct task_struct *p)
3931 unsigned int enqueued;
3933 if (!sched_feat(UTIL_EST))
3936 /* Update root cfs_rq's estimated utilization */
3937 enqueued = cfs_rq->avg.util_est.enqueued;
3938 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
3939 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3941 trace_sched_util_est_cfs_tp(cfs_rq);
3945 * Check if a (signed) value is within a specified (unsigned) margin,
3946 * based on the observation that:
3948 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
3950 * NOTE: this only works when value + maring < INT_MAX.
3952 static inline bool within_margin(int value, int margin)
3954 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
3957 static inline void util_est_update(struct cfs_rq *cfs_rq,
3958 struct task_struct *p,
3961 long last_ewma_diff;
3964 if (!sched_feat(UTIL_EST))
3968 * Skip update of task's estimated utilization when the task has not
3969 * yet completed an activation, e.g. being migrated.
3975 * If the PELT values haven't changed since enqueue time,
3976 * skip the util_est update.
3978 ue = p->se.avg.util_est;
3979 if (ue.enqueued & UTIL_AVG_UNCHANGED)
3983 * Reset EWMA on utilization increases, the moving average is used only
3984 * to smooth utilization decreases.
3986 ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
3987 if (sched_feat(UTIL_EST_FASTUP)) {
3988 if (ue.ewma < ue.enqueued) {
3989 ue.ewma = ue.enqueued;
3995 * Skip update of task's estimated utilization when its EWMA is
3996 * already ~1% close to its last activation value.
3998 last_ewma_diff = ue.enqueued - ue.ewma;
3999 if (within_margin(last_ewma_diff, (SCHED_CAPACITY_SCALE / 100)))
4003 * To avoid overestimation of actual task utilization, skip updates if
4004 * we cannot grant there is idle time in this CPU.
4006 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4010 * Update Task's estimated utilization
4012 * When *p completes an activation we can consolidate another sample
4013 * of the task size. This is done by storing the current PELT value
4014 * as ue.enqueued and by using this value to update the Exponential
4015 * Weighted Moving Average (EWMA):
4017 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4018 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4019 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4020 * = w * ( last_ewma_diff ) + ewma(t-1)
4021 * = w * (last_ewma_diff + ewma(t-1) / w)
4023 * Where 'w' is the weight of new samples, which is configured to be
4024 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4026 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4027 ue.ewma += last_ewma_diff;
4028 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4030 WRITE_ONCE(p->se.avg.util_est, ue);
4032 trace_sched_util_est_se_tp(&p->se);
4035 static inline int task_fits_capacity(struct task_struct *p, long capacity)
4037 return fits_capacity(uclamp_task_util(p), capacity);
4040 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4042 if (!static_branch_unlikely(&sched_asym_cpucapacity))
4045 if (!p || p->nr_cpus_allowed == 1) {
4046 rq->misfit_task_load = 0;
4050 if (task_fits_capacity(p, capacity_of(cpu_of(rq)))) {
4051 rq->misfit_task_load = 0;
4056 * Make sure that misfit_task_load will not be null even if
4057 * task_h_load() returns 0.
4059 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4062 #else /* CONFIG_SMP */
4064 #define UPDATE_TG 0x0
4065 #define SKIP_AGE_LOAD 0x0
4066 #define DO_ATTACH 0x0
4068 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4070 cfs_rq_util_change(cfs_rq, 0);
4073 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4076 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4078 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4080 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4086 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4089 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4092 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4094 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4096 #endif /* CONFIG_SMP */
4098 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
4100 #ifdef CONFIG_SCHED_DEBUG
4101 s64 d = se->vruntime - cfs_rq->min_vruntime;
4106 if (d > 3*sysctl_sched_latency)
4107 schedstat_inc(cfs_rq->nr_spread_over);
4112 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
4114 u64 vruntime = cfs_rq->min_vruntime;
4117 * The 'current' period is already promised to the current tasks,
4118 * however the extra weight of the new task will slow them down a
4119 * little, place the new task so that it fits in the slot that
4120 * stays open at the end.
4122 if (initial && sched_feat(START_DEBIT))
4123 vruntime += sched_vslice(cfs_rq, se);
4125 /* sleeps up to a single latency don't count. */
4127 unsigned long thresh = sysctl_sched_latency;
4130 * Halve their sleep time's effect, to allow
4131 * for a gentler effect of sleepers:
4133 if (sched_feat(GENTLE_FAIR_SLEEPERS))
4139 /* ensure we never gain time by being placed backwards. */
4140 se->vruntime = max_vruntime(se->vruntime, vruntime);
4143 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
4145 static inline void check_schedstat_required(void)
4147 #ifdef CONFIG_SCHEDSTATS
4148 if (schedstat_enabled())
4151 /* Force schedstat enabled if a dependent tracepoint is active */
4152 if (trace_sched_stat_wait_enabled() ||
4153 trace_sched_stat_sleep_enabled() ||
4154 trace_sched_stat_iowait_enabled() ||
4155 trace_sched_stat_blocked_enabled() ||
4156 trace_sched_stat_runtime_enabled()) {
4157 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
4158 "stat_blocked and stat_runtime require the "
4159 "kernel parameter schedstats=enable or "
4160 "kernel.sched_schedstats=1\n");
4165 static inline bool cfs_bandwidth_used(void);
4172 * update_min_vruntime()
4173 * vruntime -= min_vruntime
4177 * update_min_vruntime()
4178 * vruntime += min_vruntime
4180 * this way the vruntime transition between RQs is done when both
4181 * min_vruntime are up-to-date.
4185 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
4186 * vruntime -= min_vruntime
4190 * update_min_vruntime()
4191 * vruntime += min_vruntime
4193 * this way we don't have the most up-to-date min_vruntime on the originating
4194 * CPU and an up-to-date min_vruntime on the destination CPU.
4198 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4200 bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
4201 bool curr = cfs_rq->curr == se;
4204 * If we're the current task, we must renormalise before calling
4208 se->vruntime += cfs_rq->min_vruntime;
4210 update_curr(cfs_rq);
4213 * Otherwise, renormalise after, such that we're placed at the current
4214 * moment in time, instead of some random moment in the past. Being
4215 * placed in the past could significantly boost this task to the
4216 * fairness detriment of existing tasks.
4218 if (renorm && !curr)
4219 se->vruntime += cfs_rq->min_vruntime;
4222 * When enqueuing a sched_entity, we must:
4223 * - Update loads to have both entity and cfs_rq synced with now.
4224 * - Add its load to cfs_rq->runnable_avg
4225 * - For group_entity, update its weight to reflect the new share of
4227 * - Add its new weight to cfs_rq->load.weight
4229 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
4230 se_update_runnable(se);
4231 update_cfs_group(se);
4232 account_entity_enqueue(cfs_rq, se);
4234 if (flags & ENQUEUE_WAKEUP)
4235 place_entity(cfs_rq, se, 0);
4237 check_schedstat_required();
4238 update_stats_enqueue(cfs_rq, se, flags);
4239 check_spread(cfs_rq, se);
4241 __enqueue_entity(cfs_rq, se);
4245 * When bandwidth control is enabled, cfs might have been removed
4246 * because of a parent been throttled but cfs->nr_running > 1. Try to
4247 * add it unconditionnally.
4249 if (cfs_rq->nr_running == 1 || cfs_bandwidth_used())
4250 list_add_leaf_cfs_rq(cfs_rq);
4252 if (cfs_rq->nr_running == 1)
4253 check_enqueue_throttle(cfs_rq);
4256 static void __clear_buddies_last(struct sched_entity *se)
4258 for_each_sched_entity(se) {
4259 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4260 if (cfs_rq->last != se)
4263 cfs_rq->last = NULL;
4267 static void __clear_buddies_next(struct sched_entity *se)
4269 for_each_sched_entity(se) {
4270 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4271 if (cfs_rq->next != se)
4274 cfs_rq->next = NULL;
4278 static void __clear_buddies_skip(struct sched_entity *se)
4280 for_each_sched_entity(se) {
4281 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4282 if (cfs_rq->skip != se)
4285 cfs_rq->skip = NULL;
4289 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
4291 if (cfs_rq->last == se)
4292 __clear_buddies_last(se);
4294 if (cfs_rq->next == se)
4295 __clear_buddies_next(se);
4297 if (cfs_rq->skip == se)
4298 __clear_buddies_skip(se);
4301 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4304 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4307 * Update run-time statistics of the 'current'.
4309 update_curr(cfs_rq);
4312 * When dequeuing a sched_entity, we must:
4313 * - Update loads to have both entity and cfs_rq synced with now.
4314 * - Subtract its load from the cfs_rq->runnable_avg.
4315 * - Subtract its previous weight from cfs_rq->load.weight.
4316 * - For group entity, update its weight to reflect the new share
4317 * of its group cfs_rq.
4319 update_load_avg(cfs_rq, se, UPDATE_TG);
4320 se_update_runnable(se);
4322 update_stats_dequeue(cfs_rq, se, flags);
4324 clear_buddies(cfs_rq, se);
4326 if (se != cfs_rq->curr)
4327 __dequeue_entity(cfs_rq, se);
4329 account_entity_dequeue(cfs_rq, se);
4332 * Normalize after update_curr(); which will also have moved
4333 * min_vruntime if @se is the one holding it back. But before doing
4334 * update_min_vruntime() again, which will discount @se's position and
4335 * can move min_vruntime forward still more.
4337 if (!(flags & DEQUEUE_SLEEP))
4338 se->vruntime -= cfs_rq->min_vruntime;
4340 /* return excess runtime on last dequeue */
4341 return_cfs_rq_runtime(cfs_rq);
4343 update_cfs_group(se);
4346 * Now advance min_vruntime if @se was the entity holding it back,
4347 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4348 * put back on, and if we advance min_vruntime, we'll be placed back
4349 * further than we started -- ie. we'll be penalized.
4351 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
4352 update_min_vruntime(cfs_rq);
4356 * Preempt the current task with a newly woken task if needed:
4359 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4361 unsigned long ideal_runtime, delta_exec;
4362 struct sched_entity *se;
4365 ideal_runtime = sched_slice(cfs_rq, curr);
4366 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
4367 if (delta_exec > ideal_runtime) {
4368 resched_curr(rq_of(cfs_rq));
4370 * The current task ran long enough, ensure it doesn't get
4371 * re-elected due to buddy favours.
4373 clear_buddies(cfs_rq, curr);
4378 * Ensure that a task that missed wakeup preemption by a
4379 * narrow margin doesn't have to wait for a full slice.
4380 * This also mitigates buddy induced latencies under load.
4382 if (delta_exec < sysctl_sched_min_granularity)
4385 se = __pick_first_entity(cfs_rq);
4386 delta = curr->vruntime - se->vruntime;
4391 if (delta > ideal_runtime)
4392 resched_curr(rq_of(cfs_rq));
4396 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
4398 /* 'current' is not kept within the tree. */
4401 * Any task has to be enqueued before it get to execute on
4402 * a CPU. So account for the time it spent waiting on the
4405 update_stats_wait_end(cfs_rq, se);
4406 __dequeue_entity(cfs_rq, se);
4407 update_load_avg(cfs_rq, se, UPDATE_TG);
4410 update_stats_curr_start(cfs_rq, se);
4414 * Track our maximum slice length, if the CPU's load is at
4415 * least twice that of our own weight (i.e. dont track it
4416 * when there are only lesser-weight tasks around):
4418 if (schedstat_enabled() &&
4419 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
4420 schedstat_set(se->statistics.slice_max,
4421 max((u64)schedstat_val(se->statistics.slice_max),
4422 se->sum_exec_runtime - se->prev_sum_exec_runtime));
4425 se->prev_sum_exec_runtime = se->sum_exec_runtime;
4429 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
4432 * Pick the next process, keeping these things in mind, in this order:
4433 * 1) keep things fair between processes/task groups
4434 * 2) pick the "next" process, since someone really wants that to run
4435 * 3) pick the "last" process, for cache locality
4436 * 4) do not run the "skip" process, if something else is available
4438 static struct sched_entity *
4439 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4441 struct sched_entity *left = __pick_first_entity(cfs_rq);
4442 struct sched_entity *se;
4445 * If curr is set we have to see if its left of the leftmost entity
4446 * still in the tree, provided there was anything in the tree at all.
4448 if (!left || (curr && entity_before(curr, left)))
4451 se = left; /* ideally we run the leftmost entity */
4454 * Avoid running the skip buddy, if running something else can
4455 * be done without getting too unfair.
4457 if (cfs_rq->skip == se) {
4458 struct sched_entity *second;
4461 second = __pick_first_entity(cfs_rq);
4463 second = __pick_next_entity(se);
4464 if (!second || (curr && entity_before(curr, second)))
4468 if (second && wakeup_preempt_entity(second, left) < 1)
4472 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) {
4474 * Someone really wants this to run. If it's not unfair, run it.
4477 } else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) {
4479 * Prefer last buddy, try to return the CPU to a preempted task.
4484 clear_buddies(cfs_rq, se);
4489 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4491 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
4494 * If still on the runqueue then deactivate_task()
4495 * was not called and update_curr() has to be done:
4498 update_curr(cfs_rq);
4500 /* throttle cfs_rqs exceeding runtime */
4501 check_cfs_rq_runtime(cfs_rq);
4503 check_spread(cfs_rq, prev);
4506 update_stats_wait_start(cfs_rq, prev);
4507 /* Put 'current' back into the tree. */
4508 __enqueue_entity(cfs_rq, prev);
4509 /* in !on_rq case, update occurred at dequeue */
4510 update_load_avg(cfs_rq, prev, 0);
4512 cfs_rq->curr = NULL;
4516 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
4519 * Update run-time statistics of the 'current'.
4521 update_curr(cfs_rq);
4524 * Ensure that runnable average is periodically updated.
4526 update_load_avg(cfs_rq, curr, UPDATE_TG);
4527 update_cfs_group(curr);
4529 #ifdef CONFIG_SCHED_HRTICK
4531 * queued ticks are scheduled to match the slice, so don't bother
4532 * validating it and just reschedule.
4535 resched_curr(rq_of(cfs_rq));
4539 * don't let the period tick interfere with the hrtick preemption
4541 if (!sched_feat(DOUBLE_TICK) &&
4542 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
4546 if (cfs_rq->nr_running > 1)
4547 check_preempt_tick(cfs_rq, curr);
4551 /**************************************************
4552 * CFS bandwidth control machinery
4555 #ifdef CONFIG_CFS_BANDWIDTH
4557 #ifdef CONFIG_JUMP_LABEL
4558 static struct static_key __cfs_bandwidth_used;
4560 static inline bool cfs_bandwidth_used(void)
4562 return static_key_false(&__cfs_bandwidth_used);
4565 void cfs_bandwidth_usage_inc(void)
4567 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
4570 void cfs_bandwidth_usage_dec(void)
4572 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
4574 #else /* CONFIG_JUMP_LABEL */
4575 static bool cfs_bandwidth_used(void)
4580 void cfs_bandwidth_usage_inc(void) {}
4581 void cfs_bandwidth_usage_dec(void) {}
4582 #endif /* CONFIG_JUMP_LABEL */
4585 * default period for cfs group bandwidth.
4586 * default: 0.1s, units: nanoseconds
4588 static inline u64 default_cfs_period(void)
4590 return 100000000ULL;
4593 static inline u64 sched_cfs_bandwidth_slice(void)
4595 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
4599 * Replenish runtime according to assigned quota. We use sched_clock_cpu
4600 * directly instead of rq->clock to avoid adding additional synchronization
4603 * requires cfs_b->lock
4605 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
4607 if (cfs_b->quota != RUNTIME_INF)
4608 cfs_b->runtime = cfs_b->quota;
4611 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4613 return &tg->cfs_bandwidth;
4616 /* returns 0 on failure to allocate runtime */
4617 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
4618 struct cfs_rq *cfs_rq, u64 target_runtime)
4620 u64 min_amount, amount = 0;
4622 lockdep_assert_held(&cfs_b->lock);
4624 /* note: this is a positive sum as runtime_remaining <= 0 */
4625 min_amount = target_runtime - cfs_rq->runtime_remaining;
4627 if (cfs_b->quota == RUNTIME_INF)
4628 amount = min_amount;
4630 start_cfs_bandwidth(cfs_b);
4632 if (cfs_b->runtime > 0) {
4633 amount = min(cfs_b->runtime, min_amount);
4634 cfs_b->runtime -= amount;
4639 cfs_rq->runtime_remaining += amount;
4641 return cfs_rq->runtime_remaining > 0;
4644 /* returns 0 on failure to allocate runtime */
4645 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4647 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4650 raw_spin_lock(&cfs_b->lock);
4651 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
4652 raw_spin_unlock(&cfs_b->lock);
4657 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4659 /* dock delta_exec before expiring quota (as it could span periods) */
4660 cfs_rq->runtime_remaining -= delta_exec;
4662 if (likely(cfs_rq->runtime_remaining > 0))
4665 if (cfs_rq->throttled)
4668 * if we're unable to extend our runtime we resched so that the active
4669 * hierarchy can be throttled
4671 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
4672 resched_curr(rq_of(cfs_rq));
4675 static __always_inline
4676 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4678 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4681 __account_cfs_rq_runtime(cfs_rq, delta_exec);
4684 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4686 return cfs_bandwidth_used() && cfs_rq->throttled;
4689 /* check whether cfs_rq, or any parent, is throttled */
4690 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4692 return cfs_bandwidth_used() && cfs_rq->throttle_count;
4696 * Ensure that neither of the group entities corresponding to src_cpu or
4697 * dest_cpu are members of a throttled hierarchy when performing group
4698 * load-balance operations.
4700 static inline int throttled_lb_pair(struct task_group *tg,
4701 int src_cpu, int dest_cpu)
4703 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4705 src_cfs_rq = tg->cfs_rq[src_cpu];
4706 dest_cfs_rq = tg->cfs_rq[dest_cpu];
4708 return throttled_hierarchy(src_cfs_rq) ||
4709 throttled_hierarchy(dest_cfs_rq);
4712 static int tg_unthrottle_up(struct task_group *tg, void *data)
4714 struct rq *rq = data;
4715 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4717 cfs_rq->throttle_count--;
4718 if (!cfs_rq->throttle_count) {
4719 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
4720 cfs_rq->throttled_clock_task;
4722 /* Add cfs_rq with already running entity in the list */
4723 if (cfs_rq->nr_running >= 1)
4724 list_add_leaf_cfs_rq(cfs_rq);
4730 static int tg_throttle_down(struct task_group *tg, void *data)
4732 struct rq *rq = data;
4733 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4735 /* group is entering throttled state, stop time */
4736 if (!cfs_rq->throttle_count) {
4737 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4738 list_del_leaf_cfs_rq(cfs_rq);
4740 cfs_rq->throttle_count++;
4745 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
4747 struct rq *rq = rq_of(cfs_rq);
4748 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4749 struct sched_entity *se;
4750 long task_delta, idle_task_delta, dequeue = 1;
4752 raw_spin_lock(&cfs_b->lock);
4753 /* This will start the period timer if necessary */
4754 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
4756 * We have raced with bandwidth becoming available, and if we
4757 * actually throttled the timer might not unthrottle us for an
4758 * entire period. We additionally needed to make sure that any
4759 * subsequent check_cfs_rq_runtime calls agree not to throttle
4760 * us, as we may commit to do cfs put_prev+pick_next, so we ask
4761 * for 1ns of runtime rather than just check cfs_b.
4765 list_add_tail_rcu(&cfs_rq->throttled_list,
4766 &cfs_b->throttled_cfs_rq);
4768 raw_spin_unlock(&cfs_b->lock);
4771 return false; /* Throttle no longer required. */
4773 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4775 /* freeze hierarchy runnable averages while throttled */
4777 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4780 task_delta = cfs_rq->h_nr_running;
4781 idle_task_delta = cfs_rq->idle_h_nr_running;
4782 for_each_sched_entity(se) {
4783 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4784 /* throttled entity or throttle-on-deactivate */
4788 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
4790 qcfs_rq->h_nr_running -= task_delta;
4791 qcfs_rq->idle_h_nr_running -= idle_task_delta;
4793 if (qcfs_rq->load.weight) {
4794 /* Avoid re-evaluating load for this entity: */
4795 se = parent_entity(se);
4800 for_each_sched_entity(se) {
4801 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4802 /* throttled entity or throttle-on-deactivate */
4806 update_load_avg(qcfs_rq, se, 0);
4807 se_update_runnable(se);
4809 qcfs_rq->h_nr_running -= task_delta;
4810 qcfs_rq->idle_h_nr_running -= idle_task_delta;
4813 /* At this point se is NULL and we are at root level*/
4814 sub_nr_running(rq, task_delta);
4818 * Note: distribution will already see us throttled via the
4819 * throttled-list. rq->lock protects completion.
4821 cfs_rq->throttled = 1;
4822 cfs_rq->throttled_clock = rq_clock(rq);
4826 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
4828 struct rq *rq = rq_of(cfs_rq);
4829 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4830 struct sched_entity *se;
4831 long task_delta, idle_task_delta;
4833 se = cfs_rq->tg->se[cpu_of(rq)];
4835 cfs_rq->throttled = 0;
4837 update_rq_clock(rq);
4839 raw_spin_lock(&cfs_b->lock);
4840 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4841 list_del_rcu(&cfs_rq->throttled_list);
4842 raw_spin_unlock(&cfs_b->lock);
4844 /* update hierarchical throttle state */
4845 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4847 if (!cfs_rq->load.weight)
4850 task_delta = cfs_rq->h_nr_running;
4851 idle_task_delta = cfs_rq->idle_h_nr_running;
4852 for_each_sched_entity(se) {
4855 cfs_rq = cfs_rq_of(se);
4856 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4858 cfs_rq->h_nr_running += task_delta;
4859 cfs_rq->idle_h_nr_running += idle_task_delta;
4861 /* end evaluation on encountering a throttled cfs_rq */
4862 if (cfs_rq_throttled(cfs_rq))
4863 goto unthrottle_throttle;
4866 for_each_sched_entity(se) {
4867 cfs_rq = cfs_rq_of(se);
4869 update_load_avg(cfs_rq, se, UPDATE_TG);
4870 se_update_runnable(se);
4872 cfs_rq->h_nr_running += task_delta;
4873 cfs_rq->idle_h_nr_running += idle_task_delta;
4876 /* end evaluation on encountering a throttled cfs_rq */
4877 if (cfs_rq_throttled(cfs_rq))
4878 goto unthrottle_throttle;
4881 * One parent has been throttled and cfs_rq removed from the
4882 * list. Add it back to not break the leaf list.
4884 if (throttled_hierarchy(cfs_rq))
4885 list_add_leaf_cfs_rq(cfs_rq);
4888 /* At this point se is NULL and we are at root level*/
4889 add_nr_running(rq, task_delta);
4891 unthrottle_throttle:
4893 * The cfs_rq_throttled() breaks in the above iteration can result in
4894 * incomplete leaf list maintenance, resulting in triggering the
4897 for_each_sched_entity(se) {
4898 cfs_rq = cfs_rq_of(se);
4900 if (list_add_leaf_cfs_rq(cfs_rq))
4904 assert_list_leaf_cfs_rq(rq);
4906 /* Determine whether we need to wake up potentially idle CPU: */
4907 if (rq->curr == rq->idle && rq->cfs.nr_running)
4911 static void distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
4913 struct cfs_rq *cfs_rq;
4914 u64 runtime, remaining = 1;
4917 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4919 struct rq *rq = rq_of(cfs_rq);
4922 rq_lock_irqsave(rq, &rf);
4923 if (!cfs_rq_throttled(cfs_rq))
4926 /* By the above check, this should never be true */
4927 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
4929 raw_spin_lock(&cfs_b->lock);
4930 runtime = -cfs_rq->runtime_remaining + 1;
4931 if (runtime > cfs_b->runtime)
4932 runtime = cfs_b->runtime;
4933 cfs_b->runtime -= runtime;
4934 remaining = cfs_b->runtime;
4935 raw_spin_unlock(&cfs_b->lock);
4937 cfs_rq->runtime_remaining += runtime;
4939 /* we check whether we're throttled above */
4940 if (cfs_rq->runtime_remaining > 0)
4941 unthrottle_cfs_rq(cfs_rq);
4944 rq_unlock_irqrestore(rq, &rf);
4953 * Responsible for refilling a task_group's bandwidth and unthrottling its
4954 * cfs_rqs as appropriate. If there has been no activity within the last
4955 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4956 * used to track this state.
4958 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
4962 /* no need to continue the timer with no bandwidth constraint */
4963 if (cfs_b->quota == RUNTIME_INF)
4964 goto out_deactivate;
4966 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4967 cfs_b->nr_periods += overrun;
4970 * idle depends on !throttled (for the case of a large deficit), and if
4971 * we're going inactive then everything else can be deferred
4973 if (cfs_b->idle && !throttled)
4974 goto out_deactivate;
4976 __refill_cfs_bandwidth_runtime(cfs_b);
4979 /* mark as potentially idle for the upcoming period */
4984 /* account preceding periods in which throttling occurred */
4985 cfs_b->nr_throttled += overrun;
4988 * This check is repeated as we release cfs_b->lock while we unthrottle.
4990 while (throttled && cfs_b->runtime > 0) {
4991 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
4992 /* we can't nest cfs_b->lock while distributing bandwidth */
4993 distribute_cfs_runtime(cfs_b);
4994 raw_spin_lock_irqsave(&cfs_b->lock, flags);
4996 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5000 * While we are ensured activity in the period following an
5001 * unthrottle, this also covers the case in which the new bandwidth is
5002 * insufficient to cover the existing bandwidth deficit. (Forcing the
5003 * timer to remain active while there are any throttled entities.)
5013 /* a cfs_rq won't donate quota below this amount */
5014 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5015 /* minimum remaining period time to redistribute slack quota */
5016 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5017 /* how long we wait to gather additional slack before distributing */
5018 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5021 * Are we near the end of the current quota period?
5023 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5024 * hrtimer base being cleared by hrtimer_start. In the case of
5025 * migrate_hrtimers, base is never cleared, so we are fine.
5027 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5029 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5032 /* if the call-back is running a quota refresh is already occurring */
5033 if (hrtimer_callback_running(refresh_timer))
5036 /* is a quota refresh about to occur? */
5037 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5038 if (remaining < min_expire)
5044 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5046 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5048 /* if there's a quota refresh soon don't bother with slack */
5049 if (runtime_refresh_within(cfs_b, min_left))
5052 /* don't push forwards an existing deferred unthrottle */
5053 if (cfs_b->slack_started)
5055 cfs_b->slack_started = true;
5057 hrtimer_start(&cfs_b->slack_timer,
5058 ns_to_ktime(cfs_bandwidth_slack_period),
5062 /* we know any runtime found here is valid as update_curr() precedes return */
5063 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5065 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5066 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5068 if (slack_runtime <= 0)
5071 raw_spin_lock(&cfs_b->lock);
5072 if (cfs_b->quota != RUNTIME_INF) {
5073 cfs_b->runtime += slack_runtime;
5075 /* we are under rq->lock, defer unthrottling using a timer */
5076 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5077 !list_empty(&cfs_b->throttled_cfs_rq))
5078 start_cfs_slack_bandwidth(cfs_b);
5080 raw_spin_unlock(&cfs_b->lock);
5082 /* even if it's not valid for return we don't want to try again */
5083 cfs_rq->runtime_remaining -= slack_runtime;
5086 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5088 if (!cfs_bandwidth_used())
5091 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
5094 __return_cfs_rq_runtime(cfs_rq);
5098 * This is done with a timer (instead of inline with bandwidth return) since
5099 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5101 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5103 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
5104 unsigned long flags;
5106 /* confirm we're still not at a refresh boundary */
5107 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5108 cfs_b->slack_started = false;
5110 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
5111 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5115 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
5116 runtime = cfs_b->runtime;
5118 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5123 distribute_cfs_runtime(cfs_b);
5127 * When a group wakes up we want to make sure that its quota is not already
5128 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
5129 * runtime as update_curr() throttling can not trigger until it's on-rq.
5131 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
5133 if (!cfs_bandwidth_used())
5136 /* an active group must be handled by the update_curr()->put() path */
5137 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
5140 /* ensure the group is not already throttled */
5141 if (cfs_rq_throttled(cfs_rq))
5144 /* update runtime allocation */
5145 account_cfs_rq_runtime(cfs_rq, 0);
5146 if (cfs_rq->runtime_remaining <= 0)
5147 throttle_cfs_rq(cfs_rq);
5150 static void sync_throttle(struct task_group *tg, int cpu)
5152 struct cfs_rq *pcfs_rq, *cfs_rq;
5154 if (!cfs_bandwidth_used())
5160 cfs_rq = tg->cfs_rq[cpu];
5161 pcfs_rq = tg->parent->cfs_rq[cpu];
5163 cfs_rq->throttle_count = pcfs_rq->throttle_count;
5164 cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
5167 /* conditionally throttle active cfs_rq's from put_prev_entity() */
5168 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5170 if (!cfs_bandwidth_used())
5173 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
5177 * it's possible for a throttled entity to be forced into a running
5178 * state (e.g. set_curr_task), in this case we're finished.
5180 if (cfs_rq_throttled(cfs_rq))
5183 return throttle_cfs_rq(cfs_rq);
5186 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
5188 struct cfs_bandwidth *cfs_b =
5189 container_of(timer, struct cfs_bandwidth, slack_timer);
5191 do_sched_cfs_slack_timer(cfs_b);
5193 return HRTIMER_NORESTART;
5196 extern const u64 max_cfs_quota_period;
5198 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
5200 struct cfs_bandwidth *cfs_b =
5201 container_of(timer, struct cfs_bandwidth, period_timer);
5202 unsigned long flags;
5207 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5209 overrun = hrtimer_forward_now(timer, cfs_b->period);
5213 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
5216 u64 new, old = ktime_to_ns(cfs_b->period);
5219 * Grow period by a factor of 2 to avoid losing precision.
5220 * Precision loss in the quota/period ratio can cause __cfs_schedulable
5224 if (new < max_cfs_quota_period) {
5225 cfs_b->period = ns_to_ktime(new);
5228 pr_warn_ratelimited(
5229 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5231 div_u64(new, NSEC_PER_USEC),
5232 div_u64(cfs_b->quota, NSEC_PER_USEC));
5234 pr_warn_ratelimited(
5235 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5237 div_u64(old, NSEC_PER_USEC),
5238 div_u64(cfs_b->quota, NSEC_PER_USEC));
5241 /* reset count so we don't come right back in here */
5246 cfs_b->period_active = 0;
5247 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5249 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
5252 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5254 raw_spin_lock_init(&cfs_b->lock);
5256 cfs_b->quota = RUNTIME_INF;
5257 cfs_b->period = ns_to_ktime(default_cfs_period());
5259 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
5260 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
5261 cfs_b->period_timer.function = sched_cfs_period_timer;
5262 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5263 cfs_b->slack_timer.function = sched_cfs_slack_timer;
5264 cfs_b->slack_started = false;
5267 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5269 cfs_rq->runtime_enabled = 0;
5270 INIT_LIST_HEAD(&cfs_rq->throttled_list);
5273 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5275 lockdep_assert_held(&cfs_b->lock);
5277 if (cfs_b->period_active)
5280 cfs_b->period_active = 1;
5281 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
5282 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
5285 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5287 /* init_cfs_bandwidth() was not called */
5288 if (!cfs_b->throttled_cfs_rq.next)
5291 hrtimer_cancel(&cfs_b->period_timer);
5292 hrtimer_cancel(&cfs_b->slack_timer);
5296 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
5298 * The race is harmless, since modifying bandwidth settings of unhooked group
5299 * bits doesn't do much.
5302 /* cpu online calback */
5303 static void __maybe_unused update_runtime_enabled(struct rq *rq)
5305 struct task_group *tg;
5307 lockdep_assert_held(&rq->lock);
5310 list_for_each_entry_rcu(tg, &task_groups, list) {
5311 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
5312 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5314 raw_spin_lock(&cfs_b->lock);
5315 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
5316 raw_spin_unlock(&cfs_b->lock);
5321 /* cpu offline callback */
5322 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
5324 struct task_group *tg;
5326 lockdep_assert_held(&rq->lock);
5329 list_for_each_entry_rcu(tg, &task_groups, list) {
5330 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5332 if (!cfs_rq->runtime_enabled)
5336 * clock_task is not advancing so we just need to make sure
5337 * there's some valid quota amount
5339 cfs_rq->runtime_remaining = 1;
5341 * Offline rq is schedulable till CPU is completely disabled
5342 * in take_cpu_down(), so we prevent new cfs throttling here.
5344 cfs_rq->runtime_enabled = 0;
5346 if (cfs_rq_throttled(cfs_rq))
5347 unthrottle_cfs_rq(cfs_rq);
5352 #else /* CONFIG_CFS_BANDWIDTH */
5354 static inline bool cfs_bandwidth_used(void)
5359 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
5360 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
5361 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
5362 static inline void sync_throttle(struct task_group *tg, int cpu) {}
5363 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5365 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5370 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5375 static inline int throttled_lb_pair(struct task_group *tg,
5376 int src_cpu, int dest_cpu)
5381 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5383 #ifdef CONFIG_FAIR_GROUP_SCHED
5384 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5387 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5391 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5392 static inline void update_runtime_enabled(struct rq *rq) {}
5393 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
5395 #endif /* CONFIG_CFS_BANDWIDTH */
5397 /**************************************************
5398 * CFS operations on tasks:
5401 #ifdef CONFIG_SCHED_HRTICK
5402 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
5404 struct sched_entity *se = &p->se;
5405 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5407 SCHED_WARN_ON(task_rq(p) != rq);
5409 if (rq->cfs.h_nr_running > 1) {
5410 u64 slice = sched_slice(cfs_rq, se);
5411 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
5412 s64 delta = slice - ran;
5415 if (task_current(rq, p))
5419 hrtick_start(rq, delta);
5424 * called from enqueue/dequeue and updates the hrtick when the
5425 * current task is from our class and nr_running is low enough
5428 static void hrtick_update(struct rq *rq)
5430 struct task_struct *curr = rq->curr;
5432 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
5435 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
5436 hrtick_start_fair(rq, curr);
5438 #else /* !CONFIG_SCHED_HRTICK */
5440 hrtick_start_fair(struct rq *rq, struct task_struct *p)
5444 static inline void hrtick_update(struct rq *rq)
5450 static inline unsigned long cpu_util(int cpu);
5452 static inline bool cpu_overutilized(int cpu)
5454 return !fits_capacity(cpu_util(cpu), capacity_of(cpu));
5457 static inline void update_overutilized_status(struct rq *rq)
5459 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
5460 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
5461 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
5465 static inline void update_overutilized_status(struct rq *rq) { }
5468 /* Runqueue only has SCHED_IDLE tasks enqueued */
5469 static int sched_idle_rq(struct rq *rq)
5471 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
5476 static int sched_idle_cpu(int cpu)
5478 return sched_idle_rq(cpu_rq(cpu));
5483 * The enqueue_task method is called before nr_running is
5484 * increased. Here we update the fair scheduling stats and
5485 * then put the task into the rbtree:
5488 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5490 struct cfs_rq *cfs_rq;
5491 struct sched_entity *se = &p->se;
5492 int idle_h_nr_running = task_has_idle_policy(p);
5493 int task_new = !(flags & ENQUEUE_WAKEUP);
5496 * The code below (indirectly) updates schedutil which looks at
5497 * the cfs_rq utilization to select a frequency.
5498 * Let's add the task's estimated utilization to the cfs_rq's
5499 * estimated utilization, before we update schedutil.
5501 util_est_enqueue(&rq->cfs, p);
5504 * If in_iowait is set, the code below may not trigger any cpufreq
5505 * utilization updates, so do it here explicitly with the IOWAIT flag
5509 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
5511 for_each_sched_entity(se) {
5514 cfs_rq = cfs_rq_of(se);
5515 enqueue_entity(cfs_rq, se, flags);
5517 cfs_rq->h_nr_running++;
5518 cfs_rq->idle_h_nr_running += idle_h_nr_running;
5520 /* end evaluation on encountering a throttled cfs_rq */
5521 if (cfs_rq_throttled(cfs_rq))
5522 goto enqueue_throttle;
5524 flags = ENQUEUE_WAKEUP;
5527 for_each_sched_entity(se) {
5528 cfs_rq = cfs_rq_of(se);
5530 update_load_avg(cfs_rq, se, UPDATE_TG);
5531 se_update_runnable(se);
5532 update_cfs_group(se);
5534 cfs_rq->h_nr_running++;
5535 cfs_rq->idle_h_nr_running += idle_h_nr_running;
5537 /* end evaluation on encountering a throttled cfs_rq */
5538 if (cfs_rq_throttled(cfs_rq))
5539 goto enqueue_throttle;
5542 * One parent has been throttled and cfs_rq removed from the
5543 * list. Add it back to not break the leaf list.
5545 if (throttled_hierarchy(cfs_rq))
5546 list_add_leaf_cfs_rq(cfs_rq);
5549 /* At this point se is NULL and we are at root level*/
5550 add_nr_running(rq, 1);
5553 * Since new tasks are assigned an initial util_avg equal to
5554 * half of the spare capacity of their CPU, tiny tasks have the
5555 * ability to cross the overutilized threshold, which will
5556 * result in the load balancer ruining all the task placement
5557 * done by EAS. As a way to mitigate that effect, do not account
5558 * for the first enqueue operation of new tasks during the
5559 * overutilized flag detection.
5561 * A better way of solving this problem would be to wait for
5562 * the PELT signals of tasks to converge before taking them
5563 * into account, but that is not straightforward to implement,
5564 * and the following generally works well enough in practice.
5567 update_overutilized_status(rq);
5570 if (cfs_bandwidth_used()) {
5572 * When bandwidth control is enabled; the cfs_rq_throttled()
5573 * breaks in the above iteration can result in incomplete
5574 * leaf list maintenance, resulting in triggering the assertion
5577 for_each_sched_entity(se) {
5578 cfs_rq = cfs_rq_of(se);
5580 if (list_add_leaf_cfs_rq(cfs_rq))
5585 assert_list_leaf_cfs_rq(rq);
5590 static void set_next_buddy(struct sched_entity *se);
5593 * The dequeue_task method is called before nr_running is
5594 * decreased. We remove the task from the rbtree and
5595 * update the fair scheduling stats:
5597 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5599 struct cfs_rq *cfs_rq;
5600 struct sched_entity *se = &p->se;
5601 int task_sleep = flags & DEQUEUE_SLEEP;
5602 int idle_h_nr_running = task_has_idle_policy(p);
5603 bool was_sched_idle = sched_idle_rq(rq);
5605 util_est_dequeue(&rq->cfs, p);
5607 for_each_sched_entity(se) {
5608 cfs_rq = cfs_rq_of(se);
5609 dequeue_entity(cfs_rq, se, flags);
5611 cfs_rq->h_nr_running--;
5612 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5614 /* end evaluation on encountering a throttled cfs_rq */
5615 if (cfs_rq_throttled(cfs_rq))
5616 goto dequeue_throttle;
5618 /* Don't dequeue parent if it has other entities besides us */
5619 if (cfs_rq->load.weight) {
5620 /* Avoid re-evaluating load for this entity: */
5621 se = parent_entity(se);
5623 * Bias pick_next to pick a task from this cfs_rq, as
5624 * p is sleeping when it is within its sched_slice.
5626 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
5630 flags |= DEQUEUE_SLEEP;
5633 for_each_sched_entity(se) {
5634 cfs_rq = cfs_rq_of(se);
5636 update_load_avg(cfs_rq, se, UPDATE_TG);
5637 se_update_runnable(se);
5638 update_cfs_group(se);
5640 cfs_rq->h_nr_running--;
5641 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5643 /* end evaluation on encountering a throttled cfs_rq */
5644 if (cfs_rq_throttled(cfs_rq))
5645 goto dequeue_throttle;
5649 /* At this point se is NULL and we are at root level*/
5650 sub_nr_running(rq, 1);
5652 /* balance early to pull high priority tasks */
5653 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
5654 rq->next_balance = jiffies;
5657 util_est_update(&rq->cfs, p, task_sleep);
5663 /* Working cpumask for: load_balance, load_balance_newidle. */
5664 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5665 DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
5667 #ifdef CONFIG_NO_HZ_COMMON
5670 cpumask_var_t idle_cpus_mask;
5672 int has_blocked; /* Idle CPUS has blocked load */
5673 unsigned long next_balance; /* in jiffy units */
5674 unsigned long next_blocked; /* Next update of blocked load in jiffies */
5675 } nohz ____cacheline_aligned;
5677 #endif /* CONFIG_NO_HZ_COMMON */
5679 static unsigned long cpu_load(struct rq *rq)
5681 return cfs_rq_load_avg(&rq->cfs);
5685 * cpu_load_without - compute CPU load without any contributions from *p
5686 * @cpu: the CPU which load is requested
5687 * @p: the task which load should be discounted
5689 * The load of a CPU is defined by the load of tasks currently enqueued on that
5690 * CPU as well as tasks which are currently sleeping after an execution on that
5693 * This method returns the load of the specified CPU by discounting the load of
5694 * the specified task, whenever the task is currently contributing to the CPU
5697 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
5699 struct cfs_rq *cfs_rq;
5702 /* Task has no contribution or is new */
5703 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5704 return cpu_load(rq);
5707 load = READ_ONCE(cfs_rq->avg.load_avg);
5709 /* Discount task's util from CPU's util */
5710 lsub_positive(&load, task_h_load(p));
5715 static unsigned long cpu_runnable(struct rq *rq)
5717 return cfs_rq_runnable_avg(&rq->cfs);
5720 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
5722 struct cfs_rq *cfs_rq;
5723 unsigned int runnable;
5725 /* Task has no contribution or is new */
5726 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5727 return cpu_runnable(rq);
5730 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
5732 /* Discount task's runnable from CPU's runnable */
5733 lsub_positive(&runnable, p->se.avg.runnable_avg);
5738 static unsigned long capacity_of(int cpu)
5740 return cpu_rq(cpu)->cpu_capacity;
5743 static void record_wakee(struct task_struct *p)
5746 * Only decay a single time; tasks that have less then 1 wakeup per
5747 * jiffy will not have built up many flips.
5749 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5750 current->wakee_flips >>= 1;
5751 current->wakee_flip_decay_ts = jiffies;
5754 if (current->last_wakee != p) {
5755 current->last_wakee = p;
5756 current->wakee_flips++;
5761 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5763 * A waker of many should wake a different task than the one last awakened
5764 * at a frequency roughly N times higher than one of its wakees.
5766 * In order to determine whether we should let the load spread vs consolidating
5767 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5768 * partner, and a factor of lls_size higher frequency in the other.
5770 * With both conditions met, we can be relatively sure that the relationship is
5771 * non-monogamous, with partner count exceeding socket size.
5773 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5774 * whatever is irrelevant, spread criteria is apparent partner count exceeds
5777 static int wake_wide(struct task_struct *p)
5779 unsigned int master = current->wakee_flips;
5780 unsigned int slave = p->wakee_flips;
5781 int factor = __this_cpu_read(sd_llc_size);
5784 swap(master, slave);
5785 if (slave < factor || master < slave * factor)
5791 * The purpose of wake_affine() is to quickly determine on which CPU we can run
5792 * soonest. For the purpose of speed we only consider the waking and previous
5795 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
5796 * cache-affine and is (or will be) idle.
5798 * wake_affine_weight() - considers the weight to reflect the average
5799 * scheduling latency of the CPUs. This seems to work
5800 * for the overloaded case.
5803 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
5806 * If this_cpu is idle, it implies the wakeup is from interrupt
5807 * context. Only allow the move if cache is shared. Otherwise an
5808 * interrupt intensive workload could force all tasks onto one
5809 * node depending on the IO topology or IRQ affinity settings.
5811 * If the prev_cpu is idle and cache affine then avoid a migration.
5812 * There is no guarantee that the cache hot data from an interrupt
5813 * is more important than cache hot data on the prev_cpu and from
5814 * a cpufreq perspective, it's better to have higher utilisation
5817 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
5818 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
5820 if (sync && cpu_rq(this_cpu)->nr_running == 1)
5823 if (available_idle_cpu(prev_cpu))
5826 return nr_cpumask_bits;
5830 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
5831 int this_cpu, int prev_cpu, int sync)
5833 s64 this_eff_load, prev_eff_load;
5834 unsigned long task_load;
5836 this_eff_load = cpu_load(cpu_rq(this_cpu));
5839 unsigned long current_load = task_h_load(current);
5841 if (current_load > this_eff_load)
5844 this_eff_load -= current_load;
5847 task_load = task_h_load(p);
5849 this_eff_load += task_load;
5850 if (sched_feat(WA_BIAS))
5851 this_eff_load *= 100;
5852 this_eff_load *= capacity_of(prev_cpu);
5854 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
5855 prev_eff_load -= task_load;
5856 if (sched_feat(WA_BIAS))
5857 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
5858 prev_eff_load *= capacity_of(this_cpu);
5861 * If sync, adjust the weight of prev_eff_load such that if
5862 * prev_eff == this_eff that select_idle_sibling() will consider
5863 * stacking the wakee on top of the waker if no other CPU is
5869 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
5872 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5873 int this_cpu, int prev_cpu, int sync)
5875 int target = nr_cpumask_bits;
5877 if (sched_feat(WA_IDLE))
5878 target = wake_affine_idle(this_cpu, prev_cpu, sync);
5880 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
5881 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
5883 schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
5884 if (target == nr_cpumask_bits)
5887 schedstat_inc(sd->ttwu_move_affine);
5888 schedstat_inc(p->se.statistics.nr_wakeups_affine);
5892 static struct sched_group *
5893 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
5896 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
5899 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
5901 unsigned long load, min_load = ULONG_MAX;
5902 unsigned int min_exit_latency = UINT_MAX;
5903 u64 latest_idle_timestamp = 0;
5904 int least_loaded_cpu = this_cpu;
5905 int shallowest_idle_cpu = -1;
5908 /* Check if we have any choice: */
5909 if (group->group_weight == 1)
5910 return cpumask_first(sched_group_span(group));
5912 /* Traverse only the allowed CPUs */
5913 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
5914 if (sched_idle_cpu(i))
5917 if (available_idle_cpu(i)) {
5918 struct rq *rq = cpu_rq(i);
5919 struct cpuidle_state *idle = idle_get_state(rq);
5920 if (idle && idle->exit_latency < min_exit_latency) {
5922 * We give priority to a CPU whose idle state
5923 * has the smallest exit latency irrespective
5924 * of any idle timestamp.
5926 min_exit_latency = idle->exit_latency;
5927 latest_idle_timestamp = rq->idle_stamp;
5928 shallowest_idle_cpu = i;
5929 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
5930 rq->idle_stamp > latest_idle_timestamp) {
5932 * If equal or no active idle state, then
5933 * the most recently idled CPU might have
5936 latest_idle_timestamp = rq->idle_stamp;
5937 shallowest_idle_cpu = i;
5939 } else if (shallowest_idle_cpu == -1) {
5940 load = cpu_load(cpu_rq(i));
5941 if (load < min_load) {
5943 least_loaded_cpu = i;
5948 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
5951 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
5952 int cpu, int prev_cpu, int sd_flag)
5956 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
5960 * We need task's util for cpu_util_without, sync it up to
5961 * prev_cpu's last_update_time.
5963 if (!(sd_flag & SD_BALANCE_FORK))
5964 sync_entity_load_avg(&p->se);
5967 struct sched_group *group;
5968 struct sched_domain *tmp;
5971 if (!(sd->flags & sd_flag)) {
5976 group = find_idlest_group(sd, p, cpu);
5982 new_cpu = find_idlest_group_cpu(group, p, cpu);
5983 if (new_cpu == cpu) {
5984 /* Now try balancing at a lower domain level of 'cpu': */
5989 /* Now try balancing at a lower domain level of 'new_cpu': */
5991 weight = sd->span_weight;
5993 for_each_domain(cpu, tmp) {
5994 if (weight <= tmp->span_weight)
5996 if (tmp->flags & sd_flag)
6004 static inline int __select_idle_cpu(int cpu)
6006 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6012 #ifdef CONFIG_SCHED_SMT
6013 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6014 EXPORT_SYMBOL_GPL(sched_smt_present);
6016 static inline void set_idle_cores(int cpu, int val)
6018 struct sched_domain_shared *sds;
6020 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6022 WRITE_ONCE(sds->has_idle_cores, val);
6025 static inline bool test_idle_cores(int cpu, bool def)
6027 struct sched_domain_shared *sds;
6029 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6031 return READ_ONCE(sds->has_idle_cores);
6037 * Scans the local SMT mask to see if the entire core is idle, and records this
6038 * information in sd_llc_shared->has_idle_cores.
6040 * Since SMT siblings share all cache levels, inspecting this limited remote
6041 * state should be fairly cheap.
6043 void __update_idle_core(struct rq *rq)
6045 int core = cpu_of(rq);
6049 if (test_idle_cores(core, true))
6052 for_each_cpu(cpu, cpu_smt_mask(core)) {
6056 if (!available_idle_cpu(cpu))
6060 set_idle_cores(core, 1);
6066 * Scan the entire LLC domain for idle cores; this dynamically switches off if
6067 * there are no idle cores left in the system; tracked through
6068 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6070 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
6075 if (!static_branch_likely(&sched_smt_present))
6076 return __select_idle_cpu(core);
6078 for_each_cpu(cpu, cpu_smt_mask(core)) {
6079 if (!available_idle_cpu(cpu)) {
6081 if (*idle_cpu == -1) {
6082 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, p->cpus_ptr)) {
6090 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, p->cpus_ptr))
6097 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
6101 #else /* CONFIG_SCHED_SMT */
6103 static inline void set_idle_cores(int cpu, int val)
6107 static inline bool test_idle_cores(int cpu, bool def)
6112 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
6114 return __select_idle_cpu(core);
6117 #endif /* CONFIG_SCHED_SMT */
6120 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6121 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6122 * average idle time for this rq (as found in rq->avg_idle).
6124 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
6126 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6127 int i, cpu, idle_cpu = -1, nr = INT_MAX;
6128 bool smt = test_idle_cores(target, false);
6129 int this = smp_processor_id();
6130 struct sched_domain *this_sd;
6133 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
6137 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6139 if (sched_feat(SIS_PROP) && !smt) {
6140 u64 avg_cost, avg_idle, span_avg;
6143 * Due to large variance we need a large fuzz factor;
6144 * hackbench in particularly is sensitive here.
6146 avg_idle = this_rq()->avg_idle / 512;
6147 avg_cost = this_sd->avg_scan_cost + 1;
6149 span_avg = sd->span_weight * avg_idle;
6150 if (span_avg > 4*avg_cost)
6151 nr = div_u64(span_avg, avg_cost);
6155 time = cpu_clock(this);
6158 for_each_cpu_wrap(cpu, cpus, target) {
6160 i = select_idle_core(p, cpu, cpus, &idle_cpu);
6161 if ((unsigned int)i < nr_cpumask_bits)
6167 idle_cpu = __select_idle_cpu(cpu);
6168 if ((unsigned int)idle_cpu < nr_cpumask_bits)
6174 set_idle_cores(this, false);
6176 if (sched_feat(SIS_PROP) && !smt) {
6177 time = cpu_clock(this) - time;
6178 update_avg(&this_sd->avg_scan_cost, time);
6185 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
6186 * the task fits. If no CPU is big enough, but there are idle ones, try to
6187 * maximize capacity.
6190 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
6192 unsigned long task_util, best_cap = 0;
6193 int cpu, best_cpu = -1;
6194 struct cpumask *cpus;
6196 cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6197 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6199 task_util = uclamp_task_util(p);
6201 for_each_cpu_wrap(cpu, cpus, target) {
6202 unsigned long cpu_cap = capacity_of(cpu);
6204 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
6206 if (fits_capacity(task_util, cpu_cap))
6209 if (cpu_cap > best_cap) {
6218 static inline bool asym_fits_capacity(int task_util, int cpu)
6220 if (static_branch_unlikely(&sched_asym_cpucapacity))
6221 return fits_capacity(task_util, capacity_of(cpu));
6227 * Try and locate an idle core/thread in the LLC cache domain.
6229 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6231 struct sched_domain *sd;
6232 unsigned long task_util;
6233 int i, recent_used_cpu;
6236 * On asymmetric system, update task utilization because we will check
6237 * that the task fits with cpu's capacity.
6239 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6240 sync_entity_load_avg(&p->se);
6241 task_util = uclamp_task_util(p);
6244 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
6245 asym_fits_capacity(task_util, target))
6249 * If the previous CPU is cache affine and idle, don't be stupid:
6251 if (prev != target && cpus_share_cache(prev, target) &&
6252 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
6253 asym_fits_capacity(task_util, prev))
6257 * Allow a per-cpu kthread to stack with the wakee if the
6258 * kworker thread and the tasks previous CPUs are the same.
6259 * The assumption is that the wakee queued work for the
6260 * per-cpu kthread that is now complete and the wakeup is
6261 * essentially a sync wakeup. An obvious example of this
6262 * pattern is IO completions.
6264 if (is_per_cpu_kthread(current) &&
6265 prev == smp_processor_id() &&
6266 this_rq()->nr_running <= 1) {
6270 /* Check a recently used CPU as a potential idle candidate: */
6271 recent_used_cpu = p->recent_used_cpu;
6272 if (recent_used_cpu != prev &&
6273 recent_used_cpu != target &&
6274 cpus_share_cache(recent_used_cpu, target) &&
6275 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
6276 cpumask_test_cpu(p->recent_used_cpu, p->cpus_ptr) &&
6277 asym_fits_capacity(task_util, recent_used_cpu)) {
6279 * Replace recent_used_cpu with prev as it is a potential
6280 * candidate for the next wake:
6282 p->recent_used_cpu = prev;
6283 return recent_used_cpu;
6287 * For asymmetric CPU capacity systems, our domain of interest is
6288 * sd_asym_cpucapacity rather than sd_llc.
6290 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6291 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
6293 * On an asymmetric CPU capacity system where an exclusive
6294 * cpuset defines a symmetric island (i.e. one unique
6295 * capacity_orig value through the cpuset), the key will be set
6296 * but the CPUs within that cpuset will not have a domain with
6297 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
6301 i = select_idle_capacity(p, sd, target);
6302 return ((unsigned)i < nr_cpumask_bits) ? i : target;
6306 sd = rcu_dereference(per_cpu(sd_llc, target));
6310 i = select_idle_cpu(p, sd, target);
6311 if ((unsigned)i < nr_cpumask_bits)
6318 * cpu_util - Estimates the amount of capacity of a CPU used by CFS tasks.
6319 * @cpu: the CPU to get the utilization of
6321 * The unit of the return value must be the one of capacity so we can compare
6322 * the utilization with the capacity of the CPU that is available for CFS task
6323 * (ie cpu_capacity).
6325 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
6326 * recent utilization of currently non-runnable tasks on a CPU. It represents
6327 * the amount of utilization of a CPU in the range [0..capacity_orig] where
6328 * capacity_orig is the cpu_capacity available at the highest frequency
6329 * (arch_scale_freq_capacity()).
6330 * The utilization of a CPU converges towards a sum equal to or less than the
6331 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
6332 * the running time on this CPU scaled by capacity_curr.
6334 * The estimated utilization of a CPU is defined to be the maximum between its
6335 * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
6336 * currently RUNNABLE on that CPU.
6337 * This allows to properly represent the expected utilization of a CPU which
6338 * has just got a big task running since a long sleep period. At the same time
6339 * however it preserves the benefits of the "blocked utilization" in
6340 * describing the potential for other tasks waking up on the same CPU.
6342 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
6343 * higher than capacity_orig because of unfortunate rounding in
6344 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
6345 * the average stabilizes with the new running time. We need to check that the
6346 * utilization stays within the range of [0..capacity_orig] and cap it if
6347 * necessary. Without utilization capping, a group could be seen as overloaded
6348 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
6349 * available capacity. We allow utilization to overshoot capacity_curr (but not
6350 * capacity_orig) as it useful for predicting the capacity required after task
6351 * migrations (scheduler-driven DVFS).
6353 * Return: the (estimated) utilization for the specified CPU
6355 static inline unsigned long cpu_util(int cpu)
6357 struct cfs_rq *cfs_rq;
6360 cfs_rq = &cpu_rq(cpu)->cfs;
6361 util = READ_ONCE(cfs_rq->avg.util_avg);
6363 if (sched_feat(UTIL_EST))
6364 util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
6366 return min_t(unsigned long, util, capacity_orig_of(cpu));
6370 * cpu_util_without: compute cpu utilization without any contributions from *p
6371 * @cpu: the CPU which utilization is requested
6372 * @p: the task which utilization should be discounted
6374 * The utilization of a CPU is defined by the utilization of tasks currently
6375 * enqueued on that CPU as well as tasks which are currently sleeping after an
6376 * execution on that CPU.
6378 * This method returns the utilization of the specified CPU by discounting the
6379 * utilization of the specified task, whenever the task is currently
6380 * contributing to the CPU utilization.
6382 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
6384 struct cfs_rq *cfs_rq;
6387 /* Task has no contribution or is new */
6388 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6389 return cpu_util(cpu);
6391 cfs_rq = &cpu_rq(cpu)->cfs;
6392 util = READ_ONCE(cfs_rq->avg.util_avg);
6394 /* Discount task's util from CPU's util */
6395 lsub_positive(&util, task_util(p));
6400 * a) if *p is the only task sleeping on this CPU, then:
6401 * cpu_util (== task_util) > util_est (== 0)
6402 * and thus we return:
6403 * cpu_util_without = (cpu_util - task_util) = 0
6405 * b) if other tasks are SLEEPING on this CPU, which is now exiting
6407 * cpu_util >= task_util
6408 * cpu_util > util_est (== 0)
6409 * and thus we discount *p's blocked utilization to return:
6410 * cpu_util_without = (cpu_util - task_util) >= 0
6412 * c) if other tasks are RUNNABLE on that CPU and
6413 * util_est > cpu_util
6414 * then we use util_est since it returns a more restrictive
6415 * estimation of the spare capacity on that CPU, by just
6416 * considering the expected utilization of tasks already
6417 * runnable on that CPU.
6419 * Cases a) and b) are covered by the above code, while case c) is
6420 * covered by the following code when estimated utilization is
6423 if (sched_feat(UTIL_EST)) {
6424 unsigned int estimated =
6425 READ_ONCE(cfs_rq->avg.util_est.enqueued);
6428 * Despite the following checks we still have a small window
6429 * for a possible race, when an execl's select_task_rq_fair()
6430 * races with LB's detach_task():
6433 * p->on_rq = TASK_ON_RQ_MIGRATING;
6434 * ---------------------------------- A
6435 * deactivate_task() \
6436 * dequeue_task() + RaceTime
6437 * util_est_dequeue() /
6438 * ---------------------------------- B
6440 * The additional check on "current == p" it's required to
6441 * properly fix the execl regression and it helps in further
6442 * reducing the chances for the above race.
6444 if (unlikely(task_on_rq_queued(p) || current == p))
6445 lsub_positive(&estimated, _task_util_est(p));
6447 util = max(util, estimated);
6451 * Utilization (estimated) can exceed the CPU capacity, thus let's
6452 * clamp to the maximum CPU capacity to ensure consistency with
6453 * the cpu_util call.
6455 return min_t(unsigned long, util, capacity_orig_of(cpu));
6459 * Predicts what cpu_util(@cpu) would return if @p was migrated (and enqueued)
6462 static unsigned long cpu_util_next(int cpu, struct task_struct *p, int dst_cpu)
6464 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
6465 unsigned long util_est, util = READ_ONCE(cfs_rq->avg.util_avg);
6468 * If @p migrates from @cpu to another, remove its contribution. Or,
6469 * if @p migrates from another CPU to @cpu, add its contribution. In
6470 * the other cases, @cpu is not impacted by the migration, so the
6471 * util_avg should already be correct.
6473 if (task_cpu(p) == cpu && dst_cpu != cpu)
6474 sub_positive(&util, task_util(p));
6475 else if (task_cpu(p) != cpu && dst_cpu == cpu)
6476 util += task_util(p);
6478 if (sched_feat(UTIL_EST)) {
6479 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
6482 * During wake-up, the task isn't enqueued yet and doesn't
6483 * appear in the cfs_rq->avg.util_est.enqueued of any rq,
6484 * so just add it (if needed) to "simulate" what will be
6485 * cpu_util() after the task has been enqueued.
6488 util_est += _task_util_est(p);
6490 util = max(util, util_est);
6493 return min(util, capacity_orig_of(cpu));
6497 * compute_energy(): Estimates the energy that @pd would consume if @p was
6498 * migrated to @dst_cpu. compute_energy() predicts what will be the utilization
6499 * landscape of @pd's CPUs after the task migration, and uses the Energy Model
6500 * to compute what would be the energy if we decided to actually migrate that
6504 compute_energy(struct task_struct *p, int dst_cpu, struct perf_domain *pd)
6506 struct cpumask *pd_mask = perf_domain_span(pd);
6507 unsigned long cpu_cap = arch_scale_cpu_capacity(cpumask_first(pd_mask));
6508 unsigned long max_util = 0, sum_util = 0;
6512 * The capacity state of CPUs of the current rd can be driven by CPUs
6513 * of another rd if they belong to the same pd. So, account for the
6514 * utilization of these CPUs too by masking pd with cpu_online_mask
6515 * instead of the rd span.
6517 * If an entire pd is outside of the current rd, it will not appear in
6518 * its pd list and will not be accounted by compute_energy().
6520 for_each_cpu_and(cpu, pd_mask, cpu_online_mask) {
6521 unsigned long cpu_util, util_cfs = cpu_util_next(cpu, p, dst_cpu);
6522 struct task_struct *tsk = cpu == dst_cpu ? p : NULL;
6525 * Busy time computation: utilization clamping is not
6526 * required since the ratio (sum_util / cpu_capacity)
6527 * is already enough to scale the EM reported power
6528 * consumption at the (eventually clamped) cpu_capacity.
6530 sum_util += effective_cpu_util(cpu, util_cfs, cpu_cap,
6534 * Performance domain frequency: utilization clamping
6535 * must be considered since it affects the selection
6536 * of the performance domain frequency.
6537 * NOTE: in case RT tasks are running, by default the
6538 * FREQUENCY_UTIL's utilization can be max OPP.
6540 cpu_util = effective_cpu_util(cpu, util_cfs, cpu_cap,
6541 FREQUENCY_UTIL, tsk);
6542 max_util = max(max_util, cpu_util);
6545 return em_cpu_energy(pd->em_pd, max_util, sum_util);
6549 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
6550 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
6551 * spare capacity in each performance domain and uses it as a potential
6552 * candidate to execute the task. Then, it uses the Energy Model to figure
6553 * out which of the CPU candidates is the most energy-efficient.
6555 * The rationale for this heuristic is as follows. In a performance domain,
6556 * all the most energy efficient CPU candidates (according to the Energy
6557 * Model) are those for which we'll request a low frequency. When there are
6558 * several CPUs for which the frequency request will be the same, we don't
6559 * have enough data to break the tie between them, because the Energy Model
6560 * only includes active power costs. With this model, if we assume that
6561 * frequency requests follow utilization (e.g. using schedutil), the CPU with
6562 * the maximum spare capacity in a performance domain is guaranteed to be among
6563 * the best candidates of the performance domain.
6565 * In practice, it could be preferable from an energy standpoint to pack
6566 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
6567 * but that could also hurt our chances to go cluster idle, and we have no
6568 * ways to tell with the current Energy Model if this is actually a good
6569 * idea or not. So, find_energy_efficient_cpu() basically favors
6570 * cluster-packing, and spreading inside a cluster. That should at least be
6571 * a good thing for latency, and this is consistent with the idea that most
6572 * of the energy savings of EAS come from the asymmetry of the system, and
6573 * not so much from breaking the tie between identical CPUs. That's also the
6574 * reason why EAS is enabled in the topology code only for systems where
6575 * SD_ASYM_CPUCAPACITY is set.
6577 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
6578 * they don't have any useful utilization data yet and it's not possible to
6579 * forecast their impact on energy consumption. Consequently, they will be
6580 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
6581 * to be energy-inefficient in some use-cases. The alternative would be to
6582 * bias new tasks towards specific types of CPUs first, or to try to infer
6583 * their util_avg from the parent task, but those heuristics could hurt
6584 * other use-cases too. So, until someone finds a better way to solve this,
6585 * let's keep things simple by re-using the existing slow path.
6587 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
6589 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
6590 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6591 unsigned long cpu_cap, util, base_energy = 0;
6592 int cpu, best_energy_cpu = prev_cpu;
6593 struct sched_domain *sd;
6594 struct perf_domain *pd;
6597 pd = rcu_dereference(rd->pd);
6598 if (!pd || READ_ONCE(rd->overutilized))
6602 * Energy-aware wake-up happens on the lowest sched_domain starting
6603 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
6605 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
6606 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
6611 sync_entity_load_avg(&p->se);
6612 if (!task_util_est(p))
6615 for (; pd; pd = pd->next) {
6616 unsigned long cur_delta, spare_cap, max_spare_cap = 0;
6617 unsigned long base_energy_pd;
6618 int max_spare_cap_cpu = -1;
6620 /* Compute the 'base' energy of the pd, without @p */
6621 base_energy_pd = compute_energy(p, -1, pd);
6622 base_energy += base_energy_pd;
6624 for_each_cpu_and(cpu, perf_domain_span(pd), sched_domain_span(sd)) {
6625 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
6628 util = cpu_util_next(cpu, p, cpu);
6629 cpu_cap = capacity_of(cpu);
6630 spare_cap = cpu_cap;
6631 lsub_positive(&spare_cap, util);
6634 * Skip CPUs that cannot satisfy the capacity request.
6635 * IOW, placing the task there would make the CPU
6636 * overutilized. Take uclamp into account to see how
6637 * much capacity we can get out of the CPU; this is
6638 * aligned with sched_cpu_util().
6640 util = uclamp_rq_util_with(cpu_rq(cpu), util, p);
6641 if (!fits_capacity(util, cpu_cap))
6644 /* Always use prev_cpu as a candidate. */
6645 if (cpu == prev_cpu) {
6646 prev_delta = compute_energy(p, prev_cpu, pd);
6647 prev_delta -= base_energy_pd;
6648 best_delta = min(best_delta, prev_delta);
6652 * Find the CPU with the maximum spare capacity in
6653 * the performance domain
6655 if (spare_cap > max_spare_cap) {
6656 max_spare_cap = spare_cap;
6657 max_spare_cap_cpu = cpu;
6661 /* Evaluate the energy impact of using this CPU. */
6662 if (max_spare_cap_cpu >= 0 && max_spare_cap_cpu != prev_cpu) {
6663 cur_delta = compute_energy(p, max_spare_cap_cpu, pd);
6664 cur_delta -= base_energy_pd;
6665 if (cur_delta < best_delta) {
6666 best_delta = cur_delta;
6667 best_energy_cpu = max_spare_cap_cpu;
6675 * Pick the best CPU if prev_cpu cannot be used, or if it saves at
6676 * least 6% of the energy used by prev_cpu.
6678 if (prev_delta == ULONG_MAX)
6679 return best_energy_cpu;
6681 if ((prev_delta - best_delta) > ((prev_delta + base_energy) >> 4))
6682 return best_energy_cpu;
6693 * select_task_rq_fair: Select target runqueue for the waking task in domains
6694 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
6695 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
6697 * Balances load by selecting the idlest CPU in the idlest group, or under
6698 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
6700 * Returns the target CPU number.
6702 * preempt must be disabled.
6705 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
6707 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
6708 struct sched_domain *tmp, *sd = NULL;
6709 int cpu = smp_processor_id();
6710 int new_cpu = prev_cpu;
6711 int want_affine = 0;
6712 /* SD_flags and WF_flags share the first nibble */
6713 int sd_flag = wake_flags & 0xF;
6715 if (wake_flags & WF_TTWU) {
6718 if (sched_energy_enabled()) {
6719 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
6725 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
6729 for_each_domain(cpu, tmp) {
6731 * If both 'cpu' and 'prev_cpu' are part of this domain,
6732 * cpu is a valid SD_WAKE_AFFINE target.
6734 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6735 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
6736 if (cpu != prev_cpu)
6737 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
6739 sd = NULL; /* Prefer wake_affine over balance flags */
6743 if (tmp->flags & sd_flag)
6745 else if (!want_affine)
6751 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
6752 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
6754 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6757 current->recent_used_cpu = cpu;
6764 static void detach_entity_cfs_rq(struct sched_entity *se);
6767 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
6768 * cfs_rq_of(p) references at time of call are still valid and identify the
6769 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
6771 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
6774 * As blocked tasks retain absolute vruntime the migration needs to
6775 * deal with this by subtracting the old and adding the new
6776 * min_vruntime -- the latter is done by enqueue_entity() when placing
6777 * the task on the new runqueue.
6779 if (p->state == TASK_WAKING) {
6780 struct sched_entity *se = &p->se;
6781 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6784 #ifndef CONFIG_64BIT
6785 u64 min_vruntime_copy;
6788 min_vruntime_copy = cfs_rq->min_vruntime_copy;
6790 min_vruntime = cfs_rq->min_vruntime;
6791 } while (min_vruntime != min_vruntime_copy);
6793 min_vruntime = cfs_rq->min_vruntime;
6796 se->vruntime -= min_vruntime;
6799 if (p->on_rq == TASK_ON_RQ_MIGRATING) {
6801 * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
6802 * rq->lock and can modify state directly.
6804 lockdep_assert_held(&task_rq(p)->lock);
6805 detach_entity_cfs_rq(&p->se);
6809 * We are supposed to update the task to "current" time, then
6810 * its up to date and ready to go to new CPU/cfs_rq. But we
6811 * have difficulty in getting what current time is, so simply
6812 * throw away the out-of-date time. This will result in the
6813 * wakee task is less decayed, but giving the wakee more load
6816 remove_entity_load_avg(&p->se);
6819 /* Tell new CPU we are migrated */
6820 p->se.avg.last_update_time = 0;
6822 /* We have migrated, no longer consider this task hot */
6823 p->se.exec_start = 0;
6825 update_scan_period(p, new_cpu);
6828 static void task_dead_fair(struct task_struct *p)
6830 remove_entity_load_avg(&p->se);
6834 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6839 return newidle_balance(rq, rf) != 0;
6841 #endif /* CONFIG_SMP */
6843 static unsigned long wakeup_gran(struct sched_entity *se)
6845 unsigned long gran = sysctl_sched_wakeup_granularity;
6848 * Since its curr running now, convert the gran from real-time
6849 * to virtual-time in his units.
6851 * By using 'se' instead of 'curr' we penalize light tasks, so
6852 * they get preempted easier. That is, if 'se' < 'curr' then
6853 * the resulting gran will be larger, therefore penalizing the
6854 * lighter, if otoh 'se' > 'curr' then the resulting gran will
6855 * be smaller, again penalizing the lighter task.
6857 * This is especially important for buddies when the leftmost
6858 * task is higher priority than the buddy.
6860 return calc_delta_fair(gran, se);
6864 * Should 'se' preempt 'curr'.
6878 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
6880 s64 gran, vdiff = curr->vruntime - se->vruntime;
6885 gran = wakeup_gran(se);
6892 static void set_last_buddy(struct sched_entity *se)
6894 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
6897 for_each_sched_entity(se) {
6898 if (SCHED_WARN_ON(!se->on_rq))
6900 cfs_rq_of(se)->last = se;
6904 static void set_next_buddy(struct sched_entity *se)
6906 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
6909 for_each_sched_entity(se) {
6910 if (SCHED_WARN_ON(!se->on_rq))
6912 cfs_rq_of(se)->next = se;
6916 static void set_skip_buddy(struct sched_entity *se)
6918 for_each_sched_entity(se)
6919 cfs_rq_of(se)->skip = se;
6923 * Preempt the current task with a newly woken task if needed:
6925 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
6927 struct task_struct *curr = rq->curr;
6928 struct sched_entity *se = &curr->se, *pse = &p->se;
6929 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6930 int scale = cfs_rq->nr_running >= sched_nr_latency;
6931 int next_buddy_marked = 0;
6933 if (unlikely(se == pse))
6937 * This is possible from callers such as attach_tasks(), in which we
6938 * unconditionally check_prempt_curr() after an enqueue (which may have
6939 * lead to a throttle). This both saves work and prevents false
6940 * next-buddy nomination below.
6942 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
6945 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
6946 set_next_buddy(pse);
6947 next_buddy_marked = 1;
6951 * We can come here with TIF_NEED_RESCHED already set from new task
6954 * Note: this also catches the edge-case of curr being in a throttled
6955 * group (e.g. via set_curr_task), since update_curr() (in the
6956 * enqueue of curr) will have resulted in resched being set. This
6957 * prevents us from potentially nominating it as a false LAST_BUDDY
6960 if (test_tsk_need_resched(curr))
6963 /* Idle tasks are by definition preempted by non-idle tasks. */
6964 if (unlikely(task_has_idle_policy(curr)) &&
6965 likely(!task_has_idle_policy(p)))
6969 * Batch and idle tasks do not preempt non-idle tasks (their preemption
6970 * is driven by the tick):
6972 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
6975 find_matching_se(&se, &pse);
6976 update_curr(cfs_rq_of(se));
6978 if (wakeup_preempt_entity(se, pse) == 1) {
6980 * Bias pick_next to pick the sched entity that is
6981 * triggering this preemption.
6983 if (!next_buddy_marked)
6984 set_next_buddy(pse);
6993 * Only set the backward buddy when the current task is still
6994 * on the rq. This can happen when a wakeup gets interleaved
6995 * with schedule on the ->pre_schedule() or idle_balance()
6996 * point, either of which can * drop the rq lock.
6998 * Also, during early boot the idle thread is in the fair class,
6999 * for obvious reasons its a bad idea to schedule back to it.
7001 if (unlikely(!se->on_rq || curr == rq->idle))
7004 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7008 struct task_struct *
7009 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7011 struct cfs_rq *cfs_rq = &rq->cfs;
7012 struct sched_entity *se;
7013 struct task_struct *p;
7017 if (!sched_fair_runnable(rq))
7020 #ifdef CONFIG_FAIR_GROUP_SCHED
7021 if (!prev || prev->sched_class != &fair_sched_class)
7025 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7026 * likely that a next task is from the same cgroup as the current.
7028 * Therefore attempt to avoid putting and setting the entire cgroup
7029 * hierarchy, only change the part that actually changes.
7033 struct sched_entity *curr = cfs_rq->curr;
7036 * Since we got here without doing put_prev_entity() we also
7037 * have to consider cfs_rq->curr. If it is still a runnable
7038 * entity, update_curr() will update its vruntime, otherwise
7039 * forget we've ever seen it.
7043 update_curr(cfs_rq);
7048 * This call to check_cfs_rq_runtime() will do the
7049 * throttle and dequeue its entity in the parent(s).
7050 * Therefore the nr_running test will indeed
7053 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
7056 if (!cfs_rq->nr_running)
7063 se = pick_next_entity(cfs_rq, curr);
7064 cfs_rq = group_cfs_rq(se);
7070 * Since we haven't yet done put_prev_entity and if the selected task
7071 * is a different task than we started out with, try and touch the
7072 * least amount of cfs_rqs.
7075 struct sched_entity *pse = &prev->se;
7077 while (!(cfs_rq = is_same_group(se, pse))) {
7078 int se_depth = se->depth;
7079 int pse_depth = pse->depth;
7081 if (se_depth <= pse_depth) {
7082 put_prev_entity(cfs_rq_of(pse), pse);
7083 pse = parent_entity(pse);
7085 if (se_depth >= pse_depth) {
7086 set_next_entity(cfs_rq_of(se), se);
7087 se = parent_entity(se);
7091 put_prev_entity(cfs_rq, pse);
7092 set_next_entity(cfs_rq, se);
7099 put_prev_task(rq, prev);
7102 se = pick_next_entity(cfs_rq, NULL);
7103 set_next_entity(cfs_rq, se);
7104 cfs_rq = group_cfs_rq(se);
7109 done: __maybe_unused;
7112 * Move the next running task to the front of
7113 * the list, so our cfs_tasks list becomes MRU
7116 list_move(&p->se.group_node, &rq->cfs_tasks);
7119 if (hrtick_enabled_fair(rq))
7120 hrtick_start_fair(rq, p);
7122 update_misfit_status(p, rq);
7130 new_tasks = newidle_balance(rq, rf);
7133 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
7134 * possible for any higher priority task to appear. In that case we
7135 * must re-start the pick_next_entity() loop.
7144 * rq is about to be idle, check if we need to update the
7145 * lost_idle_time of clock_pelt
7147 update_idle_rq_clock_pelt(rq);
7152 static struct task_struct *__pick_next_task_fair(struct rq *rq)
7154 return pick_next_task_fair(rq, NULL, NULL);
7158 * Account for a descheduled task:
7160 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
7162 struct sched_entity *se = &prev->se;
7163 struct cfs_rq *cfs_rq;
7165 for_each_sched_entity(se) {
7166 cfs_rq = cfs_rq_of(se);
7167 put_prev_entity(cfs_rq, se);
7172 * sched_yield() is very simple
7174 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7176 static void yield_task_fair(struct rq *rq)
7178 struct task_struct *curr = rq->curr;
7179 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7180 struct sched_entity *se = &curr->se;
7183 * Are we the only task in the tree?
7185 if (unlikely(rq->nr_running == 1))
7188 clear_buddies(cfs_rq, se);
7190 if (curr->policy != SCHED_BATCH) {
7191 update_rq_clock(rq);
7193 * Update run-time statistics of the 'current'.
7195 update_curr(cfs_rq);
7197 * Tell update_rq_clock() that we've just updated,
7198 * so we don't do microscopic update in schedule()
7199 * and double the fastpath cost.
7201 rq_clock_skip_update(rq);
7207 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
7209 struct sched_entity *se = &p->se;
7211 /* throttled hierarchies are not runnable */
7212 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
7215 /* Tell the scheduler that we'd really like pse to run next. */
7218 yield_task_fair(rq);
7224 /**************************************************
7225 * Fair scheduling class load-balancing methods.
7229 * The purpose of load-balancing is to achieve the same basic fairness the
7230 * per-CPU scheduler provides, namely provide a proportional amount of compute
7231 * time to each task. This is expressed in the following equation:
7233 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
7235 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
7236 * W_i,0 is defined as:
7238 * W_i,0 = \Sum_j w_i,j (2)
7240 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
7241 * is derived from the nice value as per sched_prio_to_weight[].
7243 * The weight average is an exponential decay average of the instantaneous
7246 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
7248 * C_i is the compute capacity of CPU i, typically it is the
7249 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7250 * can also include other factors [XXX].
7252 * To achieve this balance we define a measure of imbalance which follows
7253 * directly from (1):
7255 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
7257 * We them move tasks around to minimize the imbalance. In the continuous
7258 * function space it is obvious this converges, in the discrete case we get
7259 * a few fun cases generally called infeasible weight scenarios.
7262 * - infeasible weights;
7263 * - local vs global optima in the discrete case. ]
7268 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
7269 * for all i,j solution, we create a tree of CPUs that follows the hardware
7270 * topology where each level pairs two lower groups (or better). This results
7271 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
7272 * tree to only the first of the previous level and we decrease the frequency
7273 * of load-balance at each level inv. proportional to the number of CPUs in
7279 * \Sum { --- * --- * 2^i } = O(n) (5)
7281 * `- size of each group
7282 * | | `- number of CPUs doing load-balance
7284 * `- sum over all levels
7286 * Coupled with a limit on how many tasks we can migrate every balance pass,
7287 * this makes (5) the runtime complexity of the balancer.
7289 * An important property here is that each CPU is still (indirectly) connected
7290 * to every other CPU in at most O(log n) steps:
7292 * The adjacency matrix of the resulting graph is given by:
7295 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
7298 * And you'll find that:
7300 * A^(log_2 n)_i,j != 0 for all i,j (7)
7302 * Showing there's indeed a path between every CPU in at most O(log n) steps.
7303 * The task movement gives a factor of O(m), giving a convergence complexity
7306 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
7311 * In order to avoid CPUs going idle while there's still work to do, new idle
7312 * balancing is more aggressive and has the newly idle CPU iterate up the domain
7313 * tree itself instead of relying on other CPUs to bring it work.
7315 * This adds some complexity to both (5) and (8) but it reduces the total idle
7323 * Cgroups make a horror show out of (2), instead of a simple sum we get:
7326 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
7331 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
7333 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
7335 * The big problem is S_k, its a global sum needed to compute a local (W_i)
7338 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7339 * rewrite all of this once again.]
7342 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7344 enum fbq_type { regular, remote, all };
7347 * 'group_type' describes the group of CPUs at the moment of load balancing.
7349 * The enum is ordered by pulling priority, with the group with lowest priority
7350 * first so the group_type can simply be compared when selecting the busiest
7351 * group. See update_sd_pick_busiest().
7354 /* The group has spare capacity that can be used to run more tasks. */
7355 group_has_spare = 0,
7357 * The group is fully used and the tasks don't compete for more CPU
7358 * cycles. Nevertheless, some tasks might wait before running.
7362 * SD_ASYM_CPUCAPACITY only: One task doesn't fit with CPU's capacity
7363 * and must be migrated to a more powerful CPU.
7367 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
7368 * and the task should be migrated to it instead of running on the
7373 * The tasks' affinity constraints previously prevented the scheduler
7374 * from balancing the load across the system.
7378 * The CPU is overloaded and can't provide expected CPU cycles to all
7384 enum migration_type {
7391 #define LBF_ALL_PINNED 0x01
7392 #define LBF_NEED_BREAK 0x02
7393 #define LBF_DST_PINNED 0x04
7394 #define LBF_SOME_PINNED 0x08
7397 struct sched_domain *sd;
7405 struct cpumask *dst_grpmask;
7407 enum cpu_idle_type idle;
7409 /* The set of CPUs under consideration for load-balancing */
7410 struct cpumask *cpus;
7415 unsigned int loop_break;
7416 unsigned int loop_max;
7418 enum fbq_type fbq_type;
7419 enum migration_type migration_type;
7420 struct list_head tasks;
7424 * Is this task likely cache-hot:
7426 static int task_hot(struct task_struct *p, struct lb_env *env)
7430 lockdep_assert_held(&env->src_rq->lock);
7432 if (p->sched_class != &fair_sched_class)
7435 if (unlikely(task_has_idle_policy(p)))
7438 /* SMT siblings share cache */
7439 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
7443 * Buddy candidates are cache hot:
7445 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
7446 (&p->se == cfs_rq_of(&p->se)->next ||
7447 &p->se == cfs_rq_of(&p->se)->last))
7450 if (sysctl_sched_migration_cost == -1)
7452 if (sysctl_sched_migration_cost == 0)
7455 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
7457 return delta < (s64)sysctl_sched_migration_cost;
7460 #ifdef CONFIG_NUMA_BALANCING
7462 * Returns 1, if task migration degrades locality
7463 * Returns 0, if task migration improves locality i.e migration preferred.
7464 * Returns -1, if task migration is not affected by locality.
7466 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
7468 struct numa_group *numa_group = rcu_dereference(p->numa_group);
7469 unsigned long src_weight, dst_weight;
7470 int src_nid, dst_nid, dist;
7472 if (!static_branch_likely(&sched_numa_balancing))
7475 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
7478 src_nid = cpu_to_node(env->src_cpu);
7479 dst_nid = cpu_to_node(env->dst_cpu);
7481 if (src_nid == dst_nid)
7484 /* Migrating away from the preferred node is always bad. */
7485 if (src_nid == p->numa_preferred_nid) {
7486 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7492 /* Encourage migration to the preferred node. */
7493 if (dst_nid == p->numa_preferred_nid)
7496 /* Leaving a core idle is often worse than degrading locality. */
7497 if (env->idle == CPU_IDLE)
7500 dist = node_distance(src_nid, dst_nid);
7502 src_weight = group_weight(p, src_nid, dist);
7503 dst_weight = group_weight(p, dst_nid, dist);
7505 src_weight = task_weight(p, src_nid, dist);
7506 dst_weight = task_weight(p, dst_nid, dist);
7509 return dst_weight < src_weight;
7513 static inline int migrate_degrades_locality(struct task_struct *p,
7521 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7524 int can_migrate_task(struct task_struct *p, struct lb_env *env)
7528 lockdep_assert_held(&env->src_rq->lock);
7531 * We do not migrate tasks that are:
7532 * 1) throttled_lb_pair, or
7533 * 2) cannot be migrated to this CPU due to cpus_ptr, or
7534 * 3) running (obviously), or
7535 * 4) are cache-hot on their current CPU.
7537 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7540 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
7543 schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
7545 env->flags |= LBF_SOME_PINNED;
7548 * Remember if this task can be migrated to any other CPU in
7549 * our sched_group. We may want to revisit it if we couldn't
7550 * meet load balance goals by pulling other tasks on src_cpu.
7552 * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
7553 * already computed one in current iteration.
7555 if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
7558 /* Prevent to re-select dst_cpu via env's CPUs: */
7559 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
7560 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
7561 env->flags |= LBF_DST_PINNED;
7562 env->new_dst_cpu = cpu;
7570 /* Record that we found atleast one task that could run on dst_cpu */
7571 env->flags &= ~LBF_ALL_PINNED;
7573 if (task_running(env->src_rq, p)) {
7574 schedstat_inc(p->se.statistics.nr_failed_migrations_running);
7579 * Aggressive migration if:
7580 * 1) destination numa is preferred
7581 * 2) task is cache cold, or
7582 * 3) too many balance attempts have failed.
7584 tsk_cache_hot = migrate_degrades_locality(p, env);
7585 if (tsk_cache_hot == -1)
7586 tsk_cache_hot = task_hot(p, env);
7588 if (tsk_cache_hot <= 0 ||
7589 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
7590 if (tsk_cache_hot == 1) {
7591 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
7592 schedstat_inc(p->se.statistics.nr_forced_migrations);
7597 schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
7602 * detach_task() -- detach the task for the migration specified in env
7604 static void detach_task(struct task_struct *p, struct lb_env *env)
7606 lockdep_assert_held(&env->src_rq->lock);
7608 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
7609 set_task_cpu(p, env->dst_cpu);
7613 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
7614 * part of active balancing operations within "domain".
7616 * Returns a task if successful and NULL otherwise.
7618 static struct task_struct *detach_one_task(struct lb_env *env)
7620 struct task_struct *p;
7622 lockdep_assert_held(&env->src_rq->lock);
7624 list_for_each_entry_reverse(p,
7625 &env->src_rq->cfs_tasks, se.group_node) {
7626 if (!can_migrate_task(p, env))
7629 detach_task(p, env);
7632 * Right now, this is only the second place where
7633 * lb_gained[env->idle] is updated (other is detach_tasks)
7634 * so we can safely collect stats here rather than
7635 * inside detach_tasks().
7637 schedstat_inc(env->sd->lb_gained[env->idle]);
7643 static const unsigned int sched_nr_migrate_break = 32;
7646 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
7647 * busiest_rq, as part of a balancing operation within domain "sd".
7649 * Returns number of detached tasks if successful and 0 otherwise.
7651 static int detach_tasks(struct lb_env *env)
7653 struct list_head *tasks = &env->src_rq->cfs_tasks;
7654 unsigned long util, load;
7655 struct task_struct *p;
7658 lockdep_assert_held(&env->src_rq->lock);
7660 if (env->imbalance <= 0)
7663 while (!list_empty(tasks)) {
7665 * We don't want to steal all, otherwise we may be treated likewise,
7666 * which could at worst lead to a livelock crash.
7668 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
7671 p = list_last_entry(tasks, struct task_struct, se.group_node);
7674 /* We've more or less seen every task there is, call it quits */
7675 if (env->loop > env->loop_max)
7678 /* take a breather every nr_migrate tasks */
7679 if (env->loop > env->loop_break) {
7680 env->loop_break += sched_nr_migrate_break;
7681 env->flags |= LBF_NEED_BREAK;
7685 if (!can_migrate_task(p, env))
7688 switch (env->migration_type) {
7691 * Depending of the number of CPUs and tasks and the
7692 * cgroup hierarchy, task_h_load() can return a null
7693 * value. Make sure that env->imbalance decreases
7694 * otherwise detach_tasks() will stop only after
7695 * detaching up to loop_max tasks.
7697 load = max_t(unsigned long, task_h_load(p), 1);
7699 if (sched_feat(LB_MIN) &&
7700 load < 16 && !env->sd->nr_balance_failed)
7704 * Make sure that we don't migrate too much load.
7705 * Nevertheless, let relax the constraint if
7706 * scheduler fails to find a good waiting task to
7710 if ((load >> env->sd->nr_balance_failed) > env->imbalance)
7713 env->imbalance -= load;
7717 util = task_util_est(p);
7719 if (util > env->imbalance)
7722 env->imbalance -= util;
7729 case migrate_misfit:
7730 /* This is not a misfit task */
7731 if (task_fits_capacity(p, capacity_of(env->src_cpu)))
7738 detach_task(p, env);
7739 list_add(&p->se.group_node, &env->tasks);
7743 #ifdef CONFIG_PREEMPTION
7745 * NEWIDLE balancing is a source of latency, so preemptible
7746 * kernels will stop after the first task is detached to minimize
7747 * the critical section.
7749 if (env->idle == CPU_NEWLY_IDLE)
7754 * We only want to steal up to the prescribed amount of
7757 if (env->imbalance <= 0)
7762 list_move(&p->se.group_node, tasks);
7766 * Right now, this is one of only two places we collect this stat
7767 * so we can safely collect detach_one_task() stats here rather
7768 * than inside detach_one_task().
7770 schedstat_add(env->sd->lb_gained[env->idle], detached);
7776 * attach_task() -- attach the task detached by detach_task() to its new rq.
7778 static void attach_task(struct rq *rq, struct task_struct *p)
7780 lockdep_assert_held(&rq->lock);
7782 BUG_ON(task_rq(p) != rq);
7783 activate_task(rq, p, ENQUEUE_NOCLOCK);
7784 check_preempt_curr(rq, p, 0);
7788 * attach_one_task() -- attaches the task returned from detach_one_task() to
7791 static void attach_one_task(struct rq *rq, struct task_struct *p)
7796 update_rq_clock(rq);
7802 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
7805 static void attach_tasks(struct lb_env *env)
7807 struct list_head *tasks = &env->tasks;
7808 struct task_struct *p;
7811 rq_lock(env->dst_rq, &rf);
7812 update_rq_clock(env->dst_rq);
7814 while (!list_empty(tasks)) {
7815 p = list_first_entry(tasks, struct task_struct, se.group_node);
7816 list_del_init(&p->se.group_node);
7818 attach_task(env->dst_rq, p);
7821 rq_unlock(env->dst_rq, &rf);
7824 #ifdef CONFIG_NO_HZ_COMMON
7825 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
7827 if (cfs_rq->avg.load_avg)
7830 if (cfs_rq->avg.util_avg)
7836 static inline bool others_have_blocked(struct rq *rq)
7838 if (READ_ONCE(rq->avg_rt.util_avg))
7841 if (READ_ONCE(rq->avg_dl.util_avg))
7844 if (thermal_load_avg(rq))
7847 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
7848 if (READ_ONCE(rq->avg_irq.util_avg))
7855 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
7857 rq->last_blocked_load_update_tick = jiffies;
7860 rq->has_blocked_load = 0;
7863 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
7864 static inline bool others_have_blocked(struct rq *rq) { return false; }
7865 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
7868 static bool __update_blocked_others(struct rq *rq, bool *done)
7870 const struct sched_class *curr_class;
7871 u64 now = rq_clock_pelt(rq);
7872 unsigned long thermal_pressure;
7876 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
7877 * DL and IRQ signals have been updated before updating CFS.
7879 curr_class = rq->curr->sched_class;
7881 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
7883 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
7884 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
7885 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
7886 update_irq_load_avg(rq, 0);
7888 if (others_have_blocked(rq))
7894 #ifdef CONFIG_FAIR_GROUP_SCHED
7896 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
7898 if (cfs_rq->load.weight)
7901 if (cfs_rq->avg.load_sum)
7904 if (cfs_rq->avg.util_sum)
7907 if (cfs_rq->avg.runnable_sum)
7913 static bool __update_blocked_fair(struct rq *rq, bool *done)
7915 struct cfs_rq *cfs_rq, *pos;
7916 bool decayed = false;
7917 int cpu = cpu_of(rq);
7920 * Iterates the task_group tree in a bottom up fashion, see
7921 * list_add_leaf_cfs_rq() for details.
7923 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
7924 struct sched_entity *se;
7926 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
7927 update_tg_load_avg(cfs_rq);
7929 if (cfs_rq == &rq->cfs)
7933 /* Propagate pending load changes to the parent, if any: */
7934 se = cfs_rq->tg->se[cpu];
7935 if (se && !skip_blocked_update(se))
7936 update_load_avg(cfs_rq_of(se), se, 0);
7939 * There can be a lot of idle CPU cgroups. Don't let fully
7940 * decayed cfs_rqs linger on the list.
7942 if (cfs_rq_is_decayed(cfs_rq))
7943 list_del_leaf_cfs_rq(cfs_rq);
7945 /* Don't need periodic decay once load/util_avg are null */
7946 if (cfs_rq_has_blocked(cfs_rq))
7954 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
7955 * This needs to be done in a top-down fashion because the load of a child
7956 * group is a fraction of its parents load.
7958 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
7960 struct rq *rq = rq_of(cfs_rq);
7961 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
7962 unsigned long now = jiffies;
7965 if (cfs_rq->last_h_load_update == now)
7968 WRITE_ONCE(cfs_rq->h_load_next, NULL);
7969 for_each_sched_entity(se) {
7970 cfs_rq = cfs_rq_of(se);
7971 WRITE_ONCE(cfs_rq->h_load_next, se);
7972 if (cfs_rq->last_h_load_update == now)
7977 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
7978 cfs_rq->last_h_load_update = now;
7981 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
7982 load = cfs_rq->h_load;
7983 load = div64_ul(load * se->avg.load_avg,
7984 cfs_rq_load_avg(cfs_rq) + 1);
7985 cfs_rq = group_cfs_rq(se);
7986 cfs_rq->h_load = load;
7987 cfs_rq->last_h_load_update = now;
7991 static unsigned long task_h_load(struct task_struct *p)
7993 struct cfs_rq *cfs_rq = task_cfs_rq(p);
7995 update_cfs_rq_h_load(cfs_rq);
7996 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
7997 cfs_rq_load_avg(cfs_rq) + 1);
8000 static bool __update_blocked_fair(struct rq *rq, bool *done)
8002 struct cfs_rq *cfs_rq = &rq->cfs;
8005 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
8006 if (cfs_rq_has_blocked(cfs_rq))
8012 static unsigned long task_h_load(struct task_struct *p)
8014 return p->se.avg.load_avg;
8018 static void update_blocked_averages(int cpu)
8020 bool decayed = false, done = true;
8021 struct rq *rq = cpu_rq(cpu);
8024 rq_lock_irqsave(rq, &rf);
8025 update_rq_clock(rq);
8027 decayed |= __update_blocked_others(rq, &done);
8028 decayed |= __update_blocked_fair(rq, &done);
8030 update_blocked_load_status(rq, !done);
8032 cpufreq_update_util(rq, 0);
8033 rq_unlock_irqrestore(rq, &rf);
8036 /********** Helpers for find_busiest_group ************************/
8039 * sg_lb_stats - stats of a sched_group required for load_balancing
8041 struct sg_lb_stats {
8042 unsigned long avg_load; /*Avg load across the CPUs of the group */
8043 unsigned long group_load; /* Total load over the CPUs of the group */
8044 unsigned long group_capacity;
8045 unsigned long group_util; /* Total utilization over the CPUs of the group */
8046 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
8047 unsigned int sum_nr_running; /* Nr of tasks running in the group */
8048 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
8049 unsigned int idle_cpus;
8050 unsigned int group_weight;
8051 enum group_type group_type;
8052 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
8053 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
8054 #ifdef CONFIG_NUMA_BALANCING
8055 unsigned int nr_numa_running;
8056 unsigned int nr_preferred_running;
8061 * sd_lb_stats - Structure to store the statistics of a sched_domain
8062 * during load balancing.
8064 struct sd_lb_stats {
8065 struct sched_group *busiest; /* Busiest group in this sd */
8066 struct sched_group *local; /* Local group in this sd */
8067 unsigned long total_load; /* Total load of all groups in sd */
8068 unsigned long total_capacity; /* Total capacity of all groups in sd */
8069 unsigned long avg_load; /* Average load across all groups in sd */
8070 unsigned int prefer_sibling; /* tasks should go to sibling first */
8072 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
8073 struct sg_lb_stats local_stat; /* Statistics of the local group */
8076 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
8079 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
8080 * local_stat because update_sg_lb_stats() does a full clear/assignment.
8081 * We must however set busiest_stat::group_type and
8082 * busiest_stat::idle_cpus to the worst busiest group because
8083 * update_sd_pick_busiest() reads these before assignment.
8085 *sds = (struct sd_lb_stats){
8089 .total_capacity = 0UL,
8091 .idle_cpus = UINT_MAX,
8092 .group_type = group_has_spare,
8097 static unsigned long scale_rt_capacity(int cpu)
8099 struct rq *rq = cpu_rq(cpu);
8100 unsigned long max = arch_scale_cpu_capacity(cpu);
8101 unsigned long used, free;
8104 irq = cpu_util_irq(rq);
8106 if (unlikely(irq >= max))
8110 * avg_rt.util_avg and avg_dl.util_avg track binary signals
8111 * (running and not running) with weights 0 and 1024 respectively.
8112 * avg_thermal.load_avg tracks thermal pressure and the weighted
8113 * average uses the actual delta max capacity(load).
8115 used = READ_ONCE(rq->avg_rt.util_avg);
8116 used += READ_ONCE(rq->avg_dl.util_avg);
8117 used += thermal_load_avg(rq);
8119 if (unlikely(used >= max))
8124 return scale_irq_capacity(free, irq, max);
8127 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
8129 unsigned long capacity = scale_rt_capacity(cpu);
8130 struct sched_group *sdg = sd->groups;
8132 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
8137 cpu_rq(cpu)->cpu_capacity = capacity;
8138 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
8140 sdg->sgc->capacity = capacity;
8141 sdg->sgc->min_capacity = capacity;
8142 sdg->sgc->max_capacity = capacity;
8145 void update_group_capacity(struct sched_domain *sd, int cpu)
8147 struct sched_domain *child = sd->child;
8148 struct sched_group *group, *sdg = sd->groups;
8149 unsigned long capacity, min_capacity, max_capacity;
8150 unsigned long interval;
8152 interval = msecs_to_jiffies(sd->balance_interval);
8153 interval = clamp(interval, 1UL, max_load_balance_interval);
8154 sdg->sgc->next_update = jiffies + interval;
8157 update_cpu_capacity(sd, cpu);
8162 min_capacity = ULONG_MAX;
8165 if (child->flags & SD_OVERLAP) {
8167 * SD_OVERLAP domains cannot assume that child groups
8168 * span the current group.
8171 for_each_cpu(cpu, sched_group_span(sdg)) {
8172 unsigned long cpu_cap = capacity_of(cpu);
8174 capacity += cpu_cap;
8175 min_capacity = min(cpu_cap, min_capacity);
8176 max_capacity = max(cpu_cap, max_capacity);
8180 * !SD_OVERLAP domains can assume that child groups
8181 * span the current group.
8184 group = child->groups;
8186 struct sched_group_capacity *sgc = group->sgc;
8188 capacity += sgc->capacity;
8189 min_capacity = min(sgc->min_capacity, min_capacity);
8190 max_capacity = max(sgc->max_capacity, max_capacity);
8191 group = group->next;
8192 } while (group != child->groups);
8195 sdg->sgc->capacity = capacity;
8196 sdg->sgc->min_capacity = min_capacity;
8197 sdg->sgc->max_capacity = max_capacity;
8201 * Check whether the capacity of the rq has been noticeably reduced by side
8202 * activity. The imbalance_pct is used for the threshold.
8203 * Return true is the capacity is reduced
8206 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
8208 return ((rq->cpu_capacity * sd->imbalance_pct) <
8209 (rq->cpu_capacity_orig * 100));
8213 * Check whether a rq has a misfit task and if it looks like we can actually
8214 * help that task: we can migrate the task to a CPU of higher capacity, or
8215 * the task's current CPU is heavily pressured.
8217 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
8219 return rq->misfit_task_load &&
8220 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
8221 check_cpu_capacity(rq, sd));
8225 * Group imbalance indicates (and tries to solve) the problem where balancing
8226 * groups is inadequate due to ->cpus_ptr constraints.
8228 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
8229 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
8232 * { 0 1 2 3 } { 4 5 6 7 }
8235 * If we were to balance group-wise we'd place two tasks in the first group and
8236 * two tasks in the second group. Clearly this is undesired as it will overload
8237 * cpu 3 and leave one of the CPUs in the second group unused.
8239 * The current solution to this issue is detecting the skew in the first group
8240 * by noticing the lower domain failed to reach balance and had difficulty
8241 * moving tasks due to affinity constraints.
8243 * When this is so detected; this group becomes a candidate for busiest; see
8244 * update_sd_pick_busiest(). And calculate_imbalance() and
8245 * find_busiest_group() avoid some of the usual balance conditions to allow it
8246 * to create an effective group imbalance.
8248 * This is a somewhat tricky proposition since the next run might not find the
8249 * group imbalance and decide the groups need to be balanced again. A most
8250 * subtle and fragile situation.
8253 static inline int sg_imbalanced(struct sched_group *group)
8255 return group->sgc->imbalance;
8259 * group_has_capacity returns true if the group has spare capacity that could
8260 * be used by some tasks.
8261 * We consider that a group has spare capacity if the * number of task is
8262 * smaller than the number of CPUs or if the utilization is lower than the
8263 * available capacity for CFS tasks.
8264 * For the latter, we use a threshold to stabilize the state, to take into
8265 * account the variance of the tasks' load and to return true if the available
8266 * capacity in meaningful for the load balancer.
8267 * As an example, an available capacity of 1% can appear but it doesn't make
8268 * any benefit for the load balance.
8271 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8273 if (sgs->sum_nr_running < sgs->group_weight)
8276 if ((sgs->group_capacity * imbalance_pct) <
8277 (sgs->group_runnable * 100))
8280 if ((sgs->group_capacity * 100) >
8281 (sgs->group_util * imbalance_pct))
8288 * group_is_overloaded returns true if the group has more tasks than it can
8290 * group_is_overloaded is not equals to !group_has_capacity because a group
8291 * with the exact right number of tasks, has no more spare capacity but is not
8292 * overloaded so both group_has_capacity and group_is_overloaded return
8296 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8298 if (sgs->sum_nr_running <= sgs->group_weight)
8301 if ((sgs->group_capacity * 100) <
8302 (sgs->group_util * imbalance_pct))
8305 if ((sgs->group_capacity * imbalance_pct) <
8306 (sgs->group_runnable * 100))
8313 * group_smaller_min_cpu_capacity: Returns true if sched_group sg has smaller
8314 * per-CPU capacity than sched_group ref.
8317 group_smaller_min_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8319 return fits_capacity(sg->sgc->min_capacity, ref->sgc->min_capacity);
8323 * group_smaller_max_cpu_capacity: Returns true if sched_group sg has smaller
8324 * per-CPU capacity_orig than sched_group ref.
8327 group_smaller_max_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8329 return fits_capacity(sg->sgc->max_capacity, ref->sgc->max_capacity);
8333 group_type group_classify(unsigned int imbalance_pct,
8334 struct sched_group *group,
8335 struct sg_lb_stats *sgs)
8337 if (group_is_overloaded(imbalance_pct, sgs))
8338 return group_overloaded;
8340 if (sg_imbalanced(group))
8341 return group_imbalanced;
8343 if (sgs->group_asym_packing)
8344 return group_asym_packing;
8346 if (sgs->group_misfit_task_load)
8347 return group_misfit_task;
8349 if (!group_has_capacity(imbalance_pct, sgs))
8350 return group_fully_busy;
8352 return group_has_spare;
8355 static bool update_nohz_stats(struct rq *rq, bool force)
8357 #ifdef CONFIG_NO_HZ_COMMON
8358 unsigned int cpu = rq->cpu;
8360 if (!rq->has_blocked_load)
8363 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
8366 if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
8369 update_blocked_averages(cpu);
8371 return rq->has_blocked_load;
8378 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
8379 * @env: The load balancing environment.
8380 * @group: sched_group whose statistics are to be updated.
8381 * @sgs: variable to hold the statistics for this group.
8382 * @sg_status: Holds flag indicating the status of the sched_group
8384 static inline void update_sg_lb_stats(struct lb_env *env,
8385 struct sched_group *group,
8386 struct sg_lb_stats *sgs,
8389 int i, nr_running, local_group;
8391 memset(sgs, 0, sizeof(*sgs));
8393 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(group));
8395 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
8396 struct rq *rq = cpu_rq(i);
8398 sgs->group_load += cpu_load(rq);
8399 sgs->group_util += cpu_util(i);
8400 sgs->group_runnable += cpu_runnable(rq);
8401 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
8403 nr_running = rq->nr_running;
8404 sgs->sum_nr_running += nr_running;
8407 *sg_status |= SG_OVERLOAD;
8409 if (cpu_overutilized(i))
8410 *sg_status |= SG_OVERUTILIZED;
8412 #ifdef CONFIG_NUMA_BALANCING
8413 sgs->nr_numa_running += rq->nr_numa_running;
8414 sgs->nr_preferred_running += rq->nr_preferred_running;
8417 * No need to call idle_cpu() if nr_running is not 0
8419 if (!nr_running && idle_cpu(i)) {
8421 /* Idle cpu can't have misfit task */
8428 /* Check for a misfit task on the cpu */
8429 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
8430 sgs->group_misfit_task_load < rq->misfit_task_load) {
8431 sgs->group_misfit_task_load = rq->misfit_task_load;
8432 *sg_status |= SG_OVERLOAD;
8436 /* Check if dst CPU is idle and preferred to this group */
8437 if (env->sd->flags & SD_ASYM_PACKING &&
8438 env->idle != CPU_NOT_IDLE &&
8439 sgs->sum_h_nr_running &&
8440 sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu)) {
8441 sgs->group_asym_packing = 1;
8444 sgs->group_capacity = group->sgc->capacity;
8446 sgs->group_weight = group->group_weight;
8448 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
8450 /* Computing avg_load makes sense only when group is overloaded */
8451 if (sgs->group_type == group_overloaded)
8452 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8453 sgs->group_capacity;
8457 * update_sd_pick_busiest - return 1 on busiest group
8458 * @env: The load balancing environment.
8459 * @sds: sched_domain statistics
8460 * @sg: sched_group candidate to be checked for being the busiest
8461 * @sgs: sched_group statistics
8463 * Determine if @sg is a busier group than the previously selected
8466 * Return: %true if @sg is a busier group than the previously selected
8467 * busiest group. %false otherwise.
8469 static bool update_sd_pick_busiest(struct lb_env *env,
8470 struct sd_lb_stats *sds,
8471 struct sched_group *sg,
8472 struct sg_lb_stats *sgs)
8474 struct sg_lb_stats *busiest = &sds->busiest_stat;
8476 /* Make sure that there is at least one task to pull */
8477 if (!sgs->sum_h_nr_running)
8481 * Don't try to pull misfit tasks we can't help.
8482 * We can use max_capacity here as reduction in capacity on some
8483 * CPUs in the group should either be possible to resolve
8484 * internally or be covered by avg_load imbalance (eventually).
8486 if (sgs->group_type == group_misfit_task &&
8487 (!group_smaller_max_cpu_capacity(sg, sds->local) ||
8488 sds->local_stat.group_type != group_has_spare))
8491 if (sgs->group_type > busiest->group_type)
8494 if (sgs->group_type < busiest->group_type)
8498 * The candidate and the current busiest group are the same type of
8499 * group. Let check which one is the busiest according to the type.
8502 switch (sgs->group_type) {
8503 case group_overloaded:
8504 /* Select the overloaded group with highest avg_load. */
8505 if (sgs->avg_load <= busiest->avg_load)
8509 case group_imbalanced:
8511 * Select the 1st imbalanced group as we don't have any way to
8512 * choose one more than another.
8516 case group_asym_packing:
8517 /* Prefer to move from lowest priority CPU's work */
8518 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
8522 case group_misfit_task:
8524 * If we have more than one misfit sg go with the biggest
8527 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
8531 case group_fully_busy:
8533 * Select the fully busy group with highest avg_load. In
8534 * theory, there is no need to pull task from such kind of
8535 * group because tasks have all compute capacity that they need
8536 * but we can still improve the overall throughput by reducing
8537 * contention when accessing shared HW resources.
8539 * XXX for now avg_load is not computed and always 0 so we
8540 * select the 1st one.
8542 if (sgs->avg_load <= busiest->avg_load)
8546 case group_has_spare:
8548 * Select not overloaded group with lowest number of idle cpus
8549 * and highest number of running tasks. We could also compare
8550 * the spare capacity which is more stable but it can end up
8551 * that the group has less spare capacity but finally more idle
8552 * CPUs which means less opportunity to pull tasks.
8554 if (sgs->idle_cpus > busiest->idle_cpus)
8556 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
8557 (sgs->sum_nr_running <= busiest->sum_nr_running))
8564 * Candidate sg has no more than one task per CPU and has higher
8565 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
8566 * throughput. Maximize throughput, power/energy consequences are not
8569 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
8570 (sgs->group_type <= group_fully_busy) &&
8571 (group_smaller_min_cpu_capacity(sds->local, sg)))
8577 #ifdef CONFIG_NUMA_BALANCING
8578 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8580 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
8582 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
8587 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8589 if (rq->nr_running > rq->nr_numa_running)
8591 if (rq->nr_running > rq->nr_preferred_running)
8596 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8601 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8605 #endif /* CONFIG_NUMA_BALANCING */
8611 * task_running_on_cpu - return 1 if @p is running on @cpu.
8614 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
8616 /* Task has no contribution or is new */
8617 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8620 if (task_on_rq_queued(p))
8627 * idle_cpu_without - would a given CPU be idle without p ?
8628 * @cpu: the processor on which idleness is tested.
8629 * @p: task which should be ignored.
8631 * Return: 1 if the CPU would be idle. 0 otherwise.
8633 static int idle_cpu_without(int cpu, struct task_struct *p)
8635 struct rq *rq = cpu_rq(cpu);
8637 if (rq->curr != rq->idle && rq->curr != p)
8641 * rq->nr_running can't be used but an updated version without the
8642 * impact of p on cpu must be used instead. The updated nr_running
8643 * be computed and tested before calling idle_cpu_without().
8647 if (rq->ttwu_pending)
8655 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
8656 * @sd: The sched_domain level to look for idlest group.
8657 * @group: sched_group whose statistics are to be updated.
8658 * @sgs: variable to hold the statistics for this group.
8659 * @p: The task for which we look for the idlest group/CPU.
8661 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
8662 struct sched_group *group,
8663 struct sg_lb_stats *sgs,
8664 struct task_struct *p)
8668 memset(sgs, 0, sizeof(*sgs));
8670 for_each_cpu(i, sched_group_span(group)) {
8671 struct rq *rq = cpu_rq(i);
8674 sgs->group_load += cpu_load_without(rq, p);
8675 sgs->group_util += cpu_util_without(i, p);
8676 sgs->group_runnable += cpu_runnable_without(rq, p);
8677 local = task_running_on_cpu(i, p);
8678 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
8680 nr_running = rq->nr_running - local;
8681 sgs->sum_nr_running += nr_running;
8684 * No need to call idle_cpu_without() if nr_running is not 0
8686 if (!nr_running && idle_cpu_without(i, p))
8691 /* Check if task fits in the group */
8692 if (sd->flags & SD_ASYM_CPUCAPACITY &&
8693 !task_fits_capacity(p, group->sgc->max_capacity)) {
8694 sgs->group_misfit_task_load = 1;
8697 sgs->group_capacity = group->sgc->capacity;
8699 sgs->group_weight = group->group_weight;
8701 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
8704 * Computing avg_load makes sense only when group is fully busy or
8707 if (sgs->group_type == group_fully_busy ||
8708 sgs->group_type == group_overloaded)
8709 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8710 sgs->group_capacity;
8713 static bool update_pick_idlest(struct sched_group *idlest,
8714 struct sg_lb_stats *idlest_sgs,
8715 struct sched_group *group,
8716 struct sg_lb_stats *sgs)
8718 if (sgs->group_type < idlest_sgs->group_type)
8721 if (sgs->group_type > idlest_sgs->group_type)
8725 * The candidate and the current idlest group are the same type of
8726 * group. Let check which one is the idlest according to the type.
8729 switch (sgs->group_type) {
8730 case group_overloaded:
8731 case group_fully_busy:
8732 /* Select the group with lowest avg_load. */
8733 if (idlest_sgs->avg_load <= sgs->avg_load)
8737 case group_imbalanced:
8738 case group_asym_packing:
8739 /* Those types are not used in the slow wakeup path */
8742 case group_misfit_task:
8743 /* Select group with the highest max capacity */
8744 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
8748 case group_has_spare:
8749 /* Select group with most idle CPUs */
8750 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
8753 /* Select group with lowest group_util */
8754 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
8755 idlest_sgs->group_util <= sgs->group_util)
8765 * Allow a NUMA imbalance if busy CPUs is less than 25% of the domain.
8766 * This is an approximation as the number of running tasks may not be
8767 * related to the number of busy CPUs due to sched_setaffinity.
8769 static inline bool allow_numa_imbalance(int dst_running, int dst_weight)
8771 return (dst_running < (dst_weight >> 2));
8775 * find_idlest_group() finds and returns the least busy CPU group within the
8778 * Assumes p is allowed on at least one CPU in sd.
8780 static struct sched_group *
8781 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
8783 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
8784 struct sg_lb_stats local_sgs, tmp_sgs;
8785 struct sg_lb_stats *sgs;
8786 unsigned long imbalance;
8787 struct sg_lb_stats idlest_sgs = {
8788 .avg_load = UINT_MAX,
8789 .group_type = group_overloaded,
8795 /* Skip over this group if it has no CPUs allowed */
8796 if (!cpumask_intersects(sched_group_span(group),
8800 local_group = cpumask_test_cpu(this_cpu,
8801 sched_group_span(group));
8810 update_sg_wakeup_stats(sd, group, sgs, p);
8812 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
8817 } while (group = group->next, group != sd->groups);
8820 /* There is no idlest group to push tasks to */
8824 /* The local group has been skipped because of CPU affinity */
8829 * If the local group is idler than the selected idlest group
8830 * don't try and push the task.
8832 if (local_sgs.group_type < idlest_sgs.group_type)
8836 * If the local group is busier than the selected idlest group
8837 * try and push the task.
8839 if (local_sgs.group_type > idlest_sgs.group_type)
8842 switch (local_sgs.group_type) {
8843 case group_overloaded:
8844 case group_fully_busy:
8846 /* Calculate allowed imbalance based on load */
8847 imbalance = scale_load_down(NICE_0_LOAD) *
8848 (sd->imbalance_pct-100) / 100;
8851 * When comparing groups across NUMA domains, it's possible for
8852 * the local domain to be very lightly loaded relative to the
8853 * remote domains but "imbalance" skews the comparison making
8854 * remote CPUs look much more favourable. When considering
8855 * cross-domain, add imbalance to the load on the remote node
8856 * and consider staying local.
8859 if ((sd->flags & SD_NUMA) &&
8860 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
8864 * If the local group is less loaded than the selected
8865 * idlest group don't try and push any tasks.
8867 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
8870 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
8874 case group_imbalanced:
8875 case group_asym_packing:
8876 /* Those type are not used in the slow wakeup path */
8879 case group_misfit_task:
8880 /* Select group with the highest max capacity */
8881 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
8885 case group_has_spare:
8886 if (sd->flags & SD_NUMA) {
8887 #ifdef CONFIG_NUMA_BALANCING
8890 * If there is spare capacity at NUMA, try to select
8891 * the preferred node
8893 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
8896 idlest_cpu = cpumask_first(sched_group_span(idlest));
8897 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
8901 * Otherwise, keep the task on this node to stay close
8902 * its wakeup source and improve locality. If there is
8903 * a real need of migration, periodic load balance will
8906 if (allow_numa_imbalance(local_sgs.sum_nr_running, sd->span_weight))
8911 * Select group with highest number of idle CPUs. We could also
8912 * compare the utilization which is more stable but it can end
8913 * up that the group has less spare capacity but finally more
8914 * idle CPUs which means more opportunity to run task.
8916 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
8925 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
8926 * @env: The load balancing environment.
8927 * @sds: variable to hold the statistics for this sched_domain.
8930 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
8932 struct sched_domain *child = env->sd->child;
8933 struct sched_group *sg = env->sd->groups;
8934 struct sg_lb_stats *local = &sds->local_stat;
8935 struct sg_lb_stats tmp_sgs;
8939 struct sg_lb_stats *sgs = &tmp_sgs;
8942 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
8947 if (env->idle != CPU_NEWLY_IDLE ||
8948 time_after_eq(jiffies, sg->sgc->next_update))
8949 update_group_capacity(env->sd, env->dst_cpu);
8952 update_sg_lb_stats(env, sg, sgs, &sg_status);
8958 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
8960 sds->busiest_stat = *sgs;
8964 /* Now, start updating sd_lb_stats */
8965 sds->total_load += sgs->group_load;
8966 sds->total_capacity += sgs->group_capacity;
8969 } while (sg != env->sd->groups);
8971 /* Tag domain that child domain prefers tasks go to siblings first */
8972 sds->prefer_sibling = child && child->flags & SD_PREFER_SIBLING;
8975 if (env->sd->flags & SD_NUMA)
8976 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
8978 if (!env->sd->parent) {
8979 struct root_domain *rd = env->dst_rq->rd;
8981 /* update overload indicator if we are at root domain */
8982 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
8984 /* Update over-utilization (tipping point, U >= 0) indicator */
8985 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
8986 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
8987 } else if (sg_status & SG_OVERUTILIZED) {
8988 struct root_domain *rd = env->dst_rq->rd;
8990 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
8991 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
8995 #define NUMA_IMBALANCE_MIN 2
8997 static inline long adjust_numa_imbalance(int imbalance,
8998 int dst_running, int dst_weight)
9000 if (!allow_numa_imbalance(dst_running, dst_weight))
9004 * Allow a small imbalance based on a simple pair of communicating
9005 * tasks that remain local when the destination is lightly loaded.
9007 if (imbalance <= NUMA_IMBALANCE_MIN)
9014 * calculate_imbalance - Calculate the amount of imbalance present within the
9015 * groups of a given sched_domain during load balance.
9016 * @env: load balance environment
9017 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
9019 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
9021 struct sg_lb_stats *local, *busiest;
9023 local = &sds->local_stat;
9024 busiest = &sds->busiest_stat;
9026 if (busiest->group_type == group_misfit_task) {
9027 /* Set imbalance to allow misfit tasks to be balanced. */
9028 env->migration_type = migrate_misfit;
9033 if (busiest->group_type == group_asym_packing) {
9035 * In case of asym capacity, we will try to migrate all load to
9036 * the preferred CPU.
9038 env->migration_type = migrate_task;
9039 env->imbalance = busiest->sum_h_nr_running;
9043 if (busiest->group_type == group_imbalanced) {
9045 * In the group_imb case we cannot rely on group-wide averages
9046 * to ensure CPU-load equilibrium, try to move any task to fix
9047 * the imbalance. The next load balance will take care of
9048 * balancing back the system.
9050 env->migration_type = migrate_task;
9056 * Try to use spare capacity of local group without overloading it or
9059 if (local->group_type == group_has_spare) {
9060 if ((busiest->group_type > group_fully_busy) &&
9061 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
9063 * If busiest is overloaded, try to fill spare
9064 * capacity. This might end up creating spare capacity
9065 * in busiest or busiest still being overloaded but
9066 * there is no simple way to directly compute the
9067 * amount of load to migrate in order to balance the
9070 env->migration_type = migrate_util;
9071 env->imbalance = max(local->group_capacity, local->group_util) -
9075 * In some cases, the group's utilization is max or even
9076 * higher than capacity because of migrations but the
9077 * local CPU is (newly) idle. There is at least one
9078 * waiting task in this overloaded busiest group. Let's
9081 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
9082 env->migration_type = migrate_task;
9089 if (busiest->group_weight == 1 || sds->prefer_sibling) {
9090 unsigned int nr_diff = busiest->sum_nr_running;
9092 * When prefer sibling, evenly spread running tasks on
9095 env->migration_type = migrate_task;
9096 lsub_positive(&nr_diff, local->sum_nr_running);
9097 env->imbalance = nr_diff >> 1;
9101 * If there is no overload, we just want to even the number of
9104 env->migration_type = migrate_task;
9105 env->imbalance = max_t(long, 0, (local->idle_cpus -
9106 busiest->idle_cpus) >> 1);
9109 /* Consider allowing a small imbalance between NUMA groups */
9110 if (env->sd->flags & SD_NUMA) {
9111 env->imbalance = adjust_numa_imbalance(env->imbalance,
9112 busiest->sum_nr_running, busiest->group_weight);
9119 * Local is fully busy but has to take more load to relieve the
9122 if (local->group_type < group_overloaded) {
9124 * Local will become overloaded so the avg_load metrics are
9128 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
9129 local->group_capacity;
9131 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
9132 sds->total_capacity;
9134 * If the local group is more loaded than the selected
9135 * busiest group don't try to pull any tasks.
9137 if (local->avg_load >= busiest->avg_load) {
9144 * Both group are or will become overloaded and we're trying to get all
9145 * the CPUs to the average_load, so we don't want to push ourselves
9146 * above the average load, nor do we wish to reduce the max loaded CPU
9147 * below the average load. At the same time, we also don't want to
9148 * reduce the group load below the group capacity. Thus we look for
9149 * the minimum possible imbalance.
9151 env->migration_type = migrate_load;
9152 env->imbalance = min(
9153 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
9154 (sds->avg_load - local->avg_load) * local->group_capacity
9155 ) / SCHED_CAPACITY_SCALE;
9158 /******* find_busiest_group() helpers end here *********************/
9161 * Decision matrix according to the local and busiest group type:
9163 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
9164 * has_spare nr_idle balanced N/A N/A balanced balanced
9165 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
9166 * misfit_task force N/A N/A N/A force force
9167 * asym_packing force force N/A N/A force force
9168 * imbalanced force force N/A N/A force force
9169 * overloaded force force N/A N/A force avg_load
9171 * N/A : Not Applicable because already filtered while updating
9173 * balanced : The system is balanced for these 2 groups.
9174 * force : Calculate the imbalance as load migration is probably needed.
9175 * avg_load : Only if imbalance is significant enough.
9176 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
9177 * different in groups.
9181 * find_busiest_group - Returns the busiest group within the sched_domain
9182 * if there is an imbalance.
9184 * Also calculates the amount of runnable load which should be moved
9185 * to restore balance.
9187 * @env: The load balancing environment.
9189 * Return: - The busiest group if imbalance exists.
9191 static struct sched_group *find_busiest_group(struct lb_env *env)
9193 struct sg_lb_stats *local, *busiest;
9194 struct sd_lb_stats sds;
9196 init_sd_lb_stats(&sds);
9199 * Compute the various statistics relevant for load balancing at
9202 update_sd_lb_stats(env, &sds);
9204 if (sched_energy_enabled()) {
9205 struct root_domain *rd = env->dst_rq->rd;
9207 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
9211 local = &sds.local_stat;
9212 busiest = &sds.busiest_stat;
9214 /* There is no busy sibling group to pull tasks from */
9218 /* Misfit tasks should be dealt with regardless of the avg load */
9219 if (busiest->group_type == group_misfit_task)
9222 /* ASYM feature bypasses nice load balance check */
9223 if (busiest->group_type == group_asym_packing)
9227 * If the busiest group is imbalanced the below checks don't
9228 * work because they assume all things are equal, which typically
9229 * isn't true due to cpus_ptr constraints and the like.
9231 if (busiest->group_type == group_imbalanced)
9235 * If the local group is busier than the selected busiest group
9236 * don't try and pull any tasks.
9238 if (local->group_type > busiest->group_type)
9242 * When groups are overloaded, use the avg_load to ensure fairness
9245 if (local->group_type == group_overloaded) {
9247 * If the local group is more loaded than the selected
9248 * busiest group don't try to pull any tasks.
9250 if (local->avg_load >= busiest->avg_load)
9253 /* XXX broken for overlapping NUMA groups */
9254 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
9258 * Don't pull any tasks if this group is already above the
9259 * domain average load.
9261 if (local->avg_load >= sds.avg_load)
9265 * If the busiest group is more loaded, use imbalance_pct to be
9268 if (100 * busiest->avg_load <=
9269 env->sd->imbalance_pct * local->avg_load)
9273 /* Try to move all excess tasks to child's sibling domain */
9274 if (sds.prefer_sibling && local->group_type == group_has_spare &&
9275 busiest->sum_nr_running > local->sum_nr_running + 1)
9278 if (busiest->group_type != group_overloaded) {
9279 if (env->idle == CPU_NOT_IDLE)
9281 * If the busiest group is not overloaded (and as a
9282 * result the local one too) but this CPU is already
9283 * busy, let another idle CPU try to pull task.
9287 if (busiest->group_weight > 1 &&
9288 local->idle_cpus <= (busiest->idle_cpus + 1))
9290 * If the busiest group is not overloaded
9291 * and there is no imbalance between this and busiest
9292 * group wrt idle CPUs, it is balanced. The imbalance
9293 * becomes significant if the diff is greater than 1
9294 * otherwise we might end up to just move the imbalance
9295 * on another group. Of course this applies only if
9296 * there is more than 1 CPU per group.
9300 if (busiest->sum_h_nr_running == 1)
9302 * busiest doesn't have any tasks waiting to run
9308 /* Looks like there is an imbalance. Compute it */
9309 calculate_imbalance(env, &sds);
9310 return env->imbalance ? sds.busiest : NULL;
9318 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
9320 static struct rq *find_busiest_queue(struct lb_env *env,
9321 struct sched_group *group)
9323 struct rq *busiest = NULL, *rq;
9324 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
9325 unsigned int busiest_nr = 0;
9328 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9329 unsigned long capacity, load, util;
9330 unsigned int nr_running;
9334 rt = fbq_classify_rq(rq);
9337 * We classify groups/runqueues into three groups:
9338 * - regular: there are !numa tasks
9339 * - remote: there are numa tasks that run on the 'wrong' node
9340 * - all: there is no distinction
9342 * In order to avoid migrating ideally placed numa tasks,
9343 * ignore those when there's better options.
9345 * If we ignore the actual busiest queue to migrate another
9346 * task, the next balance pass can still reduce the busiest
9347 * queue by moving tasks around inside the node.
9349 * If we cannot move enough load due to this classification
9350 * the next pass will adjust the group classification and
9351 * allow migration of more tasks.
9353 * Both cases only affect the total convergence complexity.
9355 if (rt > env->fbq_type)
9358 nr_running = rq->cfs.h_nr_running;
9362 capacity = capacity_of(i);
9365 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
9366 * eventually lead to active_balancing high->low capacity.
9367 * Higher per-CPU capacity is considered better than balancing
9370 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
9371 capacity_of(env->dst_cpu) < capacity &&
9375 switch (env->migration_type) {
9378 * When comparing with load imbalance, use cpu_load()
9379 * which is not scaled with the CPU capacity.
9381 load = cpu_load(rq);
9383 if (nr_running == 1 && load > env->imbalance &&
9384 !check_cpu_capacity(rq, env->sd))
9388 * For the load comparisons with the other CPUs,
9389 * consider the cpu_load() scaled with the CPU
9390 * capacity, so that the load can be moved away
9391 * from the CPU that is potentially running at a
9394 * Thus we're looking for max(load_i / capacity_i),
9395 * crosswise multiplication to rid ourselves of the
9396 * division works out to:
9397 * load_i * capacity_j > load_j * capacity_i;
9398 * where j is our previous maximum.
9400 if (load * busiest_capacity > busiest_load * capacity) {
9401 busiest_load = load;
9402 busiest_capacity = capacity;
9408 util = cpu_util(cpu_of(rq));
9411 * Don't try to pull utilization from a CPU with one
9412 * running task. Whatever its utilization, we will fail
9415 if (nr_running <= 1)
9418 if (busiest_util < util) {
9419 busiest_util = util;
9425 if (busiest_nr < nr_running) {
9426 busiest_nr = nr_running;
9431 case migrate_misfit:
9433 * For ASYM_CPUCAPACITY domains with misfit tasks we
9434 * simply seek the "biggest" misfit task.
9436 if (rq->misfit_task_load > busiest_load) {
9437 busiest_load = rq->misfit_task_load;
9450 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
9451 * so long as it is large enough.
9453 #define MAX_PINNED_INTERVAL 512
9456 asym_active_balance(struct lb_env *env)
9459 * ASYM_PACKING needs to force migrate tasks from busy but
9460 * lower priority CPUs in order to pack all tasks in the
9461 * highest priority CPUs.
9463 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
9464 sched_asym_prefer(env->dst_cpu, env->src_cpu);
9468 imbalanced_active_balance(struct lb_env *env)
9470 struct sched_domain *sd = env->sd;
9473 * The imbalanced case includes the case of pinned tasks preventing a fair
9474 * distribution of the load on the system but also the even distribution of the
9475 * threads on a system with spare capacity
9477 if ((env->migration_type == migrate_task) &&
9478 (sd->nr_balance_failed > sd->cache_nice_tries+2))
9484 static int need_active_balance(struct lb_env *env)
9486 struct sched_domain *sd = env->sd;
9488 if (asym_active_balance(env))
9491 if (imbalanced_active_balance(env))
9495 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
9496 * It's worth migrating the task if the src_cpu's capacity is reduced
9497 * because of other sched_class or IRQs if more capacity stays
9498 * available on dst_cpu.
9500 if ((env->idle != CPU_NOT_IDLE) &&
9501 (env->src_rq->cfs.h_nr_running == 1)) {
9502 if ((check_cpu_capacity(env->src_rq, sd)) &&
9503 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
9507 if (env->migration_type == migrate_misfit)
9513 static int active_load_balance_cpu_stop(void *data);
9515 static int should_we_balance(struct lb_env *env)
9517 struct sched_group *sg = env->sd->groups;
9521 * Ensure the balancing environment is consistent; can happen
9522 * when the softirq triggers 'during' hotplug.
9524 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
9528 * In the newly idle case, we will allow all the CPUs
9529 * to do the newly idle load balance.
9531 if (env->idle == CPU_NEWLY_IDLE)
9534 /* Try to find first idle CPU */
9535 for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
9539 /* Are we the first idle CPU? */
9540 return cpu == env->dst_cpu;
9543 /* Are we the first CPU of this group ? */
9544 return group_balance_cpu(sg) == env->dst_cpu;
9548 * Check this_cpu to ensure it is balanced within domain. Attempt to move
9549 * tasks if there is an imbalance.
9551 static int load_balance(int this_cpu, struct rq *this_rq,
9552 struct sched_domain *sd, enum cpu_idle_type idle,
9553 int *continue_balancing)
9555 int ld_moved, cur_ld_moved, active_balance = 0;
9556 struct sched_domain *sd_parent = sd->parent;
9557 struct sched_group *group;
9560 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
9562 struct lb_env env = {
9564 .dst_cpu = this_cpu,
9566 .dst_grpmask = sched_group_span(sd->groups),
9568 .loop_break = sched_nr_migrate_break,
9571 .tasks = LIST_HEAD_INIT(env.tasks),
9574 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
9576 schedstat_inc(sd->lb_count[idle]);
9579 if (!should_we_balance(&env)) {
9580 *continue_balancing = 0;
9584 group = find_busiest_group(&env);
9586 schedstat_inc(sd->lb_nobusyg[idle]);
9590 busiest = find_busiest_queue(&env, group);
9592 schedstat_inc(sd->lb_nobusyq[idle]);
9596 BUG_ON(busiest == env.dst_rq);
9598 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
9600 env.src_cpu = busiest->cpu;
9601 env.src_rq = busiest;
9604 /* Clear this flag as soon as we find a pullable task */
9605 env.flags |= LBF_ALL_PINNED;
9606 if (busiest->nr_running > 1) {
9608 * Attempt to move tasks. If find_busiest_group has found
9609 * an imbalance but busiest->nr_running <= 1, the group is
9610 * still unbalanced. ld_moved simply stays zero, so it is
9611 * correctly treated as an imbalance.
9613 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
9616 rq_lock_irqsave(busiest, &rf);
9617 update_rq_clock(busiest);
9620 * cur_ld_moved - load moved in current iteration
9621 * ld_moved - cumulative load moved across iterations
9623 cur_ld_moved = detach_tasks(&env);
9626 * We've detached some tasks from busiest_rq. Every
9627 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9628 * unlock busiest->lock, and we are able to be sure
9629 * that nobody can manipulate the tasks in parallel.
9630 * See task_rq_lock() family for the details.
9633 rq_unlock(busiest, &rf);
9637 ld_moved += cur_ld_moved;
9640 local_irq_restore(rf.flags);
9642 if (env.flags & LBF_NEED_BREAK) {
9643 env.flags &= ~LBF_NEED_BREAK;
9648 * Revisit (affine) tasks on src_cpu that couldn't be moved to
9649 * us and move them to an alternate dst_cpu in our sched_group
9650 * where they can run. The upper limit on how many times we
9651 * iterate on same src_cpu is dependent on number of CPUs in our
9654 * This changes load balance semantics a bit on who can move
9655 * load to a given_cpu. In addition to the given_cpu itself
9656 * (or a ilb_cpu acting on its behalf where given_cpu is
9657 * nohz-idle), we now have balance_cpu in a position to move
9658 * load to given_cpu. In rare situations, this may cause
9659 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
9660 * _independently_ and at _same_ time to move some load to
9661 * given_cpu) causing exceess load to be moved to given_cpu.
9662 * This however should not happen so much in practice and
9663 * moreover subsequent load balance cycles should correct the
9664 * excess load moved.
9666 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
9668 /* Prevent to re-select dst_cpu via env's CPUs */
9669 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
9671 env.dst_rq = cpu_rq(env.new_dst_cpu);
9672 env.dst_cpu = env.new_dst_cpu;
9673 env.flags &= ~LBF_DST_PINNED;
9675 env.loop_break = sched_nr_migrate_break;
9678 * Go back to "more_balance" rather than "redo" since we
9679 * need to continue with same src_cpu.
9685 * We failed to reach balance because of affinity.
9688 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9690 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
9691 *group_imbalance = 1;
9694 /* All tasks on this runqueue were pinned by CPU affinity */
9695 if (unlikely(env.flags & LBF_ALL_PINNED)) {
9696 __cpumask_clear_cpu(cpu_of(busiest), cpus);
9698 * Attempting to continue load balancing at the current
9699 * sched_domain level only makes sense if there are
9700 * active CPUs remaining as possible busiest CPUs to
9701 * pull load from which are not contained within the
9702 * destination group that is receiving any migrated
9705 if (!cpumask_subset(cpus, env.dst_grpmask)) {
9707 env.loop_break = sched_nr_migrate_break;
9710 goto out_all_pinned;
9715 schedstat_inc(sd->lb_failed[idle]);
9717 * Increment the failure counter only on periodic balance.
9718 * We do not want newidle balance, which can be very
9719 * frequent, pollute the failure counter causing
9720 * excessive cache_hot migrations and active balances.
9722 if (idle != CPU_NEWLY_IDLE)
9723 sd->nr_balance_failed++;
9725 if (need_active_balance(&env)) {
9726 unsigned long flags;
9728 raw_spin_lock_irqsave(&busiest->lock, flags);
9731 * Don't kick the active_load_balance_cpu_stop,
9732 * if the curr task on busiest CPU can't be
9733 * moved to this_cpu:
9735 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
9736 raw_spin_unlock_irqrestore(&busiest->lock,
9738 goto out_one_pinned;
9741 /* Record that we found at least one task that could run on this_cpu */
9742 env.flags &= ~LBF_ALL_PINNED;
9745 * ->active_balance synchronizes accesses to
9746 * ->active_balance_work. Once set, it's cleared
9747 * only after active load balance is finished.
9749 if (!busiest->active_balance) {
9750 busiest->active_balance = 1;
9751 busiest->push_cpu = this_cpu;
9754 raw_spin_unlock_irqrestore(&busiest->lock, flags);
9756 if (active_balance) {
9757 stop_one_cpu_nowait(cpu_of(busiest),
9758 active_load_balance_cpu_stop, busiest,
9759 &busiest->active_balance_work);
9762 /* We've kicked active balancing, force task migration. */
9763 sd->nr_balance_failed = sd->cache_nice_tries+1;
9766 sd->nr_balance_failed = 0;
9769 if (likely(!active_balance) || need_active_balance(&env)) {
9770 /* We were unbalanced, so reset the balancing interval */
9771 sd->balance_interval = sd->min_interval;
9778 * We reach balance although we may have faced some affinity
9779 * constraints. Clear the imbalance flag only if other tasks got
9780 * a chance to move and fix the imbalance.
9782 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
9783 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9785 if (*group_imbalance)
9786 *group_imbalance = 0;
9791 * We reach balance because all tasks are pinned at this level so
9792 * we can't migrate them. Let the imbalance flag set so parent level
9793 * can try to migrate them.
9795 schedstat_inc(sd->lb_balanced[idle]);
9797 sd->nr_balance_failed = 0;
9803 * newidle_balance() disregards balance intervals, so we could
9804 * repeatedly reach this code, which would lead to balance_interval
9805 * skyrocketting in a short amount of time. Skip the balance_interval
9806 * increase logic to avoid that.
9808 if (env.idle == CPU_NEWLY_IDLE)
9811 /* tune up the balancing interval */
9812 if ((env.flags & LBF_ALL_PINNED &&
9813 sd->balance_interval < MAX_PINNED_INTERVAL) ||
9814 sd->balance_interval < sd->max_interval)
9815 sd->balance_interval *= 2;
9820 static inline unsigned long
9821 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
9823 unsigned long interval = sd->balance_interval;
9826 interval *= sd->busy_factor;
9828 /* scale ms to jiffies */
9829 interval = msecs_to_jiffies(interval);
9832 * Reduce likelihood of busy balancing at higher domains racing with
9833 * balancing at lower domains by preventing their balancing periods
9834 * from being multiples of each other.
9839 interval = clamp(interval, 1UL, max_load_balance_interval);
9845 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
9847 unsigned long interval, next;
9849 /* used by idle balance, so cpu_busy = 0 */
9850 interval = get_sd_balance_interval(sd, 0);
9851 next = sd->last_balance + interval;
9853 if (time_after(*next_balance, next))
9854 *next_balance = next;
9858 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
9859 * running tasks off the busiest CPU onto idle CPUs. It requires at
9860 * least 1 task to be running on each physical CPU where possible, and
9861 * avoids physical / logical imbalances.
9863 static int active_load_balance_cpu_stop(void *data)
9865 struct rq *busiest_rq = data;
9866 int busiest_cpu = cpu_of(busiest_rq);
9867 int target_cpu = busiest_rq->push_cpu;
9868 struct rq *target_rq = cpu_rq(target_cpu);
9869 struct sched_domain *sd;
9870 struct task_struct *p = NULL;
9873 rq_lock_irq(busiest_rq, &rf);
9875 * Between queueing the stop-work and running it is a hole in which
9876 * CPUs can become inactive. We should not move tasks from or to
9879 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
9882 /* Make sure the requested CPU hasn't gone down in the meantime: */
9883 if (unlikely(busiest_cpu != smp_processor_id() ||
9884 !busiest_rq->active_balance))
9887 /* Is there any task to move? */
9888 if (busiest_rq->nr_running <= 1)
9892 * This condition is "impossible", if it occurs
9893 * we need to fix it. Originally reported by
9894 * Bjorn Helgaas on a 128-CPU setup.
9896 BUG_ON(busiest_rq == target_rq);
9898 /* Search for an sd spanning us and the target CPU. */
9900 for_each_domain(target_cpu, sd) {
9901 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
9906 struct lb_env env = {
9908 .dst_cpu = target_cpu,
9909 .dst_rq = target_rq,
9910 .src_cpu = busiest_rq->cpu,
9911 .src_rq = busiest_rq,
9914 * can_migrate_task() doesn't need to compute new_dst_cpu
9915 * for active balancing. Since we have CPU_IDLE, but no
9916 * @dst_grpmask we need to make that test go away with lying
9919 .flags = LBF_DST_PINNED,
9922 schedstat_inc(sd->alb_count);
9923 update_rq_clock(busiest_rq);
9925 p = detach_one_task(&env);
9927 schedstat_inc(sd->alb_pushed);
9928 /* Active balancing done, reset the failure counter. */
9929 sd->nr_balance_failed = 0;
9931 schedstat_inc(sd->alb_failed);
9936 busiest_rq->active_balance = 0;
9937 rq_unlock(busiest_rq, &rf);
9940 attach_one_task(target_rq, p);
9947 static DEFINE_SPINLOCK(balancing);
9950 * Scale the max load_balance interval with the number of CPUs in the system.
9951 * This trades load-balance latency on larger machines for less cross talk.
9953 void update_max_interval(void)
9955 max_load_balance_interval = HZ*num_online_cpus()/10;
9959 * It checks each scheduling domain to see if it is due to be balanced,
9960 * and initiates a balancing operation if so.
9962 * Balancing parameters are set up in init_sched_domains.
9964 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
9966 int continue_balancing = 1;
9968 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
9969 unsigned long interval;
9970 struct sched_domain *sd;
9971 /* Earliest time when we have to do rebalance again */
9972 unsigned long next_balance = jiffies + 60*HZ;
9973 int update_next_balance = 0;
9974 int need_serialize, need_decay = 0;
9978 for_each_domain(cpu, sd) {
9980 * Decay the newidle max times here because this is a regular
9981 * visit to all the domains. Decay ~1% per second.
9983 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
9984 sd->max_newidle_lb_cost =
9985 (sd->max_newidle_lb_cost * 253) / 256;
9986 sd->next_decay_max_lb_cost = jiffies + HZ;
9989 max_cost += sd->max_newidle_lb_cost;
9992 * Stop the load balance at this level. There is another
9993 * CPU in our sched group which is doing load balancing more
9996 if (!continue_balancing) {
10002 interval = get_sd_balance_interval(sd, busy);
10004 need_serialize = sd->flags & SD_SERIALIZE;
10005 if (need_serialize) {
10006 if (!spin_trylock(&balancing))
10010 if (time_after_eq(jiffies, sd->last_balance + interval)) {
10011 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
10013 * The LBF_DST_PINNED logic could have changed
10014 * env->dst_cpu, so we can't know our idle
10015 * state even if we migrated tasks. Update it.
10017 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
10018 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
10020 sd->last_balance = jiffies;
10021 interval = get_sd_balance_interval(sd, busy);
10023 if (need_serialize)
10024 spin_unlock(&balancing);
10026 if (time_after(next_balance, sd->last_balance + interval)) {
10027 next_balance = sd->last_balance + interval;
10028 update_next_balance = 1;
10033 * Ensure the rq-wide value also decays but keep it at a
10034 * reasonable floor to avoid funnies with rq->avg_idle.
10036 rq->max_idle_balance_cost =
10037 max((u64)sysctl_sched_migration_cost, max_cost);
10042 * next_balance will be updated only when there is a need.
10043 * When the cpu is attached to null domain for ex, it will not be
10046 if (likely(update_next_balance)) {
10047 rq->next_balance = next_balance;
10049 #ifdef CONFIG_NO_HZ_COMMON
10051 * If this CPU has been elected to perform the nohz idle
10052 * balance. Other idle CPUs have already rebalanced with
10053 * nohz_idle_balance() and nohz.next_balance has been
10054 * updated accordingly. This CPU is now running the idle load
10055 * balance for itself and we need to update the
10056 * nohz.next_balance accordingly.
10058 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
10059 nohz.next_balance = rq->next_balance;
10064 static inline int on_null_domain(struct rq *rq)
10066 return unlikely(!rcu_dereference_sched(rq->sd));
10069 #ifdef CONFIG_NO_HZ_COMMON
10071 * idle load balancing details
10072 * - When one of the busy CPUs notice that there may be an idle rebalancing
10073 * needed, they will kick the idle load balancer, which then does idle
10074 * load balancing for all the idle CPUs.
10075 * - HK_FLAG_MISC CPUs are used for this task, because HK_FLAG_SCHED not set
10079 static inline int find_new_ilb(void)
10083 for_each_cpu_and(ilb, nohz.idle_cpus_mask,
10084 housekeeping_cpumask(HK_FLAG_MISC)) {
10086 if (ilb == smp_processor_id())
10097 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
10098 * idle CPU in the HK_FLAG_MISC housekeeping set (if there is one).
10100 static void kick_ilb(unsigned int flags)
10105 * Increase nohz.next_balance only when if full ilb is triggered but
10106 * not if we only update stats.
10108 if (flags & NOHZ_BALANCE_KICK)
10109 nohz.next_balance = jiffies+1;
10111 ilb_cpu = find_new_ilb();
10113 if (ilb_cpu >= nr_cpu_ids)
10117 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
10118 * the first flag owns it; cleared by nohz_csd_func().
10120 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
10121 if (flags & NOHZ_KICK_MASK)
10125 * This way we generate an IPI on the target CPU which
10126 * is idle. And the softirq performing nohz idle load balance
10127 * will be run before returning from the IPI.
10129 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
10133 * Current decision point for kicking the idle load balancer in the presence
10134 * of idle CPUs in the system.
10136 static void nohz_balancer_kick(struct rq *rq)
10138 unsigned long now = jiffies;
10139 struct sched_domain_shared *sds;
10140 struct sched_domain *sd;
10141 int nr_busy, i, cpu = rq->cpu;
10142 unsigned int flags = 0;
10144 if (unlikely(rq->idle_balance))
10148 * We may be recently in ticked or tickless idle mode. At the first
10149 * busy tick after returning from idle, we will update the busy stats.
10151 nohz_balance_exit_idle(rq);
10154 * None are in tickless mode and hence no need for NOHZ idle load
10157 if (likely(!atomic_read(&nohz.nr_cpus)))
10160 if (READ_ONCE(nohz.has_blocked) &&
10161 time_after(now, READ_ONCE(nohz.next_blocked)))
10162 flags = NOHZ_STATS_KICK;
10164 if (time_before(now, nohz.next_balance))
10167 if (rq->nr_running >= 2) {
10168 flags = NOHZ_KICK_MASK;
10174 sd = rcu_dereference(rq->sd);
10177 * If there's a CFS task and the current CPU has reduced
10178 * capacity; kick the ILB to see if there's a better CPU to run
10181 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
10182 flags = NOHZ_KICK_MASK;
10187 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
10190 * When ASYM_PACKING; see if there's a more preferred CPU
10191 * currently idle; in which case, kick the ILB to move tasks
10194 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
10195 if (sched_asym_prefer(i, cpu)) {
10196 flags = NOHZ_KICK_MASK;
10202 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
10205 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
10206 * to run the misfit task on.
10208 if (check_misfit_status(rq, sd)) {
10209 flags = NOHZ_KICK_MASK;
10214 * For asymmetric systems, we do not want to nicely balance
10215 * cache use, instead we want to embrace asymmetry and only
10216 * ensure tasks have enough CPU capacity.
10218 * Skip the LLC logic because it's not relevant in that case.
10223 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
10226 * If there is an imbalance between LLC domains (IOW we could
10227 * increase the overall cache use), we need some less-loaded LLC
10228 * domain to pull some load. Likewise, we may need to spread
10229 * load within the current LLC domain (e.g. packed SMT cores but
10230 * other CPUs are idle). We can't really know from here how busy
10231 * the others are - so just get a nohz balance going if it looks
10232 * like this LLC domain has tasks we could move.
10234 nr_busy = atomic_read(&sds->nr_busy_cpus);
10236 flags = NOHZ_KICK_MASK;
10247 static void set_cpu_sd_state_busy(int cpu)
10249 struct sched_domain *sd;
10252 sd = rcu_dereference(per_cpu(sd_llc, cpu));
10254 if (!sd || !sd->nohz_idle)
10258 atomic_inc(&sd->shared->nr_busy_cpus);
10263 void nohz_balance_exit_idle(struct rq *rq)
10265 SCHED_WARN_ON(rq != this_rq());
10267 if (likely(!rq->nohz_tick_stopped))
10270 rq->nohz_tick_stopped = 0;
10271 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
10272 atomic_dec(&nohz.nr_cpus);
10274 set_cpu_sd_state_busy(rq->cpu);
10277 static void set_cpu_sd_state_idle(int cpu)
10279 struct sched_domain *sd;
10282 sd = rcu_dereference(per_cpu(sd_llc, cpu));
10284 if (!sd || sd->nohz_idle)
10288 atomic_dec(&sd->shared->nr_busy_cpus);
10294 * This routine will record that the CPU is going idle with tick stopped.
10295 * This info will be used in performing idle load balancing in the future.
10297 void nohz_balance_enter_idle(int cpu)
10299 struct rq *rq = cpu_rq(cpu);
10301 SCHED_WARN_ON(cpu != smp_processor_id());
10303 /* If this CPU is going down, then nothing needs to be done: */
10304 if (!cpu_active(cpu))
10307 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
10308 if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
10312 * Can be set safely without rq->lock held
10313 * If a clear happens, it will have evaluated last additions because
10314 * rq->lock is held during the check and the clear
10316 rq->has_blocked_load = 1;
10319 * The tick is still stopped but load could have been added in the
10320 * meantime. We set the nohz.has_blocked flag to trig a check of the
10321 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
10322 * of nohz.has_blocked can only happen after checking the new load
10324 if (rq->nohz_tick_stopped)
10327 /* If we're a completely isolated CPU, we don't play: */
10328 if (on_null_domain(rq))
10331 rq->nohz_tick_stopped = 1;
10333 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
10334 atomic_inc(&nohz.nr_cpus);
10337 * Ensures that if nohz_idle_balance() fails to observe our
10338 * @idle_cpus_mask store, it must observe the @has_blocked
10341 smp_mb__after_atomic();
10343 set_cpu_sd_state_idle(cpu);
10347 * Each time a cpu enter idle, we assume that it has blocked load and
10348 * enable the periodic update of the load of idle cpus
10350 WRITE_ONCE(nohz.has_blocked, 1);
10354 * Internal function that runs load balance for all idle cpus. The load balance
10355 * can be a simple update of blocked load or a complete load balance with
10356 * tasks movement depending of flags.
10357 * The function returns false if the loop has stopped before running
10358 * through all idle CPUs.
10360 static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
10361 enum cpu_idle_type idle)
10363 /* Earliest time when we have to do rebalance again */
10364 unsigned long now = jiffies;
10365 unsigned long next_balance = now + 60*HZ;
10366 bool has_blocked_load = false;
10367 int update_next_balance = 0;
10368 int this_cpu = this_rq->cpu;
10373 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
10376 * We assume there will be no idle load after this update and clear
10377 * the has_blocked flag. If a cpu enters idle in the mean time, it will
10378 * set the has_blocked flag and trig another update of idle load.
10379 * Because a cpu that becomes idle, is added to idle_cpus_mask before
10380 * setting the flag, we are sure to not clear the state and not
10381 * check the load of an idle cpu.
10383 WRITE_ONCE(nohz.has_blocked, 0);
10386 * Ensures that if we miss the CPU, we must see the has_blocked
10387 * store from nohz_balance_enter_idle().
10391 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
10392 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
10396 * If this CPU gets work to do, stop the load balancing
10397 * work being done for other CPUs. Next load
10398 * balancing owner will pick it up.
10400 if (need_resched()) {
10401 has_blocked_load = true;
10405 rq = cpu_rq(balance_cpu);
10407 has_blocked_load |= update_nohz_stats(rq, true);
10410 * If time for next balance is due,
10413 if (time_after_eq(jiffies, rq->next_balance)) {
10414 struct rq_flags rf;
10416 rq_lock_irqsave(rq, &rf);
10417 update_rq_clock(rq);
10418 rq_unlock_irqrestore(rq, &rf);
10420 if (flags & NOHZ_BALANCE_KICK)
10421 rebalance_domains(rq, CPU_IDLE);
10424 if (time_after(next_balance, rq->next_balance)) {
10425 next_balance = rq->next_balance;
10426 update_next_balance = 1;
10431 * next_balance will be updated only when there is a need.
10432 * When the CPU is attached to null domain for ex, it will not be
10435 if (likely(update_next_balance))
10436 nohz.next_balance = next_balance;
10438 /* Newly idle CPU doesn't need an update */
10439 if (idle != CPU_NEWLY_IDLE) {
10440 update_blocked_averages(this_cpu);
10441 has_blocked_load |= this_rq->has_blocked_load;
10444 if (flags & NOHZ_BALANCE_KICK)
10445 rebalance_domains(this_rq, CPU_IDLE);
10447 WRITE_ONCE(nohz.next_blocked,
10448 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
10450 /* The full idle balance loop has been done */
10454 /* There is still blocked load, enable periodic update */
10455 if (has_blocked_load)
10456 WRITE_ONCE(nohz.has_blocked, 1);
10462 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
10463 * rebalancing for all the cpus for whom scheduler ticks are stopped.
10465 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10467 unsigned int flags = this_rq->nohz_idle_balance;
10472 this_rq->nohz_idle_balance = 0;
10474 if (idle != CPU_IDLE)
10477 _nohz_idle_balance(this_rq, flags, idle);
10482 static void nohz_newidle_balance(struct rq *this_rq)
10484 int this_cpu = this_rq->cpu;
10487 * This CPU doesn't want to be disturbed by scheduler
10490 if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
10493 /* Will wake up very soon. No time for doing anything else*/
10494 if (this_rq->avg_idle < sysctl_sched_migration_cost)
10497 /* Don't need to update blocked load of idle CPUs*/
10498 if (!READ_ONCE(nohz.has_blocked) ||
10499 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
10503 * Blocked load of idle CPUs need to be updated.
10504 * Kick an ILB to update statistics.
10506 kick_ilb(NOHZ_STATS_KICK);
10509 #else /* !CONFIG_NO_HZ_COMMON */
10510 static inline void nohz_balancer_kick(struct rq *rq) { }
10512 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10517 static inline void nohz_newidle_balance(struct rq *this_rq) { }
10518 #endif /* CONFIG_NO_HZ_COMMON */
10521 * newidle_balance is called by schedule() if this_cpu is about to become
10522 * idle. Attempts to pull tasks from other CPUs.
10525 * < 0 - we released the lock and there are !fair tasks present
10526 * 0 - failed, no new tasks
10527 * > 0 - success, new (fair) tasks present
10529 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
10531 unsigned long next_balance = jiffies + HZ;
10532 int this_cpu = this_rq->cpu;
10533 struct sched_domain *sd;
10534 int pulled_task = 0;
10537 update_misfit_status(NULL, this_rq);
10539 * We must set idle_stamp _before_ calling idle_balance(), such that we
10540 * measure the duration of idle_balance() as idle time.
10542 this_rq->idle_stamp = rq_clock(this_rq);
10545 * Do not pull tasks towards !active CPUs...
10547 if (!cpu_active(this_cpu))
10551 * This is OK, because current is on_cpu, which avoids it being picked
10552 * for load-balance and preemption/IRQs are still disabled avoiding
10553 * further scheduler activity on it and we're being very careful to
10554 * re-start the picking loop.
10556 rq_unpin_lock(this_rq, rf);
10558 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
10559 !READ_ONCE(this_rq->rd->overload)) {
10562 sd = rcu_dereference_check_sched_domain(this_rq->sd);
10564 update_next_balance(sd, &next_balance);
10570 raw_spin_unlock(&this_rq->lock);
10572 update_blocked_averages(this_cpu);
10574 for_each_domain(this_cpu, sd) {
10575 int continue_balancing = 1;
10576 u64 t0, domain_cost;
10578 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
10579 update_next_balance(sd, &next_balance);
10583 if (sd->flags & SD_BALANCE_NEWIDLE) {
10584 t0 = sched_clock_cpu(this_cpu);
10586 pulled_task = load_balance(this_cpu, this_rq,
10587 sd, CPU_NEWLY_IDLE,
10588 &continue_balancing);
10590 domain_cost = sched_clock_cpu(this_cpu) - t0;
10591 if (domain_cost > sd->max_newidle_lb_cost)
10592 sd->max_newidle_lb_cost = domain_cost;
10594 curr_cost += domain_cost;
10597 update_next_balance(sd, &next_balance);
10600 * Stop searching for tasks to pull if there are
10601 * now runnable tasks on this rq.
10603 if (pulled_task || this_rq->nr_running > 0)
10608 raw_spin_lock(&this_rq->lock);
10610 if (curr_cost > this_rq->max_idle_balance_cost)
10611 this_rq->max_idle_balance_cost = curr_cost;
10615 * While browsing the domains, we released the rq lock, a task could
10616 * have been enqueued in the meantime. Since we're not going idle,
10617 * pretend we pulled a task.
10619 if (this_rq->cfs.h_nr_running && !pulled_task)
10622 /* Move the next balance forward */
10623 if (time_after(this_rq->next_balance, next_balance))
10624 this_rq->next_balance = next_balance;
10626 /* Is there a task of a high priority class? */
10627 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
10631 this_rq->idle_stamp = 0;
10633 nohz_newidle_balance(this_rq);
10635 rq_repin_lock(this_rq, rf);
10637 return pulled_task;
10641 * run_rebalance_domains is triggered when needed from the scheduler tick.
10642 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
10644 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
10646 struct rq *this_rq = this_rq();
10647 enum cpu_idle_type idle = this_rq->idle_balance ?
10648 CPU_IDLE : CPU_NOT_IDLE;
10651 * If this CPU has a pending nohz_balance_kick, then do the
10652 * balancing on behalf of the other idle CPUs whose ticks are
10653 * stopped. Do nohz_idle_balance *before* rebalance_domains to
10654 * give the idle CPUs a chance to load balance. Else we may
10655 * load balance only within the local sched_domain hierarchy
10656 * and abort nohz_idle_balance altogether if we pull some load.
10658 if (nohz_idle_balance(this_rq, idle))
10661 /* normal load balance */
10662 update_blocked_averages(this_rq->cpu);
10663 rebalance_domains(this_rq, idle);
10667 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
10669 void trigger_load_balance(struct rq *rq)
10672 * Don't need to rebalance while attached to NULL domain or
10673 * runqueue CPU is not active
10675 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
10678 if (time_after_eq(jiffies, rq->next_balance))
10679 raise_softirq(SCHED_SOFTIRQ);
10681 nohz_balancer_kick(rq);
10684 static void rq_online_fair(struct rq *rq)
10688 update_runtime_enabled(rq);
10691 static void rq_offline_fair(struct rq *rq)
10695 /* Ensure any throttled groups are reachable by pick_next_task */
10696 unthrottle_offline_cfs_rqs(rq);
10699 #endif /* CONFIG_SMP */
10702 * scheduler tick hitting a task of our scheduling class.
10704 * NOTE: This function can be called remotely by the tick offload that
10705 * goes along full dynticks. Therefore no local assumption can be made
10706 * and everything must be accessed through the @rq and @curr passed in
10709 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
10711 struct cfs_rq *cfs_rq;
10712 struct sched_entity *se = &curr->se;
10714 for_each_sched_entity(se) {
10715 cfs_rq = cfs_rq_of(se);
10716 entity_tick(cfs_rq, se, queued);
10719 if (static_branch_unlikely(&sched_numa_balancing))
10720 task_tick_numa(rq, curr);
10722 update_misfit_status(curr, rq);
10723 update_overutilized_status(task_rq(curr));
10727 * called on fork with the child task as argument from the parent's context
10728 * - child not yet on the tasklist
10729 * - preemption disabled
10731 static void task_fork_fair(struct task_struct *p)
10733 struct cfs_rq *cfs_rq;
10734 struct sched_entity *se = &p->se, *curr;
10735 struct rq *rq = this_rq();
10736 struct rq_flags rf;
10739 update_rq_clock(rq);
10741 cfs_rq = task_cfs_rq(current);
10742 curr = cfs_rq->curr;
10744 update_curr(cfs_rq);
10745 se->vruntime = curr->vruntime;
10747 place_entity(cfs_rq, se, 1);
10749 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
10751 * Upon rescheduling, sched_class::put_prev_task() will place
10752 * 'current' within the tree based on its new key value.
10754 swap(curr->vruntime, se->vruntime);
10758 se->vruntime -= cfs_rq->min_vruntime;
10759 rq_unlock(rq, &rf);
10763 * Priority of the task has changed. Check to see if we preempt
10764 * the current task.
10767 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
10769 if (!task_on_rq_queued(p))
10772 if (rq->cfs.nr_running == 1)
10776 * Reschedule if we are currently running on this runqueue and
10777 * our priority decreased, or if we are not currently running on
10778 * this runqueue and our priority is higher than the current's
10780 if (task_current(rq, p)) {
10781 if (p->prio > oldprio)
10784 check_preempt_curr(rq, p, 0);
10787 static inline bool vruntime_normalized(struct task_struct *p)
10789 struct sched_entity *se = &p->se;
10792 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
10793 * the dequeue_entity(.flags=0) will already have normalized the
10800 * When !on_rq, vruntime of the task has usually NOT been normalized.
10801 * But there are some cases where it has already been normalized:
10803 * - A forked child which is waiting for being woken up by
10804 * wake_up_new_task().
10805 * - A task which has been woken up by try_to_wake_up() and
10806 * waiting for actually being woken up by sched_ttwu_pending().
10808 if (!se->sum_exec_runtime ||
10809 (p->state == TASK_WAKING && p->sched_remote_wakeup))
10815 #ifdef CONFIG_FAIR_GROUP_SCHED
10817 * Propagate the changes of the sched_entity across the tg tree to make it
10818 * visible to the root
10820 static void propagate_entity_cfs_rq(struct sched_entity *se)
10822 struct cfs_rq *cfs_rq;
10824 /* Start to propagate at parent */
10827 for_each_sched_entity(se) {
10828 cfs_rq = cfs_rq_of(se);
10830 if (cfs_rq_throttled(cfs_rq))
10833 update_load_avg(cfs_rq, se, UPDATE_TG);
10837 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
10840 static void detach_entity_cfs_rq(struct sched_entity *se)
10842 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10844 /* Catch up with the cfs_rq and remove our load when we leave */
10845 update_load_avg(cfs_rq, se, 0);
10846 detach_entity_load_avg(cfs_rq, se);
10847 update_tg_load_avg(cfs_rq);
10848 propagate_entity_cfs_rq(se);
10851 static void attach_entity_cfs_rq(struct sched_entity *se)
10853 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10855 #ifdef CONFIG_FAIR_GROUP_SCHED
10857 * Since the real-depth could have been changed (only FAIR
10858 * class maintain depth value), reset depth properly.
10860 se->depth = se->parent ? se->parent->depth + 1 : 0;
10863 /* Synchronize entity with its cfs_rq */
10864 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
10865 attach_entity_load_avg(cfs_rq, se);
10866 update_tg_load_avg(cfs_rq);
10867 propagate_entity_cfs_rq(se);
10870 static void detach_task_cfs_rq(struct task_struct *p)
10872 struct sched_entity *se = &p->se;
10873 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10875 if (!vruntime_normalized(p)) {
10877 * Fix up our vruntime so that the current sleep doesn't
10878 * cause 'unlimited' sleep bonus.
10880 place_entity(cfs_rq, se, 0);
10881 se->vruntime -= cfs_rq->min_vruntime;
10884 detach_entity_cfs_rq(se);
10887 static void attach_task_cfs_rq(struct task_struct *p)
10889 struct sched_entity *se = &p->se;
10890 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10892 attach_entity_cfs_rq(se);
10894 if (!vruntime_normalized(p))
10895 se->vruntime += cfs_rq->min_vruntime;
10898 static void switched_from_fair(struct rq *rq, struct task_struct *p)
10900 detach_task_cfs_rq(p);
10903 static void switched_to_fair(struct rq *rq, struct task_struct *p)
10905 attach_task_cfs_rq(p);
10907 if (task_on_rq_queued(p)) {
10909 * We were most likely switched from sched_rt, so
10910 * kick off the schedule if running, otherwise just see
10911 * if we can still preempt the current task.
10913 if (task_current(rq, p))
10916 check_preempt_curr(rq, p, 0);
10920 /* Account for a task changing its policy or group.
10922 * This routine is mostly called to set cfs_rq->curr field when a task
10923 * migrates between groups/classes.
10925 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
10927 struct sched_entity *se = &p->se;
10930 if (task_on_rq_queued(p)) {
10932 * Move the next running task to the front of the list, so our
10933 * cfs_tasks list becomes MRU one.
10935 list_move(&se->group_node, &rq->cfs_tasks);
10939 for_each_sched_entity(se) {
10940 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10942 set_next_entity(cfs_rq, se);
10943 /* ensure bandwidth has been allocated on our new cfs_rq */
10944 account_cfs_rq_runtime(cfs_rq, 0);
10948 void init_cfs_rq(struct cfs_rq *cfs_rq)
10950 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
10951 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
10952 #ifndef CONFIG_64BIT
10953 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
10956 raw_spin_lock_init(&cfs_rq->removed.lock);
10960 #ifdef CONFIG_FAIR_GROUP_SCHED
10961 static void task_set_group_fair(struct task_struct *p)
10963 struct sched_entity *se = &p->se;
10965 set_task_rq(p, task_cpu(p));
10966 se->depth = se->parent ? se->parent->depth + 1 : 0;
10969 static void task_move_group_fair(struct task_struct *p)
10971 detach_task_cfs_rq(p);
10972 set_task_rq(p, task_cpu(p));
10975 /* Tell se's cfs_rq has been changed -- migrated */
10976 p->se.avg.last_update_time = 0;
10978 attach_task_cfs_rq(p);
10981 static void task_change_group_fair(struct task_struct *p, int type)
10984 case TASK_SET_GROUP:
10985 task_set_group_fair(p);
10988 case TASK_MOVE_GROUP:
10989 task_move_group_fair(p);
10994 void free_fair_sched_group(struct task_group *tg)
10998 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
11000 for_each_possible_cpu(i) {
11002 kfree(tg->cfs_rq[i]);
11011 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11013 struct sched_entity *se;
11014 struct cfs_rq *cfs_rq;
11017 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
11020 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
11024 tg->shares = NICE_0_LOAD;
11026 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
11028 for_each_possible_cpu(i) {
11029 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
11030 GFP_KERNEL, cpu_to_node(i));
11034 se = kzalloc_node(sizeof(struct sched_entity),
11035 GFP_KERNEL, cpu_to_node(i));
11039 init_cfs_rq(cfs_rq);
11040 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
11041 init_entity_runnable_average(se);
11052 void online_fair_sched_group(struct task_group *tg)
11054 struct sched_entity *se;
11055 struct rq_flags rf;
11059 for_each_possible_cpu(i) {
11062 rq_lock_irq(rq, &rf);
11063 update_rq_clock(rq);
11064 attach_entity_cfs_rq(se);
11065 sync_throttle(tg, i);
11066 rq_unlock_irq(rq, &rf);
11070 void unregister_fair_sched_group(struct task_group *tg)
11072 unsigned long flags;
11076 for_each_possible_cpu(cpu) {
11078 remove_entity_load_avg(tg->se[cpu]);
11081 * Only empty task groups can be destroyed; so we can speculatively
11082 * check on_list without danger of it being re-added.
11084 if (!tg->cfs_rq[cpu]->on_list)
11089 raw_spin_lock_irqsave(&rq->lock, flags);
11090 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
11091 raw_spin_unlock_irqrestore(&rq->lock, flags);
11095 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
11096 struct sched_entity *se, int cpu,
11097 struct sched_entity *parent)
11099 struct rq *rq = cpu_rq(cpu);
11103 init_cfs_rq_runtime(cfs_rq);
11105 tg->cfs_rq[cpu] = cfs_rq;
11108 /* se could be NULL for root_task_group */
11113 se->cfs_rq = &rq->cfs;
11116 se->cfs_rq = parent->my_q;
11117 se->depth = parent->depth + 1;
11121 /* guarantee group entities always have weight */
11122 update_load_set(&se->load, NICE_0_LOAD);
11123 se->parent = parent;
11126 static DEFINE_MUTEX(shares_mutex);
11128 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
11133 * We can't change the weight of the root cgroup.
11138 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
11140 mutex_lock(&shares_mutex);
11141 if (tg->shares == shares)
11144 tg->shares = shares;
11145 for_each_possible_cpu(i) {
11146 struct rq *rq = cpu_rq(i);
11147 struct sched_entity *se = tg->se[i];
11148 struct rq_flags rf;
11150 /* Propagate contribution to hierarchy */
11151 rq_lock_irqsave(rq, &rf);
11152 update_rq_clock(rq);
11153 for_each_sched_entity(se) {
11154 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11155 update_cfs_group(se);
11157 rq_unlock_irqrestore(rq, &rf);
11161 mutex_unlock(&shares_mutex);
11164 #else /* CONFIG_FAIR_GROUP_SCHED */
11166 void free_fair_sched_group(struct task_group *tg) { }
11168 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11173 void online_fair_sched_group(struct task_group *tg) { }
11175 void unregister_fair_sched_group(struct task_group *tg) { }
11177 #endif /* CONFIG_FAIR_GROUP_SCHED */
11180 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
11182 struct sched_entity *se = &task->se;
11183 unsigned int rr_interval = 0;
11186 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11189 if (rq->cfs.load.weight)
11190 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
11192 return rr_interval;
11196 * All the scheduling class methods:
11198 DEFINE_SCHED_CLASS(fair) = {
11200 .enqueue_task = enqueue_task_fair,
11201 .dequeue_task = dequeue_task_fair,
11202 .yield_task = yield_task_fair,
11203 .yield_to_task = yield_to_task_fair,
11205 .check_preempt_curr = check_preempt_wakeup,
11207 .pick_next_task = __pick_next_task_fair,
11208 .put_prev_task = put_prev_task_fair,
11209 .set_next_task = set_next_task_fair,
11212 .balance = balance_fair,
11213 .select_task_rq = select_task_rq_fair,
11214 .migrate_task_rq = migrate_task_rq_fair,
11216 .rq_online = rq_online_fair,
11217 .rq_offline = rq_offline_fair,
11219 .task_dead = task_dead_fair,
11220 .set_cpus_allowed = set_cpus_allowed_common,
11223 .task_tick = task_tick_fair,
11224 .task_fork = task_fork_fair,
11226 .prio_changed = prio_changed_fair,
11227 .switched_from = switched_from_fair,
11228 .switched_to = switched_to_fair,
11230 .get_rr_interval = get_rr_interval_fair,
11232 .update_curr = update_curr_fair,
11234 #ifdef CONFIG_FAIR_GROUP_SCHED
11235 .task_change_group = task_change_group_fair,
11238 #ifdef CONFIG_UCLAMP_TASK
11239 .uclamp_enabled = 1,
11243 #ifdef CONFIG_SCHED_DEBUG
11244 void print_cfs_stats(struct seq_file *m, int cpu)
11246 struct cfs_rq *cfs_rq, *pos;
11249 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
11250 print_cfs_rq(m, cpu, cfs_rq);
11254 #ifdef CONFIG_NUMA_BALANCING
11255 void show_numa_stats(struct task_struct *p, struct seq_file *m)
11258 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
11259 struct numa_group *ng;
11262 ng = rcu_dereference(p->numa_group);
11263 for_each_online_node(node) {
11264 if (p->numa_faults) {
11265 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
11266 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
11269 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
11270 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
11272 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
11276 #endif /* CONFIG_NUMA_BALANCING */
11277 #endif /* CONFIG_SCHED_DEBUG */
11279 __init void init_sched_fair_class(void)
11282 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
11284 #ifdef CONFIG_NO_HZ_COMMON
11285 nohz.next_balance = jiffies;
11286 nohz.next_blocked = jiffies;
11287 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
11294 * Helper functions to facilitate extracting info from tracepoints.
11297 const struct sched_avg *sched_trace_cfs_rq_avg(struct cfs_rq *cfs_rq)
11300 return cfs_rq ? &cfs_rq->avg : NULL;
11305 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_avg);
11307 char *sched_trace_cfs_rq_path(struct cfs_rq *cfs_rq, char *str, int len)
11311 strlcpy(str, "(null)", len);
11316 cfs_rq_tg_path(cfs_rq, str, len);
11319 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_path);
11321 int sched_trace_cfs_rq_cpu(struct cfs_rq *cfs_rq)
11323 return cfs_rq ? cpu_of(rq_of(cfs_rq)) : -1;
11325 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_cpu);
11327 const struct sched_avg *sched_trace_rq_avg_rt(struct rq *rq)
11330 return rq ? &rq->avg_rt : NULL;
11335 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_rt);
11337 const struct sched_avg *sched_trace_rq_avg_dl(struct rq *rq)
11340 return rq ? &rq->avg_dl : NULL;
11345 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_dl);
11347 const struct sched_avg *sched_trace_rq_avg_irq(struct rq *rq)
11349 #if defined(CONFIG_SMP) && defined(CONFIG_HAVE_SCHED_AVG_IRQ)
11350 return rq ? &rq->avg_irq : NULL;
11355 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_irq);
11357 int sched_trace_rq_cpu(struct rq *rq)
11359 return rq ? cpu_of(rq) : -1;
11361 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu);
11363 int sched_trace_rq_cpu_capacity(struct rq *rq)
11369 SCHED_CAPACITY_SCALE
11373 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu_capacity);
11375 const struct cpumask *sched_trace_rd_span(struct root_domain *rd)
11378 return rd ? rd->span : NULL;
11383 EXPORT_SYMBOL_GPL(sched_trace_rd_span);
11385 int sched_trace_rq_nr_running(struct rq *rq)
11387 return rq ? rq->nr_running : -1;
11389 EXPORT_SYMBOL_GPL(sched_trace_rq_nr_running);