2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de>
9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
23 #include <linux/latencytop.h>
24 #include <linux/sched.h>
25 #include <linux/cpumask.h>
26 #include <linux/cpuidle.h>
27 #include <linux/slab.h>
28 #include <linux/profile.h>
29 #include <linux/interrupt.h>
30 #include <linux/mempolicy.h>
31 #include <linux/migrate.h>
32 #include <linux/task_work.h>
33 #include <linux/module.h>
35 #include <trace/events/sched.h>
42 * Targeted preemption latency for CPU-bound tasks:
43 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
45 * NOTE: this latency value is not the same as the concept of
46 * 'timeslice length' - timeslices in CFS are of variable length
47 * and have no persistent notion like in traditional, time-slice
48 * based scheduling concepts.
50 * (to see the precise effective timeslice length of your workload,
51 * run vmstat and monitor the context-switches (cs) field)
53 unsigned int sysctl_sched_latency = 6000000ULL;
54 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
56 unsigned int sysctl_sched_sync_hint_enable = 1;
57 unsigned int sysctl_sched_cstate_aware = 1;
59 #ifdef CONFIG_SCHED_WALT
60 unsigned int sysctl_sched_use_walt_cpu_util = 1;
61 unsigned int sysctl_sched_use_walt_task_util = 1;
62 __read_mostly unsigned int sysctl_sched_walt_cpu_high_irqload =
66 * The initial- and re-scaling of tunables is configurable
67 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
70 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
71 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
72 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
74 enum sched_tunable_scaling sysctl_sched_tunable_scaling
75 = SCHED_TUNABLESCALING_LOG;
78 * Minimal preemption granularity for CPU-bound tasks:
79 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
81 unsigned int sysctl_sched_min_granularity = 750000ULL;
82 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
85 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
87 static unsigned int sched_nr_latency = 8;
90 * After fork, child runs first. If set to 0 (default) then
91 * parent will (try to) run first.
93 unsigned int sysctl_sched_child_runs_first __read_mostly;
96 * SCHED_OTHER wake-up granularity.
97 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
99 * This option delays the preemption effects of decoupled workloads
100 * and reduces their over-scheduling. Synchronous workloads will still
101 * have immediate wakeup/sleep latencies.
103 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
104 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
106 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
109 * The exponential sliding window over which load is averaged for shares
113 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
115 #ifdef CONFIG_CFS_BANDWIDTH
117 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
118 * each time a cfs_rq requests quota.
120 * Note: in the case that the slice exceeds the runtime remaining (either due
121 * to consumption or the quota being specified to be smaller than the slice)
122 * we will always only issue the remaining available time.
124 * default: 5 msec, units: microseconds
126 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
130 * The margin used when comparing utilization with CPU capacity:
131 * util * margin < capacity * 1024
133 unsigned int capacity_margin = 1280; /* ~20% */
135 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
141 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
147 static inline void update_load_set(struct load_weight *lw, unsigned long w)
154 * Increase the granularity value when there are more CPUs,
155 * because with more CPUs the 'effective latency' as visible
156 * to users decreases. But the relationship is not linear,
157 * so pick a second-best guess by going with the log2 of the
160 * This idea comes from the SD scheduler of Con Kolivas:
162 static unsigned int get_update_sysctl_factor(void)
164 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
167 switch (sysctl_sched_tunable_scaling) {
168 case SCHED_TUNABLESCALING_NONE:
171 case SCHED_TUNABLESCALING_LINEAR:
174 case SCHED_TUNABLESCALING_LOG:
176 factor = 1 + ilog2(cpus);
183 static void update_sysctl(void)
185 unsigned int factor = get_update_sysctl_factor();
187 #define SET_SYSCTL(name) \
188 (sysctl_##name = (factor) * normalized_sysctl_##name)
189 SET_SYSCTL(sched_min_granularity);
190 SET_SYSCTL(sched_latency);
191 SET_SYSCTL(sched_wakeup_granularity);
195 void sched_init_granularity(void)
200 #define WMULT_CONST (~0U)
201 #define WMULT_SHIFT 32
203 static void __update_inv_weight(struct load_weight *lw)
207 if (likely(lw->inv_weight))
210 w = scale_load_down(lw->weight);
212 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
214 else if (unlikely(!w))
215 lw->inv_weight = WMULT_CONST;
217 lw->inv_weight = WMULT_CONST / w;
221 * delta_exec * weight / lw.weight
223 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
225 * Either weight := NICE_0_LOAD and lw \e prio_to_wmult[], in which case
226 * we're guaranteed shift stays positive because inv_weight is guaranteed to
227 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
229 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
230 * weight/lw.weight <= 1, and therefore our shift will also be positive.
232 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
234 u64 fact = scale_load_down(weight);
235 int shift = WMULT_SHIFT;
237 __update_inv_weight(lw);
239 if (unlikely(fact >> 32)) {
246 /* hint to use a 32x32->64 mul */
247 fact = (u64)(u32)fact * lw->inv_weight;
254 return mul_u64_u32_shr(delta_exec, fact, shift);
258 const struct sched_class fair_sched_class;
260 /**************************************************************
261 * CFS operations on generic schedulable entities:
264 #ifdef CONFIG_FAIR_GROUP_SCHED
266 /* cpu runqueue to which this cfs_rq is attached */
267 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
272 /* An entity is a task if it doesn't "own" a runqueue */
273 #define entity_is_task(se) (!se->my_q)
275 static inline struct task_struct *task_of(struct sched_entity *se)
277 #ifdef CONFIG_SCHED_DEBUG
278 WARN_ON_ONCE(!entity_is_task(se));
280 return container_of(se, struct task_struct, se);
283 /* Walk up scheduling entities hierarchy */
284 #define for_each_sched_entity(se) \
285 for (; se; se = se->parent)
287 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
292 /* runqueue on which this entity is (to be) queued */
293 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
298 /* runqueue "owned" by this group */
299 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
304 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
306 if (!cfs_rq->on_list) {
307 struct rq *rq = rq_of(cfs_rq);
308 int cpu = cpu_of(rq);
310 * Ensure we either appear before our parent (if already
311 * enqueued) or force our parent to appear after us when it is
312 * enqueued. The fact that we always enqueue bottom-up
313 * reduces this to two cases and a special case for the root
314 * cfs_rq. Furthermore, it also means that we will always reset
315 * tmp_alone_branch either when the branch is connected
316 * to a tree or when we reach the beg of the tree
318 if (cfs_rq->tg->parent &&
319 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
321 * If parent is already on the list, we add the child
322 * just before. Thanks to circular linked property of
323 * the list, this means to put the child at the tail
324 * of the list that starts by parent.
326 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
327 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
329 * The branch is now connected to its tree so we can
330 * reset tmp_alone_branch to the beginning of the
333 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
334 } else if (!cfs_rq->tg->parent) {
336 * cfs rq without parent should be put
337 * at the tail of the list.
339 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
340 &rq->leaf_cfs_rq_list);
342 * We have reach the beg of a tree so we can reset
343 * tmp_alone_branch to the beginning of the list.
345 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
348 * The parent has not already been added so we want to
349 * make sure that it will be put after us.
350 * tmp_alone_branch points to the beg of the branch
351 * where we will add parent.
353 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
354 rq->tmp_alone_branch);
356 * update tmp_alone_branch to points to the new beg
359 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
366 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
368 if (cfs_rq->on_list) {
369 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
374 /* Iterate thr' all leaf cfs_rq's on a runqueue */
375 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
376 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
378 /* Do the two (enqueued) entities belong to the same group ? */
379 static inline struct cfs_rq *
380 is_same_group(struct sched_entity *se, struct sched_entity *pse)
382 if (se->cfs_rq == pse->cfs_rq)
388 static inline struct sched_entity *parent_entity(struct sched_entity *se)
394 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
396 int se_depth, pse_depth;
399 * preemption test can be made between sibling entities who are in the
400 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
401 * both tasks until we find their ancestors who are siblings of common
405 /* First walk up until both entities are at same depth */
406 se_depth = (*se)->depth;
407 pse_depth = (*pse)->depth;
409 while (se_depth > pse_depth) {
411 *se = parent_entity(*se);
414 while (pse_depth > se_depth) {
416 *pse = parent_entity(*pse);
419 while (!is_same_group(*se, *pse)) {
420 *se = parent_entity(*se);
421 *pse = parent_entity(*pse);
425 #else /* !CONFIG_FAIR_GROUP_SCHED */
427 static inline struct task_struct *task_of(struct sched_entity *se)
429 return container_of(se, struct task_struct, se);
432 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
434 return container_of(cfs_rq, struct rq, cfs);
437 #define entity_is_task(se) 1
439 #define for_each_sched_entity(se) \
440 for (; se; se = NULL)
442 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
444 return &task_rq(p)->cfs;
447 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
449 struct task_struct *p = task_of(se);
450 struct rq *rq = task_rq(p);
455 /* runqueue "owned" by this group */
456 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
461 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
465 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
469 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
470 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
472 static inline struct sched_entity *parent_entity(struct sched_entity *se)
478 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
482 #endif /* CONFIG_FAIR_GROUP_SCHED */
484 static __always_inline
485 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
487 /**************************************************************
488 * Scheduling class tree data structure manipulation methods:
491 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
493 s64 delta = (s64)(vruntime - max_vruntime);
495 max_vruntime = vruntime;
500 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
502 s64 delta = (s64)(vruntime - min_vruntime);
504 min_vruntime = vruntime;
509 static inline int entity_before(struct sched_entity *a,
510 struct sched_entity *b)
512 return (s64)(a->vruntime - b->vruntime) < 0;
515 static void update_min_vruntime(struct cfs_rq *cfs_rq)
517 u64 vruntime = cfs_rq->min_vruntime;
520 vruntime = cfs_rq->curr->vruntime;
522 if (cfs_rq->rb_leftmost) {
523 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
528 vruntime = se->vruntime;
530 vruntime = min_vruntime(vruntime, se->vruntime);
533 /* ensure we never gain time by being placed backwards. */
534 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
537 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
542 * Enqueue an entity into the rb-tree:
544 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
546 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
547 struct rb_node *parent = NULL;
548 struct sched_entity *entry;
552 * Find the right place in the rbtree:
556 entry = rb_entry(parent, struct sched_entity, run_node);
558 * We dont care about collisions. Nodes with
559 * the same key stay together.
561 if (entity_before(se, entry)) {
562 link = &parent->rb_left;
564 link = &parent->rb_right;
570 * Maintain a cache of leftmost tree entries (it is frequently
574 cfs_rq->rb_leftmost = &se->run_node;
576 rb_link_node(&se->run_node, parent, link);
577 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
580 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
582 if (cfs_rq->rb_leftmost == &se->run_node) {
583 struct rb_node *next_node;
585 next_node = rb_next(&se->run_node);
586 cfs_rq->rb_leftmost = next_node;
589 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
592 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
594 struct rb_node *left = cfs_rq->rb_leftmost;
599 return rb_entry(left, struct sched_entity, run_node);
602 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
604 struct rb_node *next = rb_next(&se->run_node);
609 return rb_entry(next, struct sched_entity, run_node);
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);
620 return rb_entry(last, struct sched_entity, run_node);
623 /**************************************************************
624 * Scheduling class statistics methods:
627 int sched_proc_update_handler(struct ctl_table *table, int write,
628 void __user *buffer, size_t *lenp,
631 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
632 unsigned int factor = get_update_sysctl_factor();
637 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
638 sysctl_sched_min_granularity);
640 #define WRT_SYSCTL(name) \
641 (normalized_sysctl_##name = sysctl_##name / (factor))
642 WRT_SYSCTL(sched_min_granularity);
643 WRT_SYSCTL(sched_latency);
644 WRT_SYSCTL(sched_wakeup_granularity);
654 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
656 if (unlikely(se->load.weight != NICE_0_LOAD))
657 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
663 * The idea is to set a period in which each task runs once.
665 * When there are too many tasks (sched_nr_latency) we have to stretch
666 * this period because otherwise the slices get too small.
668 * p = (nr <= nl) ? l : l*nr/nl
670 static u64 __sched_period(unsigned long nr_running)
672 if (unlikely(nr_running > sched_nr_latency))
673 return nr_running * sysctl_sched_min_granularity;
675 return sysctl_sched_latency;
679 * We calculate the wall-time slice from the period by taking a part
680 * proportional to the weight.
684 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
686 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
688 for_each_sched_entity(se) {
689 struct load_weight *load;
690 struct load_weight lw;
692 cfs_rq = cfs_rq_of(se);
693 load = &cfs_rq->load;
695 if (unlikely(!se->on_rq)) {
698 update_load_add(&lw, se->load.weight);
701 slice = __calc_delta(slice, se->load.weight, load);
707 * We calculate the vruntime slice of a to-be-inserted task.
711 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
713 return calc_delta_fair(sched_slice(cfs_rq, se), se);
717 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
718 static unsigned long task_h_load(struct task_struct *p);
721 * We choose a half-life close to 1 scheduling period.
722 * Note: The tables runnable_avg_yN_inv and runnable_avg_yN_sum are
723 * dependent on this value.
725 #define LOAD_AVG_PERIOD 32
726 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
727 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_AVG_MAX */
729 /* Give new sched_entity start runnable values to heavy its load in infant time */
730 void init_entity_runnable_average(struct sched_entity *se)
732 struct sched_avg *sa = &se->avg;
734 sa->last_update_time = 0;
736 * sched_avg's period_contrib should be strictly less then 1024, so
737 * we give it 1023 to make sure it is almost a period (1024us), and
738 * will definitely be update (after enqueue).
740 sa->period_contrib = 1023;
742 * Tasks are intialized with full load to be seen as heavy tasks until
743 * they get a chance to stabilize to their real load level.
744 * Group entities are intialized with zero load to reflect the fact that
745 * nothing has been attached to the task group yet.
747 if (entity_is_task(se))
748 sa->load_avg = scale_load_down(se->load.weight);
749 sa->load_sum = sa->load_avg * LOAD_AVG_MAX;
751 * In previous Android versions, we used to have:
752 * sa->util_avg = scale_load_down(SCHED_LOAD_SCALE);
753 * sa->util_sum = sa->util_avg * LOAD_AVG_MAX;
754 * However, that functionality has been moved to enqueue.
755 * It is unclear if we should restore this in enqueue.
758 * At this point, util_avg won't be used in select_task_rq_fair anyway
762 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
765 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
766 static int update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq);
767 static void attach_entity_cfs_rq(struct sched_entity *se);
768 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se);
771 * With new tasks being created, their initial util_avgs are extrapolated
772 * based on the cfs_rq's current util_avg:
774 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
776 * However, in many cases, the above util_avg does not give a desired
777 * value. Moreover, the sum of the util_avgs may be divergent, such
778 * as when the series is a harmonic series.
780 * To solve this problem, we also cap the util_avg of successive tasks to
781 * only 1/2 of the left utilization budget:
783 * util_avg_cap = (1024 - cfs_rq->avg.util_avg) / 2^n
785 * where n denotes the nth task.
787 * For example, a simplest series from the beginning would be like:
789 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
790 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
792 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
793 * if util_avg > util_avg_cap.
795 void post_init_entity_util_avg(struct sched_entity *se)
797 struct cfs_rq *cfs_rq = cfs_rq_of(se);
798 struct sched_avg *sa = &se->avg;
799 long cap = (long)(SCHED_CAPACITY_SCALE - cfs_rq->avg.util_avg) / 2;
802 if (cfs_rq->avg.util_avg != 0) {
803 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
804 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
806 if (sa->util_avg > cap)
812 * If we wish to restore tuning via setting initial util,
813 * this is where we should do it.
815 sa->util_sum = sa->util_avg * LOAD_AVG_MAX;
818 if (entity_is_task(se)) {
819 struct task_struct *p = task_of(se);
820 if (p->sched_class != &fair_sched_class) {
822 * For !fair tasks do:
824 update_cfs_rq_load_avg(now, cfs_rq, false);
825 attach_entity_load_avg(cfs_rq, se);
826 switched_from_fair(rq, p);
828 * such that the next switched_to_fair() has the
831 se->avg.last_update_time = cfs_rq_clock_task(cfs_rq);
836 attach_entity_cfs_rq(se);
839 #else /* !CONFIG_SMP */
840 void init_entity_runnable_average(struct sched_entity *se)
843 void post_init_entity_util_avg(struct sched_entity *se)
846 static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
849 #endif /* CONFIG_SMP */
852 * Update the current task's runtime statistics.
854 static void update_curr(struct cfs_rq *cfs_rq)
856 struct sched_entity *curr = cfs_rq->curr;
857 u64 now = rq_clock_task(rq_of(cfs_rq));
863 delta_exec = now - curr->exec_start;
864 if (unlikely((s64)delta_exec <= 0))
867 curr->exec_start = now;
869 schedstat_set(curr->statistics.exec_max,
870 max(delta_exec, curr->statistics.exec_max));
872 curr->sum_exec_runtime += delta_exec;
873 schedstat_add(cfs_rq, exec_clock, delta_exec);
875 curr->vruntime += calc_delta_fair(delta_exec, curr);
876 update_min_vruntime(cfs_rq);
878 if (entity_is_task(curr)) {
879 struct task_struct *curtask = task_of(curr);
881 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
882 cpuacct_charge(curtask, delta_exec);
883 account_group_exec_runtime(curtask, delta_exec);
886 account_cfs_rq_runtime(cfs_rq, delta_exec);
889 static void update_curr_fair(struct rq *rq)
891 update_curr(cfs_rq_of(&rq->curr->se));
895 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
897 schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq)));
901 * Task is being enqueued - update stats:
903 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
906 * Are we enqueueing a waiting task? (for current tasks
907 * a dequeue/enqueue event is a NOP)
909 if (se != cfs_rq->curr)
910 update_stats_wait_start(cfs_rq, se);
914 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
916 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
917 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start));
918 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
919 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
920 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
921 #ifdef CONFIG_SCHEDSTATS
922 if (entity_is_task(se)) {
923 trace_sched_stat_wait(task_of(se),
924 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
927 schedstat_set(se->statistics.wait_start, 0);
931 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
934 * Mark the end of the wait period if dequeueing a
937 if (se != cfs_rq->curr)
938 update_stats_wait_end(cfs_rq, se);
942 * We are picking a new current task - update its stats:
945 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
948 * We are starting a new run period:
950 se->exec_start = rq_clock_task(rq_of(cfs_rq));
953 /**************************************************
954 * Scheduling class queueing methods:
957 #ifdef CONFIG_NUMA_BALANCING
959 * Approximate time to scan a full NUMA task in ms. The task scan period is
960 * calculated based on the tasks virtual memory size and
961 * numa_balancing_scan_size.
963 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
964 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
966 /* Portion of address space to scan in MB */
967 unsigned int sysctl_numa_balancing_scan_size = 256;
969 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
970 unsigned int sysctl_numa_balancing_scan_delay = 1000;
972 static unsigned int task_nr_scan_windows(struct task_struct *p)
974 unsigned long rss = 0;
975 unsigned long nr_scan_pages;
978 * Calculations based on RSS as non-present and empty pages are skipped
979 * by the PTE scanner and NUMA hinting faults should be trapped based
982 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
983 rss = get_mm_rss(p->mm);
987 rss = round_up(rss, nr_scan_pages);
988 return rss / nr_scan_pages;
991 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
992 #define MAX_SCAN_WINDOW 2560
994 static unsigned int task_scan_min(struct task_struct *p)
996 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
997 unsigned int scan, floor;
998 unsigned int windows = 1;
1000 if (scan_size < MAX_SCAN_WINDOW)
1001 windows = MAX_SCAN_WINDOW / scan_size;
1002 floor = 1000 / windows;
1004 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1005 return max_t(unsigned int, floor, scan);
1008 static unsigned int task_scan_max(struct task_struct *p)
1010 unsigned int smin = task_scan_min(p);
1013 /* Watch for min being lower than max due to floor calculations */
1014 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1015 return max(smin, smax);
1018 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1020 rq->nr_numa_running += (p->numa_preferred_nid != -1);
1021 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1024 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1026 rq->nr_numa_running -= (p->numa_preferred_nid != -1);
1027 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1033 spinlock_t lock; /* nr_tasks, tasks */
1037 struct rcu_head rcu;
1038 nodemask_t active_nodes;
1039 unsigned long total_faults;
1041 * Faults_cpu is used to decide whether memory should move
1042 * towards the CPU. As a consequence, these stats are weighted
1043 * more by CPU use than by memory faults.
1045 unsigned long *faults_cpu;
1046 unsigned long faults[0];
1049 /* Shared or private faults. */
1050 #define NR_NUMA_HINT_FAULT_TYPES 2
1052 /* Memory and CPU locality */
1053 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1055 /* Averaged statistics, and temporary buffers. */
1056 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1058 pid_t task_numa_group_id(struct task_struct *p)
1060 return p->numa_group ? p->numa_group->gid : 0;
1064 * The averaged statistics, shared & private, memory & cpu,
1065 * occupy the first half of the array. The second half of the
1066 * array is for current counters, which are averaged into the
1067 * first set by task_numa_placement.
1069 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1071 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1074 static inline unsigned long task_faults(struct task_struct *p, int nid)
1076 if (!p->numa_faults)
1079 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1080 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1083 static inline unsigned long group_faults(struct task_struct *p, int nid)
1088 return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1089 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1092 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1094 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
1095 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
1098 /* Handle placement on systems where not all nodes are directly connected. */
1099 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1100 int maxdist, bool task)
1102 unsigned long score = 0;
1106 * All nodes are directly connected, and the same distance
1107 * from each other. No need for fancy placement algorithms.
1109 if (sched_numa_topology_type == NUMA_DIRECT)
1113 * This code is called for each node, introducing N^2 complexity,
1114 * which should be ok given the number of nodes rarely exceeds 8.
1116 for_each_online_node(node) {
1117 unsigned long faults;
1118 int dist = node_distance(nid, node);
1121 * The furthest away nodes in the system are not interesting
1122 * for placement; nid was already counted.
1124 if (dist == sched_max_numa_distance || node == nid)
1128 * On systems with a backplane NUMA topology, compare groups
1129 * of nodes, and move tasks towards the group with the most
1130 * memory accesses. When comparing two nodes at distance
1131 * "hoplimit", only nodes closer by than "hoplimit" are part
1132 * of each group. Skip other nodes.
1134 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1138 /* Add up the faults from nearby nodes. */
1140 faults = task_faults(p, node);
1142 faults = group_faults(p, node);
1145 * On systems with a glueless mesh NUMA topology, there are
1146 * no fixed "groups of nodes". Instead, nodes that are not
1147 * directly connected bounce traffic through intermediate
1148 * nodes; a numa_group can occupy any set of nodes.
1149 * The further away a node is, the less the faults count.
1150 * This seems to result in good task placement.
1152 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1153 faults *= (sched_max_numa_distance - dist);
1154 faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
1164 * These return the fraction of accesses done by a particular task, or
1165 * task group, on a particular numa node. The group weight is given a
1166 * larger multiplier, in order to group tasks together that are almost
1167 * evenly spread out between numa nodes.
1169 static inline unsigned long task_weight(struct task_struct *p, int nid,
1172 unsigned long faults, total_faults;
1174 if (!p->numa_faults)
1177 total_faults = p->total_numa_faults;
1182 faults = task_faults(p, nid);
1183 faults += score_nearby_nodes(p, nid, dist, true);
1185 return 1000 * faults / total_faults;
1188 static inline unsigned long group_weight(struct task_struct *p, int nid,
1191 unsigned long faults, total_faults;
1196 total_faults = p->numa_group->total_faults;
1201 faults = group_faults(p, nid);
1202 faults += score_nearby_nodes(p, nid, dist, false);
1204 return 1000 * faults / total_faults;
1207 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1208 int src_nid, int dst_cpu)
1210 struct numa_group *ng = p->numa_group;
1211 int dst_nid = cpu_to_node(dst_cpu);
1212 int last_cpupid, this_cpupid;
1214 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1217 * Multi-stage node selection is used in conjunction with a periodic
1218 * migration fault to build a temporal task<->page relation. By using
1219 * a two-stage filter we remove short/unlikely relations.
1221 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1222 * a task's usage of a particular page (n_p) per total usage of this
1223 * page (n_t) (in a given time-span) to a probability.
1225 * Our periodic faults will sample this probability and getting the
1226 * same result twice in a row, given these samples are fully
1227 * independent, is then given by P(n)^2, provided our sample period
1228 * is sufficiently short compared to the usage pattern.
1230 * This quadric squishes small probabilities, making it less likely we
1231 * act on an unlikely task<->page relation.
1233 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1234 if (!cpupid_pid_unset(last_cpupid) &&
1235 cpupid_to_nid(last_cpupid) != dst_nid)
1238 /* Always allow migrate on private faults */
1239 if (cpupid_match_pid(p, last_cpupid))
1242 /* A shared fault, but p->numa_group has not been set up yet. */
1247 * Do not migrate if the destination is not a node that
1248 * is actively used by this numa group.
1250 if (!node_isset(dst_nid, ng->active_nodes))
1254 * Source is a node that is not actively used by this
1255 * numa group, while the destination is. Migrate.
1257 if (!node_isset(src_nid, ng->active_nodes))
1261 * Both source and destination are nodes in active
1262 * use by this numa group. Maximize memory bandwidth
1263 * by migrating from more heavily used groups, to less
1264 * heavily used ones, spreading the load around.
1265 * Use a 1/4 hysteresis to avoid spurious page movement.
1267 return group_faults(p, dst_nid) < (group_faults(p, src_nid) * 3 / 4);
1270 static unsigned long weighted_cpuload(const int cpu);
1271 static unsigned long source_load(int cpu, int type);
1272 static unsigned long target_load(int cpu, int type);
1273 static unsigned long capacity_of(int cpu);
1274 static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
1276 /* Cached statistics for all CPUs within a node */
1278 unsigned long nr_running;
1281 /* Total compute capacity of CPUs on a node */
1282 unsigned long compute_capacity;
1284 /* Approximate capacity in terms of runnable tasks on a node */
1285 unsigned long task_capacity;
1286 int has_free_capacity;
1290 * XXX borrowed from update_sg_lb_stats
1292 static void update_numa_stats(struct numa_stats *ns, int nid)
1294 int smt, cpu, cpus = 0;
1295 unsigned long capacity;
1297 memset(ns, 0, sizeof(*ns));
1298 for_each_cpu(cpu, cpumask_of_node(nid)) {
1299 struct rq *rq = cpu_rq(cpu);
1301 ns->nr_running += rq->nr_running;
1302 ns->load += weighted_cpuload(cpu);
1303 ns->compute_capacity += capacity_of(cpu);
1309 * If we raced with hotplug and there are no CPUs left in our mask
1310 * the @ns structure is NULL'ed and task_numa_compare() will
1311 * not find this node attractive.
1313 * We'll either bail at !has_free_capacity, or we'll detect a huge
1314 * imbalance and bail there.
1319 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1320 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
1321 capacity = cpus / smt; /* cores */
1323 ns->task_capacity = min_t(unsigned, capacity,
1324 DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
1325 ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
1328 struct task_numa_env {
1329 struct task_struct *p;
1331 int src_cpu, src_nid;
1332 int dst_cpu, dst_nid;
1334 struct numa_stats src_stats, dst_stats;
1339 struct task_struct *best_task;
1344 static void task_numa_assign(struct task_numa_env *env,
1345 struct task_struct *p, long imp)
1348 put_task_struct(env->best_task);
1351 env->best_imp = imp;
1352 env->best_cpu = env->dst_cpu;
1355 static bool load_too_imbalanced(long src_load, long dst_load,
1356 struct task_numa_env *env)
1359 long orig_src_load, orig_dst_load;
1360 long src_capacity, dst_capacity;
1363 * The load is corrected for the CPU capacity available on each node.
1366 * ------------ vs ---------
1367 * src_capacity dst_capacity
1369 src_capacity = env->src_stats.compute_capacity;
1370 dst_capacity = env->dst_stats.compute_capacity;
1372 /* We care about the slope of the imbalance, not the direction. */
1373 if (dst_load < src_load)
1374 swap(dst_load, src_load);
1376 /* Is the difference below the threshold? */
1377 imb = dst_load * src_capacity * 100 -
1378 src_load * dst_capacity * env->imbalance_pct;
1383 * The imbalance is above the allowed threshold.
1384 * Compare it with the old imbalance.
1386 orig_src_load = env->src_stats.load;
1387 orig_dst_load = env->dst_stats.load;
1389 if (orig_dst_load < orig_src_load)
1390 swap(orig_dst_load, orig_src_load);
1392 old_imb = orig_dst_load * src_capacity * 100 -
1393 orig_src_load * dst_capacity * env->imbalance_pct;
1395 /* Would this change make things worse? */
1396 return (imb > old_imb);
1400 * This checks if the overall compute and NUMA accesses of the system would
1401 * be improved if the source tasks was migrated to the target dst_cpu taking
1402 * into account that it might be best if task running on the dst_cpu should
1403 * be exchanged with the source task
1405 static void task_numa_compare(struct task_numa_env *env,
1406 long taskimp, long groupimp)
1408 struct rq *src_rq = cpu_rq(env->src_cpu);
1409 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1410 struct task_struct *cur;
1411 long src_load, dst_load;
1413 long imp = env->p->numa_group ? groupimp : taskimp;
1415 int dist = env->dist;
1416 bool assigned = false;
1420 raw_spin_lock_irq(&dst_rq->lock);
1423 * No need to move the exiting task or idle task.
1425 if ((cur->flags & PF_EXITING) || is_idle_task(cur))
1429 * The task_struct must be protected here to protect the
1430 * p->numa_faults access in the task_weight since the
1431 * numa_faults could already be freed in the following path:
1432 * finish_task_switch()
1433 * --> put_task_struct()
1434 * --> __put_task_struct()
1435 * --> task_numa_free()
1437 get_task_struct(cur);
1440 raw_spin_unlock_irq(&dst_rq->lock);
1443 * Because we have preemption enabled we can get migrated around and
1444 * end try selecting ourselves (current == env->p) as a swap candidate.
1450 * "imp" is the fault differential for the source task between the
1451 * source and destination node. Calculate the total differential for
1452 * the source task and potential destination task. The more negative
1453 * the value is, the more rmeote accesses that would be expected to
1454 * be incurred if the tasks were swapped.
1457 /* Skip this swap candidate if cannot move to the source cpu */
1458 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
1462 * If dst and source tasks are in the same NUMA group, or not
1463 * in any group then look only at task weights.
1465 if (cur->numa_group == env->p->numa_group) {
1466 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1467 task_weight(cur, env->dst_nid, dist);
1469 * Add some hysteresis to prevent swapping the
1470 * tasks within a group over tiny differences.
1472 if (cur->numa_group)
1476 * Compare the group weights. If a task is all by
1477 * itself (not part of a group), use the task weight
1480 if (cur->numa_group)
1481 imp += group_weight(cur, env->src_nid, dist) -
1482 group_weight(cur, env->dst_nid, dist);
1484 imp += task_weight(cur, env->src_nid, dist) -
1485 task_weight(cur, env->dst_nid, dist);
1489 if (imp <= env->best_imp && moveimp <= env->best_imp)
1493 /* Is there capacity at our destination? */
1494 if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
1495 !env->dst_stats.has_free_capacity)
1501 /* Balance doesn't matter much if we're running a task per cpu */
1502 if (imp > env->best_imp && src_rq->nr_running == 1 &&
1503 dst_rq->nr_running == 1)
1507 * In the overloaded case, try and keep the load balanced.
1510 load = task_h_load(env->p);
1511 dst_load = env->dst_stats.load + load;
1512 src_load = env->src_stats.load - load;
1514 if (moveimp > imp && moveimp > env->best_imp) {
1516 * If the improvement from just moving env->p direction is
1517 * better than swapping tasks around, check if a move is
1518 * possible. Store a slightly smaller score than moveimp,
1519 * so an actually idle CPU will win.
1521 if (!load_too_imbalanced(src_load, dst_load, env)) {
1523 put_task_struct(cur);
1529 if (imp <= env->best_imp)
1533 load = task_h_load(cur);
1538 if (load_too_imbalanced(src_load, dst_load, env))
1542 * One idle CPU per node is evaluated for a task numa move.
1543 * Call select_idle_sibling to maybe find a better one.
1546 env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
1551 task_numa_assign(env, cur, imp);
1555 * The dst_rq->curr isn't assigned. The protection for task_struct is
1558 if (cur && !assigned)
1559 put_task_struct(cur);
1562 static void task_numa_find_cpu(struct task_numa_env *env,
1563 long taskimp, long groupimp)
1567 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1568 /* Skip this CPU if the source task cannot migrate */
1569 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
1573 task_numa_compare(env, taskimp, groupimp);
1577 /* Only move tasks to a NUMA node less busy than the current node. */
1578 static bool numa_has_capacity(struct task_numa_env *env)
1580 struct numa_stats *src = &env->src_stats;
1581 struct numa_stats *dst = &env->dst_stats;
1583 if (src->has_free_capacity && !dst->has_free_capacity)
1587 * Only consider a task move if the source has a higher load
1588 * than the destination, corrected for CPU capacity on each node.
1590 * src->load dst->load
1591 * --------------------- vs ---------------------
1592 * src->compute_capacity dst->compute_capacity
1594 if (src->load * dst->compute_capacity * env->imbalance_pct >
1596 dst->load * src->compute_capacity * 100)
1602 static int task_numa_migrate(struct task_struct *p)
1604 struct task_numa_env env = {
1607 .src_cpu = task_cpu(p),
1608 .src_nid = task_node(p),
1610 .imbalance_pct = 112,
1616 struct sched_domain *sd;
1617 unsigned long taskweight, groupweight;
1619 long taskimp, groupimp;
1622 * Pick the lowest SD_NUMA domain, as that would have the smallest
1623 * imbalance and would be the first to start moving tasks about.
1625 * And we want to avoid any moving of tasks about, as that would create
1626 * random movement of tasks -- counter the numa conditions we're trying
1630 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
1632 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
1636 * Cpusets can break the scheduler domain tree into smaller
1637 * balance domains, some of which do not cross NUMA boundaries.
1638 * Tasks that are "trapped" in such domains cannot be migrated
1639 * elsewhere, so there is no point in (re)trying.
1641 if (unlikely(!sd)) {
1642 p->numa_preferred_nid = task_node(p);
1646 env.dst_nid = p->numa_preferred_nid;
1647 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
1648 taskweight = task_weight(p, env.src_nid, dist);
1649 groupweight = group_weight(p, env.src_nid, dist);
1650 update_numa_stats(&env.src_stats, env.src_nid);
1651 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
1652 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
1653 update_numa_stats(&env.dst_stats, env.dst_nid);
1655 /* Try to find a spot on the preferred nid. */
1656 if (numa_has_capacity(&env))
1657 task_numa_find_cpu(&env, taskimp, groupimp);
1660 * Look at other nodes in these cases:
1661 * - there is no space available on the preferred_nid
1662 * - the task is part of a numa_group that is interleaved across
1663 * multiple NUMA nodes; in order to better consolidate the group,
1664 * we need to check other locations.
1666 if (env.best_cpu == -1 || (p->numa_group &&
1667 nodes_weight(p->numa_group->active_nodes) > 1)) {
1668 for_each_online_node(nid) {
1669 if (nid == env.src_nid || nid == p->numa_preferred_nid)
1672 dist = node_distance(env.src_nid, env.dst_nid);
1673 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1675 taskweight = task_weight(p, env.src_nid, dist);
1676 groupweight = group_weight(p, env.src_nid, dist);
1679 /* Only consider nodes where both task and groups benefit */
1680 taskimp = task_weight(p, nid, dist) - taskweight;
1681 groupimp = group_weight(p, nid, dist) - groupweight;
1682 if (taskimp < 0 && groupimp < 0)
1687 update_numa_stats(&env.dst_stats, env.dst_nid);
1688 if (numa_has_capacity(&env))
1689 task_numa_find_cpu(&env, taskimp, groupimp);
1694 * If the task is part of a workload that spans multiple NUMA nodes,
1695 * and is migrating into one of the workload's active nodes, remember
1696 * this node as the task's preferred numa node, so the workload can
1698 * A task that migrated to a second choice node will be better off
1699 * trying for a better one later. Do not set the preferred node here.
1701 if (p->numa_group) {
1702 if (env.best_cpu == -1)
1707 if (node_isset(nid, p->numa_group->active_nodes))
1708 sched_setnuma(p, env.dst_nid);
1711 /* No better CPU than the current one was found. */
1712 if (env.best_cpu == -1)
1716 * Reset the scan period if the task is being rescheduled on an
1717 * alternative node to recheck if the tasks is now properly placed.
1719 p->numa_scan_period = task_scan_min(p);
1721 if (env.best_task == NULL) {
1722 ret = migrate_task_to(p, env.best_cpu);
1724 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
1728 ret = migrate_swap(p, env.best_task);
1730 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
1731 put_task_struct(env.best_task);
1735 /* Attempt to migrate a task to a CPU on the preferred node. */
1736 static void numa_migrate_preferred(struct task_struct *p)
1738 unsigned long interval = HZ;
1740 /* This task has no NUMA fault statistics yet */
1741 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
1744 /* Periodically retry migrating the task to the preferred node */
1745 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
1746 p->numa_migrate_retry = jiffies + interval;
1748 /* Success if task is already running on preferred CPU */
1749 if (task_node(p) == p->numa_preferred_nid)
1752 /* Otherwise, try migrate to a CPU on the preferred node */
1753 task_numa_migrate(p);
1757 * Find the nodes on which the workload is actively running. We do this by
1758 * tracking the nodes from which NUMA hinting faults are triggered. This can
1759 * be different from the set of nodes where the workload's memory is currently
1762 * The bitmask is used to make smarter decisions on when to do NUMA page
1763 * migrations, To prevent flip-flopping, and excessive page migrations, nodes
1764 * are added when they cause over 6/16 of the maximum number of faults, but
1765 * only removed when they drop below 3/16.
1767 static void update_numa_active_node_mask(struct numa_group *numa_group)
1769 unsigned long faults, max_faults = 0;
1772 for_each_online_node(nid) {
1773 faults = group_faults_cpu(numa_group, nid);
1774 if (faults > max_faults)
1775 max_faults = faults;
1778 for_each_online_node(nid) {
1779 faults = group_faults_cpu(numa_group, nid);
1780 if (!node_isset(nid, numa_group->active_nodes)) {
1781 if (faults > max_faults * 6 / 16)
1782 node_set(nid, numa_group->active_nodes);
1783 } else if (faults < max_faults * 3 / 16)
1784 node_clear(nid, numa_group->active_nodes);
1789 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1790 * increments. The more local the fault statistics are, the higher the scan
1791 * period will be for the next scan window. If local/(local+remote) ratio is
1792 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1793 * the scan period will decrease. Aim for 70% local accesses.
1795 #define NUMA_PERIOD_SLOTS 10
1796 #define NUMA_PERIOD_THRESHOLD 7
1799 * Increase the scan period (slow down scanning) if the majority of
1800 * our memory is already on our local node, or if the majority of
1801 * the page accesses are shared with other processes.
1802 * Otherwise, decrease the scan period.
1804 static void update_task_scan_period(struct task_struct *p,
1805 unsigned long shared, unsigned long private)
1807 unsigned int period_slot;
1811 unsigned long remote = p->numa_faults_locality[0];
1812 unsigned long local = p->numa_faults_locality[1];
1815 * If there were no record hinting faults then either the task is
1816 * completely idle or all activity is areas that are not of interest
1817 * to automatic numa balancing. Related to that, if there were failed
1818 * migration then it implies we are migrating too quickly or the local
1819 * node is overloaded. In either case, scan slower
1821 if (local + shared == 0 || p->numa_faults_locality[2]) {
1822 p->numa_scan_period = min(p->numa_scan_period_max,
1823 p->numa_scan_period << 1);
1825 p->mm->numa_next_scan = jiffies +
1826 msecs_to_jiffies(p->numa_scan_period);
1832 * Prepare to scale scan period relative to the current period.
1833 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1834 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1835 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1837 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1838 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1839 if (ratio >= NUMA_PERIOD_THRESHOLD) {
1840 int slot = ratio - NUMA_PERIOD_THRESHOLD;
1843 diff = slot * period_slot;
1845 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1848 * Scale scan rate increases based on sharing. There is an
1849 * inverse relationship between the degree of sharing and
1850 * the adjustment made to the scanning period. Broadly
1851 * speaking the intent is that there is little point
1852 * scanning faster if shared accesses dominate as it may
1853 * simply bounce migrations uselessly
1855 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared + 1));
1856 diff = (diff * ratio) / NUMA_PERIOD_SLOTS;
1859 p->numa_scan_period = clamp(p->numa_scan_period + diff,
1860 task_scan_min(p), task_scan_max(p));
1861 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1865 * Get the fraction of time the task has been running since the last
1866 * NUMA placement cycle. The scheduler keeps similar statistics, but
1867 * decays those on a 32ms period, which is orders of magnitude off
1868 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1869 * stats only if the task is so new there are no NUMA statistics yet.
1871 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1873 u64 runtime, delta, now;
1874 /* Use the start of this time slice to avoid calculations. */
1875 now = p->se.exec_start;
1876 runtime = p->se.sum_exec_runtime;
1878 if (p->last_task_numa_placement) {
1879 delta = runtime - p->last_sum_exec_runtime;
1880 *period = now - p->last_task_numa_placement;
1882 /* Avoid time going backwards, prevent potential divide error: */
1883 if (unlikely((s64)*period < 0))
1886 delta = p->se.avg.load_sum / p->se.load.weight;
1887 *period = LOAD_AVG_MAX;
1890 p->last_sum_exec_runtime = runtime;
1891 p->last_task_numa_placement = now;
1897 * Determine the preferred nid for a task in a numa_group. This needs to
1898 * be done in a way that produces consistent results with group_weight,
1899 * otherwise workloads might not converge.
1901 static int preferred_group_nid(struct task_struct *p, int nid)
1906 /* Direct connections between all NUMA nodes. */
1907 if (sched_numa_topology_type == NUMA_DIRECT)
1911 * On a system with glueless mesh NUMA topology, group_weight
1912 * scores nodes according to the number of NUMA hinting faults on
1913 * both the node itself, and on nearby nodes.
1915 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1916 unsigned long score, max_score = 0;
1917 int node, max_node = nid;
1919 dist = sched_max_numa_distance;
1921 for_each_online_node(node) {
1922 score = group_weight(p, node, dist);
1923 if (score > max_score) {
1932 * Finding the preferred nid in a system with NUMA backplane
1933 * interconnect topology is more involved. The goal is to locate
1934 * tasks from numa_groups near each other in the system, and
1935 * untangle workloads from different sides of the system. This requires
1936 * searching down the hierarchy of node groups, recursively searching
1937 * inside the highest scoring group of nodes. The nodemask tricks
1938 * keep the complexity of the search down.
1940 nodes = node_online_map;
1941 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
1942 unsigned long max_faults = 0;
1943 nodemask_t max_group = NODE_MASK_NONE;
1946 /* Are there nodes at this distance from each other? */
1947 if (!find_numa_distance(dist))
1950 for_each_node_mask(a, nodes) {
1951 unsigned long faults = 0;
1952 nodemask_t this_group;
1953 nodes_clear(this_group);
1955 /* Sum group's NUMA faults; includes a==b case. */
1956 for_each_node_mask(b, nodes) {
1957 if (node_distance(a, b) < dist) {
1958 faults += group_faults(p, b);
1959 node_set(b, this_group);
1960 node_clear(b, nodes);
1964 /* Remember the top group. */
1965 if (faults > max_faults) {
1966 max_faults = faults;
1967 max_group = this_group;
1969 * subtle: at the smallest distance there is
1970 * just one node left in each "group", the
1971 * winner is the preferred nid.
1976 /* Next round, evaluate the nodes within max_group. */
1984 static void task_numa_placement(struct task_struct *p)
1986 int seq, nid, max_nid = -1, max_group_nid = -1;
1987 unsigned long max_faults = 0, max_group_faults = 0;
1988 unsigned long fault_types[2] = { 0, 0 };
1989 unsigned long total_faults;
1990 u64 runtime, period;
1991 spinlock_t *group_lock = NULL;
1994 * The p->mm->numa_scan_seq field gets updated without
1995 * exclusive access. Use READ_ONCE() here to ensure
1996 * that the field is read in a single access:
1998 seq = READ_ONCE(p->mm->numa_scan_seq);
1999 if (p->numa_scan_seq == seq)
2001 p->numa_scan_seq = seq;
2002 p->numa_scan_period_max = task_scan_max(p);
2004 total_faults = p->numa_faults_locality[0] +
2005 p->numa_faults_locality[1];
2006 runtime = numa_get_avg_runtime(p, &period);
2008 /* If the task is part of a group prevent parallel updates to group stats */
2009 if (p->numa_group) {
2010 group_lock = &p->numa_group->lock;
2011 spin_lock_irq(group_lock);
2014 /* Find the node with the highest number of faults */
2015 for_each_online_node(nid) {
2016 /* Keep track of the offsets in numa_faults array */
2017 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2018 unsigned long faults = 0, group_faults = 0;
2021 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2022 long diff, f_diff, f_weight;
2024 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2025 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2026 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2027 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2029 /* Decay existing window, copy faults since last scan */
2030 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2031 fault_types[priv] += p->numa_faults[membuf_idx];
2032 p->numa_faults[membuf_idx] = 0;
2035 * Normalize the faults_from, so all tasks in a group
2036 * count according to CPU use, instead of by the raw
2037 * number of faults. Tasks with little runtime have
2038 * little over-all impact on throughput, and thus their
2039 * faults are less important.
2041 f_weight = div64_u64(runtime << 16, period + 1);
2042 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2044 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2045 p->numa_faults[cpubuf_idx] = 0;
2047 p->numa_faults[mem_idx] += diff;
2048 p->numa_faults[cpu_idx] += f_diff;
2049 faults += p->numa_faults[mem_idx];
2050 p->total_numa_faults += diff;
2051 if (p->numa_group) {
2053 * safe because we can only change our own group
2055 * mem_idx represents the offset for a given
2056 * nid and priv in a specific region because it
2057 * is at the beginning of the numa_faults array.
2059 p->numa_group->faults[mem_idx] += diff;
2060 p->numa_group->faults_cpu[mem_idx] += f_diff;
2061 p->numa_group->total_faults += diff;
2062 group_faults += p->numa_group->faults[mem_idx];
2066 if (faults > max_faults) {
2067 max_faults = faults;
2071 if (group_faults > max_group_faults) {
2072 max_group_faults = group_faults;
2073 max_group_nid = nid;
2077 update_task_scan_period(p, fault_types[0], fault_types[1]);
2079 if (p->numa_group) {
2080 update_numa_active_node_mask(p->numa_group);
2081 spin_unlock_irq(group_lock);
2082 max_nid = preferred_group_nid(p, max_group_nid);
2086 /* Set the new preferred node */
2087 if (max_nid != p->numa_preferred_nid)
2088 sched_setnuma(p, max_nid);
2090 if (task_node(p) != p->numa_preferred_nid)
2091 numa_migrate_preferred(p);
2095 static inline int get_numa_group(struct numa_group *grp)
2097 return atomic_inc_not_zero(&grp->refcount);
2100 static inline void put_numa_group(struct numa_group *grp)
2102 if (atomic_dec_and_test(&grp->refcount))
2103 kfree_rcu(grp, rcu);
2106 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2109 struct numa_group *grp, *my_grp;
2110 struct task_struct *tsk;
2112 int cpu = cpupid_to_cpu(cpupid);
2115 if (unlikely(!p->numa_group)) {
2116 unsigned int size = sizeof(struct numa_group) +
2117 4*nr_node_ids*sizeof(unsigned long);
2119 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2123 atomic_set(&grp->refcount, 1);
2124 spin_lock_init(&grp->lock);
2126 /* Second half of the array tracks nids where faults happen */
2127 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2130 node_set(task_node(current), grp->active_nodes);
2132 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2133 grp->faults[i] = p->numa_faults[i];
2135 grp->total_faults = p->total_numa_faults;
2138 rcu_assign_pointer(p->numa_group, grp);
2142 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2144 if (!cpupid_match_pid(tsk, cpupid))
2147 grp = rcu_dereference(tsk->numa_group);
2151 my_grp = p->numa_group;
2156 * Only join the other group if its bigger; if we're the bigger group,
2157 * the other task will join us.
2159 if (my_grp->nr_tasks > grp->nr_tasks)
2163 * Tie-break on the grp address.
2165 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2168 /* Always join threads in the same process. */
2169 if (tsk->mm == current->mm)
2172 /* Simple filter to avoid false positives due to PID collisions */
2173 if (flags & TNF_SHARED)
2176 /* Update priv based on whether false sharing was detected */
2179 if (join && !get_numa_group(grp))
2187 BUG_ON(irqs_disabled());
2188 double_lock_irq(&my_grp->lock, &grp->lock);
2190 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2191 my_grp->faults[i] -= p->numa_faults[i];
2192 grp->faults[i] += p->numa_faults[i];
2194 my_grp->total_faults -= p->total_numa_faults;
2195 grp->total_faults += p->total_numa_faults;
2200 spin_unlock(&my_grp->lock);
2201 spin_unlock_irq(&grp->lock);
2203 rcu_assign_pointer(p->numa_group, grp);
2205 put_numa_group(my_grp);
2213 void task_numa_free(struct task_struct *p)
2215 struct numa_group *grp = p->numa_group;
2216 void *numa_faults = p->numa_faults;
2217 unsigned long flags;
2221 spin_lock_irqsave(&grp->lock, flags);
2222 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2223 grp->faults[i] -= p->numa_faults[i];
2224 grp->total_faults -= p->total_numa_faults;
2227 spin_unlock_irqrestore(&grp->lock, flags);
2228 RCU_INIT_POINTER(p->numa_group, NULL);
2229 put_numa_group(grp);
2232 p->numa_faults = NULL;
2237 * Got a PROT_NONE fault for a page on @node.
2239 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2241 struct task_struct *p = current;
2242 bool migrated = flags & TNF_MIGRATED;
2243 int cpu_node = task_node(current);
2244 int local = !!(flags & TNF_FAULT_LOCAL);
2247 if (!static_branch_likely(&sched_numa_balancing))
2250 /* for example, ksmd faulting in a user's mm */
2254 /* Allocate buffer to track faults on a per-node basis */
2255 if (unlikely(!p->numa_faults)) {
2256 int size = sizeof(*p->numa_faults) *
2257 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2259 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2260 if (!p->numa_faults)
2263 p->total_numa_faults = 0;
2264 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2268 * First accesses are treated as private, otherwise consider accesses
2269 * to be private if the accessing pid has not changed
2271 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2274 priv = cpupid_match_pid(p, last_cpupid);
2275 if (!priv && !(flags & TNF_NO_GROUP))
2276 task_numa_group(p, last_cpupid, flags, &priv);
2280 * If a workload spans multiple NUMA nodes, a shared fault that
2281 * occurs wholly within the set of nodes that the workload is
2282 * actively using should be counted as local. This allows the
2283 * scan rate to slow down when a workload has settled down.
2285 if (!priv && !local && p->numa_group &&
2286 node_isset(cpu_node, p->numa_group->active_nodes) &&
2287 node_isset(mem_node, p->numa_group->active_nodes))
2290 task_numa_placement(p);
2293 * Retry task to preferred node migration periodically, in case it
2294 * case it previously failed, or the scheduler moved us.
2296 if (time_after(jiffies, p->numa_migrate_retry))
2297 numa_migrate_preferred(p);
2300 p->numa_pages_migrated += pages;
2301 if (flags & TNF_MIGRATE_FAIL)
2302 p->numa_faults_locality[2] += pages;
2304 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2305 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2306 p->numa_faults_locality[local] += pages;
2309 static void reset_ptenuma_scan(struct task_struct *p)
2312 * We only did a read acquisition of the mmap sem, so
2313 * p->mm->numa_scan_seq is written to without exclusive access
2314 * and the update is not guaranteed to be atomic. That's not
2315 * much of an issue though, since this is just used for
2316 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2317 * expensive, to avoid any form of compiler optimizations:
2319 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
2320 p->mm->numa_scan_offset = 0;
2324 * The expensive part of numa migration is done from task_work context.
2325 * Triggered from task_tick_numa().
2327 void task_numa_work(struct callback_head *work)
2329 unsigned long migrate, next_scan, now = jiffies;
2330 struct task_struct *p = current;
2331 struct mm_struct *mm = p->mm;
2332 struct vm_area_struct *vma;
2333 unsigned long start, end;
2334 unsigned long nr_pte_updates = 0;
2335 long pages, virtpages;
2337 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
2339 work->next = work; /* protect against double add */
2341 * Who cares about NUMA placement when they're dying.
2343 * NOTE: make sure not to dereference p->mm before this check,
2344 * exit_task_work() happens _after_ exit_mm() so we could be called
2345 * without p->mm even though we still had it when we enqueued this
2348 if (p->flags & PF_EXITING)
2351 if (!mm->numa_next_scan) {
2352 mm->numa_next_scan = now +
2353 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2357 * Enforce maximal scan/migration frequency..
2359 migrate = mm->numa_next_scan;
2360 if (time_before(now, migrate))
2363 if (p->numa_scan_period == 0) {
2364 p->numa_scan_period_max = task_scan_max(p);
2365 p->numa_scan_period = task_scan_min(p);
2368 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2369 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2373 * Delay this task enough that another task of this mm will likely win
2374 * the next time around.
2376 p->node_stamp += 2 * TICK_NSEC;
2378 start = mm->numa_scan_offset;
2379 pages = sysctl_numa_balancing_scan_size;
2380 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2381 virtpages = pages * 8; /* Scan up to this much virtual space */
2386 if (!down_read_trylock(&mm->mmap_sem))
2388 vma = find_vma(mm, start);
2390 reset_ptenuma_scan(p);
2394 for (; vma; vma = vma->vm_next) {
2395 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
2396 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
2401 * Shared library pages mapped by multiple processes are not
2402 * migrated as it is expected they are cache replicated. Avoid
2403 * hinting faults in read-only file-backed mappings or the vdso
2404 * as migrating the pages will be of marginal benefit.
2407 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2411 * Skip inaccessible VMAs to avoid any confusion between
2412 * PROT_NONE and NUMA hinting ptes
2414 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2418 start = max(start, vma->vm_start);
2419 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2420 end = min(end, vma->vm_end);
2421 nr_pte_updates = change_prot_numa(vma, start, end);
2424 * Try to scan sysctl_numa_balancing_size worth of
2425 * hpages that have at least one present PTE that
2426 * is not already pte-numa. If the VMA contains
2427 * areas that are unused or already full of prot_numa
2428 * PTEs, scan up to virtpages, to skip through those
2432 pages -= (end - start) >> PAGE_SHIFT;
2433 virtpages -= (end - start) >> PAGE_SHIFT;
2436 if (pages <= 0 || virtpages <= 0)
2440 } while (end != vma->vm_end);
2445 * It is possible to reach the end of the VMA list but the last few
2446 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2447 * would find the !migratable VMA on the next scan but not reset the
2448 * scanner to the start so check it now.
2451 mm->numa_scan_offset = start;
2453 reset_ptenuma_scan(p);
2454 up_read(&mm->mmap_sem);
2458 * Drive the periodic memory faults..
2460 void task_tick_numa(struct rq *rq, struct task_struct *curr)
2462 struct callback_head *work = &curr->numa_work;
2466 * We don't care about NUMA placement if we don't have memory.
2468 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2472 * Using runtime rather than walltime has the dual advantage that
2473 * we (mostly) drive the selection from busy threads and that the
2474 * task needs to have done some actual work before we bother with
2477 now = curr->se.sum_exec_runtime;
2478 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2480 if (now > curr->node_stamp + period) {
2481 if (!curr->node_stamp)
2482 curr->numa_scan_period = task_scan_min(curr);
2483 curr->node_stamp += period;
2485 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2486 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2487 task_work_add(curr, work, true);
2492 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2496 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2500 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2503 #endif /* CONFIG_NUMA_BALANCING */
2506 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2508 update_load_add(&cfs_rq->load, se->load.weight);
2509 if (!parent_entity(se))
2510 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
2512 if (entity_is_task(se)) {
2513 struct rq *rq = rq_of(cfs_rq);
2515 account_numa_enqueue(rq, task_of(se));
2516 list_add(&se->group_node, &rq->cfs_tasks);
2519 cfs_rq->nr_running++;
2523 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2525 update_load_sub(&cfs_rq->load, se->load.weight);
2526 if (!parent_entity(se))
2527 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
2528 if (entity_is_task(se)) {
2529 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
2530 list_del_init(&se->group_node);
2532 cfs_rq->nr_running--;
2535 #ifdef CONFIG_FAIR_GROUP_SCHED
2537 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2539 long tg_weight, load, shares;
2542 * This really should be: cfs_rq->avg.load_avg, but instead we use
2543 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2544 * the shares for small weight interactive tasks.
2546 load = scale_load_down(cfs_rq->load.weight);
2548 tg_weight = atomic_long_read(&tg->load_avg);
2550 /* Ensure tg_weight >= load */
2551 tg_weight -= cfs_rq->tg_load_avg_contrib;
2554 shares = (tg->shares * load);
2556 shares /= tg_weight;
2558 if (shares < MIN_SHARES)
2559 shares = MIN_SHARES;
2560 if (shares > tg->shares)
2561 shares = tg->shares;
2565 # else /* CONFIG_SMP */
2566 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2570 # endif /* CONFIG_SMP */
2572 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2573 unsigned long weight)
2576 /* commit outstanding execution time */
2577 if (cfs_rq->curr == se)
2578 update_curr(cfs_rq);
2579 account_entity_dequeue(cfs_rq, se);
2582 update_load_set(&se->load, weight);
2585 account_entity_enqueue(cfs_rq, se);
2588 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2590 static void update_cfs_shares(struct sched_entity *se)
2592 struct cfs_rq *cfs_rq = group_cfs_rq(se);
2593 struct task_group *tg;
2599 if (throttled_hierarchy(cfs_rq))
2605 if (likely(se->load.weight == tg->shares))
2608 shares = calc_cfs_shares(cfs_rq, tg);
2610 reweight_entity(cfs_rq_of(se), se, shares);
2613 #else /* CONFIG_FAIR_GROUP_SCHED */
2614 static inline void update_cfs_shares(struct sched_entity *se)
2617 #endif /* CONFIG_FAIR_GROUP_SCHED */
2620 /* Precomputed fixed inverse multiplies for multiplication by y^n */
2621 static const u32 runnable_avg_yN_inv[] = {
2622 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2623 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2624 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2625 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2626 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2627 0x85aac367, 0x82cd8698,
2631 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2632 * over-estimates when re-combining.
2634 static const u32 runnable_avg_yN_sum[] = {
2635 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2636 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2637 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2642 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2644 static __always_inline u64 decay_load(u64 val, u64 n)
2646 unsigned int local_n;
2650 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2653 /* after bounds checking we can collapse to 32-bit */
2657 * As y^PERIOD = 1/2, we can combine
2658 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2659 * With a look-up table which covers y^n (n<PERIOD)
2661 * To achieve constant time decay_load.
2663 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2664 val >>= local_n / LOAD_AVG_PERIOD;
2665 local_n %= LOAD_AVG_PERIOD;
2668 val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
2673 * For updates fully spanning n periods, the contribution to runnable
2674 * average will be: \Sum 1024*y^n
2676 * We can compute this reasonably efficiently by combining:
2677 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2679 static u32 __compute_runnable_contrib(u64 n)
2683 if (likely(n <= LOAD_AVG_PERIOD))
2684 return runnable_avg_yN_sum[n];
2685 else if (unlikely(n >= LOAD_AVG_MAX_N))
2686 return LOAD_AVG_MAX;
2688 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
2690 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
2691 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
2693 n -= LOAD_AVG_PERIOD;
2694 } while (n > LOAD_AVG_PERIOD);
2696 contrib = decay_load(contrib, n);
2697 return contrib + runnable_avg_yN_sum[n];
2700 #if (SCHED_LOAD_SHIFT - SCHED_LOAD_RESOLUTION) != 10 || SCHED_CAPACITY_SHIFT != 10
2701 #error "load tracking assumes 2^10 as unit"
2704 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
2707 * We can represent the historical contribution to runnable average as the
2708 * coefficients of a geometric series. To do this we sub-divide our runnable
2709 * history into segments of approximately 1ms (1024us); label the segment that
2710 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2712 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2714 * (now) (~1ms ago) (~2ms ago)
2716 * Let u_i denote the fraction of p_i that the entity was runnable.
2718 * We then designate the fractions u_i as our co-efficients, yielding the
2719 * following representation of historical load:
2720 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2722 * We choose y based on the with of a reasonably scheduling period, fixing:
2725 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2726 * approximately half as much as the contribution to load within the last ms
2729 * When a period "rolls over" and we have new u_0`, multiplying the previous
2730 * sum again by y is sufficient to update:
2731 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2732 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2734 static __always_inline int
2735 __update_load_avg(u64 now, int cpu, struct sched_avg *sa,
2736 unsigned long weight, int running, struct cfs_rq *cfs_rq)
2738 u64 delta, scaled_delta, periods;
2740 unsigned int delta_w, scaled_delta_w, decayed = 0;
2741 unsigned long scale_freq, scale_cpu;
2743 delta = now - sa->last_update_time;
2745 * This should only happen when time goes backwards, which it
2746 * unfortunately does during sched clock init when we swap over to TSC.
2748 if ((s64)delta < 0) {
2749 sa->last_update_time = now;
2754 * Use 1024ns as the unit of measurement since it's a reasonable
2755 * approximation of 1us and fast to compute.
2760 sa->last_update_time = now;
2762 scale_freq = arch_scale_freq_capacity(NULL, cpu);
2763 scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
2764 trace_sched_contrib_scale_f(cpu, scale_freq, scale_cpu);
2766 /* delta_w is the amount already accumulated against our next period */
2767 delta_w = sa->period_contrib;
2768 if (delta + delta_w >= 1024) {
2771 /* how much left for next period will start over, we don't know yet */
2772 sa->period_contrib = 0;
2775 * Now that we know we're crossing a period boundary, figure
2776 * out how much from delta we need to complete the current
2777 * period and accrue it.
2779 delta_w = 1024 - delta_w;
2780 scaled_delta_w = cap_scale(delta_w, scale_freq);
2782 sa->load_sum += weight * scaled_delta_w;
2784 cfs_rq->runnable_load_sum +=
2785 weight * scaled_delta_w;
2789 sa->util_sum += scaled_delta_w * scale_cpu;
2793 /* Figure out how many additional periods this update spans */
2794 periods = delta / 1024;
2797 sa->load_sum = decay_load(sa->load_sum, periods + 1);
2799 cfs_rq->runnable_load_sum =
2800 decay_load(cfs_rq->runnable_load_sum, periods + 1);
2802 sa->util_sum = decay_load((u64)(sa->util_sum), periods + 1);
2804 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
2805 contrib = __compute_runnable_contrib(periods);
2806 contrib = cap_scale(contrib, scale_freq);
2808 sa->load_sum += weight * contrib;
2810 cfs_rq->runnable_load_sum += weight * contrib;
2813 sa->util_sum += contrib * scale_cpu;
2816 /* Remainder of delta accrued against u_0` */
2817 scaled_delta = cap_scale(delta, scale_freq);
2819 sa->load_sum += weight * scaled_delta;
2821 cfs_rq->runnable_load_sum += weight * scaled_delta;
2824 sa->util_sum += scaled_delta * scale_cpu;
2826 sa->period_contrib += delta;
2829 sa->load_avg = div_u64(sa->load_sum, LOAD_AVG_MAX);
2831 cfs_rq->runnable_load_avg =
2832 div_u64(cfs_rq->runnable_load_sum, LOAD_AVG_MAX);
2834 sa->util_avg = sa->util_sum / LOAD_AVG_MAX;
2841 * Signed add and clamp on underflow.
2843 * Explicitly do a load-store to ensure the intermediate value never hits
2844 * memory. This allows lockless observations without ever seeing the negative
2847 #define add_positive(_ptr, _val) do { \
2848 typeof(_ptr) ptr = (_ptr); \
2849 typeof(_val) val = (_val); \
2850 typeof(*ptr) res, var = READ_ONCE(*ptr); \
2854 if (val < 0 && res > var) \
2857 WRITE_ONCE(*ptr, res); \
2860 #ifdef CONFIG_FAIR_GROUP_SCHED
2862 * update_tg_load_avg - update the tg's load avg
2863 * @cfs_rq: the cfs_rq whose avg changed
2864 * @force: update regardless of how small the difference
2866 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
2867 * However, because tg->load_avg is a global value there are performance
2870 * In order to avoid having to look at the other cfs_rq's, we use a
2871 * differential update where we store the last value we propagated. This in
2872 * turn allows skipping updates if the differential is 'small'.
2874 * Updating tg's load_avg is necessary before update_cfs_share() (which is
2875 * done) and effective_load() (which is not done because it is too costly).
2877 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
2879 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
2882 * No need to update load_avg for root_task_group as it is not used.
2884 if (cfs_rq->tg == &root_task_group)
2887 if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
2888 atomic_long_add(delta, &cfs_rq->tg->load_avg);
2889 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
2894 * Called within set_task_rq() right before setting a task's cpu. The
2895 * caller only guarantees p->pi_lock is held; no other assumptions,
2896 * including the state of rq->lock, should be made.
2898 void set_task_rq_fair(struct sched_entity *se,
2899 struct cfs_rq *prev, struct cfs_rq *next)
2901 if (!sched_feat(ATTACH_AGE_LOAD))
2905 * We are supposed to update the task to "current" time, then its up to
2906 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
2907 * getting what current time is, so simply throw away the out-of-date
2908 * time. This will result in the wakee task is less decayed, but giving
2909 * the wakee more load sounds not bad.
2911 if (se->avg.last_update_time && prev) {
2912 u64 p_last_update_time;
2913 u64 n_last_update_time;
2915 #ifndef CONFIG_64BIT
2916 u64 p_last_update_time_copy;
2917 u64 n_last_update_time_copy;
2920 p_last_update_time_copy = prev->load_last_update_time_copy;
2921 n_last_update_time_copy = next->load_last_update_time_copy;
2925 p_last_update_time = prev->avg.last_update_time;
2926 n_last_update_time = next->avg.last_update_time;
2928 } while (p_last_update_time != p_last_update_time_copy ||
2929 n_last_update_time != n_last_update_time_copy);
2931 p_last_update_time = prev->avg.last_update_time;
2932 n_last_update_time = next->avg.last_update_time;
2934 __update_load_avg(p_last_update_time, cpu_of(rq_of(prev)),
2935 &se->avg, 0, 0, NULL);
2936 se->avg.last_update_time = n_last_update_time;
2940 /* Take into account change of utilization of a child task group */
2942 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se)
2944 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
2945 long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
2947 /* Nothing to update */
2951 /* Set new sched_entity's utilization */
2952 se->avg.util_avg = gcfs_rq->avg.util_avg;
2953 se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
2955 /* Update parent cfs_rq utilization */
2956 add_positive(&cfs_rq->avg.util_avg, delta);
2957 cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
2960 /* Take into account change of load of a child task group */
2962 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se)
2964 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
2965 long delta, load = gcfs_rq->avg.load_avg;
2968 * If the load of group cfs_rq is null, the load of the
2969 * sched_entity will also be null so we can skip the formula
2974 /* Get tg's load and ensure tg_load > 0 */
2975 tg_load = atomic_long_read(&gcfs_rq->tg->load_avg) + 1;
2977 /* Ensure tg_load >= load and updated with current load*/
2978 tg_load -= gcfs_rq->tg_load_avg_contrib;
2982 * We need to compute a correction term in the case that the
2983 * task group is consuming more CPU than a task of equal
2984 * weight. A task with a weight equals to tg->shares will have
2985 * a load less or equal to scale_load_down(tg->shares).
2986 * Similarly, the sched_entities that represent the task group
2987 * at parent level, can't have a load higher than
2988 * scale_load_down(tg->shares). And the Sum of sched_entities'
2989 * load must be <= scale_load_down(tg->shares).
2991 if (tg_load > scale_load_down(gcfs_rq->tg->shares)) {
2992 /* scale gcfs_rq's load into tg's shares*/
2993 load *= scale_load_down(gcfs_rq->tg->shares);
2998 delta = load - se->avg.load_avg;
3000 /* Nothing to update */
3004 /* Set new sched_entity's load */
3005 se->avg.load_avg = load;
3006 se->avg.load_sum = se->avg.load_avg * LOAD_AVG_MAX;
3008 /* Update parent cfs_rq load */
3009 add_positive(&cfs_rq->avg.load_avg, delta);
3010 cfs_rq->avg.load_sum = cfs_rq->avg.load_avg * LOAD_AVG_MAX;
3013 * If the sched_entity is already enqueued, we also have to update the
3014 * runnable load avg.
3017 /* Update parent cfs_rq runnable_load_avg */
3018 add_positive(&cfs_rq->runnable_load_avg, delta);
3019 cfs_rq->runnable_load_sum = cfs_rq->runnable_load_avg * LOAD_AVG_MAX;
3023 static inline void set_tg_cfs_propagate(struct cfs_rq *cfs_rq)
3025 cfs_rq->propagate_avg = 1;
3028 static inline int test_and_clear_tg_cfs_propagate(struct sched_entity *se)
3030 struct cfs_rq *cfs_rq = group_cfs_rq(se);
3032 if (!cfs_rq->propagate_avg)
3035 cfs_rq->propagate_avg = 0;
3039 /* Update task and its cfs_rq load average */
3040 static inline int propagate_entity_load_avg(struct sched_entity *se)
3042 struct cfs_rq *cfs_rq;
3044 if (entity_is_task(se))
3047 if (!test_and_clear_tg_cfs_propagate(se))
3050 cfs_rq = cfs_rq_of(se);
3052 set_tg_cfs_propagate(cfs_rq);
3054 update_tg_cfs_util(cfs_rq, se);
3055 update_tg_cfs_load(cfs_rq, se);
3060 #else /* CONFIG_FAIR_GROUP_SCHED */
3062 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
3064 static inline int propagate_entity_load_avg(struct sched_entity *se)
3069 static inline void set_tg_cfs_propagate(struct cfs_rq *cfs_rq) {}
3071 #endif /* CONFIG_FAIR_GROUP_SCHED */
3073 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq)
3075 if (&this_rq()->cfs == cfs_rq) {
3077 * There are a few boundary cases this might miss but it should
3078 * get called often enough that that should (hopefully) not be
3079 * a real problem -- added to that it only calls on the local
3080 * CPU, so if we enqueue remotely we'll miss an update, but
3081 * the next tick/schedule should update.
3083 * It will not get called when we go idle, because the idle
3084 * thread is a different class (!fair), nor will the utilization
3085 * number include things like RT tasks.
3087 * As is, the util number is not freq-invariant (we'd have to
3088 * implement arch_scale_freq_capacity() for that).
3092 cpufreq_update_util(rq_of(cfs_rq), 0);
3096 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
3099 * Unsigned subtract and clamp on underflow.
3101 * Explicitly do a load-store to ensure the intermediate value never hits
3102 * memory. This allows lockless observations without ever seeing the negative
3105 #define sub_positive(_ptr, _val) do { \
3106 typeof(_ptr) ptr = (_ptr); \
3107 typeof(*ptr) val = (_val); \
3108 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3112 WRITE_ONCE(*ptr, res); \
3116 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3117 * @now: current time, as per cfs_rq_clock_task()
3118 * @cfs_rq: cfs_rq to update
3119 * @update_freq: should we call cfs_rq_util_change() or will the call do so
3121 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3122 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3123 * post_init_entity_util_avg().
3125 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3127 * Returns true if the load decayed or we removed load.
3129 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3130 * call update_tg_load_avg() when this function returns true.
3133 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3135 struct sched_avg *sa = &cfs_rq->avg;
3136 int decayed, removed = 0, removed_util = 0;
3138 if (atomic_long_read(&cfs_rq->removed_load_avg)) {
3139 s64 r = atomic_long_xchg(&cfs_rq->removed_load_avg, 0);
3140 sub_positive(&sa->load_avg, r);
3141 sub_positive(&sa->load_sum, r * LOAD_AVG_MAX);
3143 set_tg_cfs_propagate(cfs_rq);
3146 if (atomic_long_read(&cfs_rq->removed_util_avg)) {
3147 long r = atomic_long_xchg(&cfs_rq->removed_util_avg, 0);
3148 sub_positive(&sa->util_avg, r);
3149 sub_positive(&sa->util_sum, r * LOAD_AVG_MAX);
3151 set_tg_cfs_propagate(cfs_rq);
3154 decayed = __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
3155 scale_load_down(cfs_rq->load.weight), cfs_rq->curr != NULL, cfs_rq);
3157 #ifndef CONFIG_64BIT
3159 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3162 /* Trace CPU load, unless cfs_rq belongs to a non-root task_group */
3163 if (cfs_rq == &rq_of(cfs_rq)->cfs)
3164 trace_sched_load_avg_cpu(cpu_of(rq_of(cfs_rq)), cfs_rq);
3166 if (update_freq && (decayed || removed_util))
3167 cfs_rq_util_change(cfs_rq);
3169 return decayed || removed;
3173 * Optional action to be done while updating the load average
3175 #define UPDATE_TG 0x1
3176 #define SKIP_AGE_LOAD 0x2
3178 /* Update task and its cfs_rq load average */
3179 static inline void update_load_avg(struct sched_entity *se, int flags)
3181 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3182 u64 now = cfs_rq_clock_task(cfs_rq);
3183 int cpu = cpu_of(rq_of(cfs_rq));
3188 * Track task load average for carrying it to new CPU after migrated, and
3189 * track group sched_entity load average for task_h_load calc in migration
3191 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) {
3192 __update_load_avg(now, cpu, &se->avg,
3193 se->on_rq * scale_load_down(se->load.weight),
3194 cfs_rq->curr == se, NULL);
3197 decayed = update_cfs_rq_load_avg(now, cfs_rq, true);
3198 decayed |= propagate_entity_load_avg(se);
3200 if (decayed && (flags & UPDATE_TG))
3201 update_tg_load_avg(cfs_rq, 0);
3203 if (entity_is_task(se)) {
3204 #ifdef CONFIG_SCHED_WALT
3205 ptr = (void *)&(task_of(se)->ravg);
3207 trace_sched_load_avg_task(task_of(se), &se->avg, ptr);
3212 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3213 * @cfs_rq: cfs_rq to attach to
3214 * @se: sched_entity to attach
3216 * Must call update_cfs_rq_load_avg() before this, since we rely on
3217 * cfs_rq->avg.last_update_time being current.
3219 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3221 se->avg.last_update_time = cfs_rq->avg.last_update_time;
3222 cfs_rq->avg.load_avg += se->avg.load_avg;
3223 cfs_rq->avg.load_sum += se->avg.load_sum;
3224 cfs_rq->avg.util_avg += se->avg.util_avg;
3225 cfs_rq->avg.util_sum += se->avg.util_sum;
3226 set_tg_cfs_propagate(cfs_rq);
3228 cfs_rq_util_change(cfs_rq);
3232 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3233 * @cfs_rq: cfs_rq to detach from
3234 * @se: sched_entity to detach
3236 * Must call update_cfs_rq_load_avg() before this, since we rely on
3237 * cfs_rq->avg.last_update_time being current.
3239 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3242 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3243 sub_positive(&cfs_rq->avg.load_sum, se->avg.load_sum);
3244 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3245 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
3246 set_tg_cfs_propagate(cfs_rq);
3248 cfs_rq_util_change(cfs_rq);
3251 /* Add the load generated by se into cfs_rq's load average */
3253 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3255 struct sched_avg *sa = &se->avg;
3257 cfs_rq->runnable_load_avg += sa->load_avg;
3258 cfs_rq->runnable_load_sum += sa->load_sum;
3260 if (!sa->last_update_time) {
3261 attach_entity_load_avg(cfs_rq, se);
3262 update_tg_load_avg(cfs_rq, 0);
3266 /* Remove the runnable load generated by se from cfs_rq's runnable load average */
3268 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3270 cfs_rq->runnable_load_avg =
3271 max_t(long, cfs_rq->runnable_load_avg - se->avg.load_avg, 0);
3272 cfs_rq->runnable_load_sum =
3273 max_t(s64, cfs_rq->runnable_load_sum - se->avg.load_sum, 0);
3276 #ifndef CONFIG_64BIT
3277 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3279 u64 last_update_time_copy;
3280 u64 last_update_time;
3283 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3285 last_update_time = cfs_rq->avg.last_update_time;
3286 } while (last_update_time != last_update_time_copy);
3288 return last_update_time;
3291 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3293 return cfs_rq->avg.last_update_time;
3298 * Synchronize entity load avg of dequeued entity without locking
3301 void sync_entity_load_avg(struct sched_entity *se)
3303 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3304 u64 last_update_time;
3306 last_update_time = cfs_rq_last_update_time(cfs_rq);
3307 __update_load_avg(last_update_time, cpu_of(rq_of(cfs_rq)), &se->avg, 0, 0, NULL);
3311 * Task first catches up with cfs_rq, and then subtract
3312 * itself from the cfs_rq (task must be off the queue now).
3314 void remove_entity_load_avg(struct sched_entity *se)
3316 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3319 * tasks cannot exit without having gone through wake_up_new_task() ->
3320 * post_init_entity_util_avg() which will have added things to the
3321 * cfs_rq, so we can remove unconditionally.
3323 * Similarly for groups, they will have passed through
3324 * post_init_entity_util_avg() before unregister_sched_fair_group()
3328 sync_entity_load_avg(se);
3329 atomic_long_add(se->avg.load_avg, &cfs_rq->removed_load_avg);
3330 atomic_long_add(se->avg.util_avg, &cfs_rq->removed_util_avg);
3334 * Update the rq's load with the elapsed running time before entering
3335 * idle. if the last scheduled task is not a CFS task, idle_enter will
3336 * be the only way to update the runnable statistic.
3338 void idle_enter_fair(struct rq *this_rq)
3343 * Update the rq's load with the elapsed idle time before a task is
3344 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
3345 * be the only way to update the runnable statistic.
3347 void idle_exit_fair(struct rq *this_rq)
3351 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
3353 return cfs_rq->runnable_load_avg;
3356 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3358 return cfs_rq->avg.load_avg;
3361 static int idle_balance(struct rq *this_rq);
3363 #else /* CONFIG_SMP */
3366 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3371 #define UPDATE_TG 0x0
3372 #define SKIP_AGE_LOAD 0x0
3374 static inline void update_load_avg(struct sched_entity *se, int not_used1){}
3376 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3378 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3379 static inline void remove_entity_load_avg(struct sched_entity *se) {}
3382 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3384 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3386 static inline int idle_balance(struct rq *rq)
3391 #endif /* CONFIG_SMP */
3393 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
3395 #ifdef CONFIG_SCHEDSTATS
3396 struct task_struct *tsk = NULL;
3398 if (entity_is_task(se))
3401 if (se->statistics.sleep_start) {
3402 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
3407 if (unlikely(delta > se->statistics.sleep_max))
3408 se->statistics.sleep_max = delta;
3410 se->statistics.sleep_start = 0;
3411 se->statistics.sum_sleep_runtime += delta;
3414 account_scheduler_latency(tsk, delta >> 10, 1);
3415 trace_sched_stat_sleep(tsk, delta);
3418 if (se->statistics.block_start) {
3419 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
3424 if (unlikely(delta > se->statistics.block_max))
3425 se->statistics.block_max = delta;
3427 se->statistics.block_start = 0;
3428 se->statistics.sum_sleep_runtime += delta;
3431 if (tsk->in_iowait) {
3432 se->statistics.iowait_sum += delta;
3433 se->statistics.iowait_count++;
3434 trace_sched_stat_iowait(tsk, delta);
3437 trace_sched_stat_blocked(tsk, delta);
3438 trace_sched_blocked_reason(tsk);
3441 * Blocking time is in units of nanosecs, so shift by
3442 * 20 to get a milliseconds-range estimation of the
3443 * amount of time that the task spent sleeping:
3445 if (unlikely(prof_on == SLEEP_PROFILING)) {
3446 profile_hits(SLEEP_PROFILING,
3447 (void *)get_wchan(tsk),
3450 account_scheduler_latency(tsk, delta >> 10, 0);
3456 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
3458 #ifdef CONFIG_SCHED_DEBUG
3459 s64 d = se->vruntime - cfs_rq->min_vruntime;
3464 if (d > 3*sysctl_sched_latency)
3465 schedstat_inc(cfs_rq, nr_spread_over);
3470 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
3472 u64 vruntime = cfs_rq->min_vruntime;
3475 * The 'current' period is already promised to the current tasks,
3476 * however the extra weight of the new task will slow them down a
3477 * little, place the new task so that it fits in the slot that
3478 * stays open at the end.
3480 if (initial && sched_feat(START_DEBIT))
3481 vruntime += sched_vslice(cfs_rq, se);
3483 /* sleeps up to a single latency don't count. */
3485 unsigned long thresh = sysctl_sched_latency;
3488 * Halve their sleep time's effect, to allow
3489 * for a gentler effect of sleepers:
3491 if (sched_feat(GENTLE_FAIR_SLEEPERS))
3497 /* ensure we never gain time by being placed backwards. */
3498 se->vruntime = max_vruntime(se->vruntime, vruntime);
3501 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
3504 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3507 * Update the normalized vruntime before updating min_vruntime
3508 * through calling update_curr().
3510 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
3511 se->vruntime += cfs_rq->min_vruntime;
3514 * Update run-time statistics of the 'current'.
3516 update_curr(cfs_rq);
3517 update_load_avg(se, UPDATE_TG);
3518 enqueue_entity_load_avg(cfs_rq, se);
3519 update_cfs_shares(se);
3520 account_entity_enqueue(cfs_rq, se);
3522 if (flags & ENQUEUE_WAKEUP) {
3523 place_entity(cfs_rq, se, 0);
3524 enqueue_sleeper(cfs_rq, se);
3527 update_stats_enqueue(cfs_rq, se);
3528 check_spread(cfs_rq, se);
3529 if (se != cfs_rq->curr)
3530 __enqueue_entity(cfs_rq, se);
3533 if (cfs_rq->nr_running == 1) {
3534 list_add_leaf_cfs_rq(cfs_rq);
3535 check_enqueue_throttle(cfs_rq);
3539 static void __clear_buddies_last(struct sched_entity *se)
3541 for_each_sched_entity(se) {
3542 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3543 if (cfs_rq->last != se)
3546 cfs_rq->last = NULL;
3550 static void __clear_buddies_next(struct sched_entity *se)
3552 for_each_sched_entity(se) {
3553 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3554 if (cfs_rq->next != se)
3557 cfs_rq->next = NULL;
3561 static void __clear_buddies_skip(struct sched_entity *se)
3563 for_each_sched_entity(se) {
3564 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3565 if (cfs_rq->skip != se)
3568 cfs_rq->skip = NULL;
3572 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3574 if (cfs_rq->last == se)
3575 __clear_buddies_last(se);
3577 if (cfs_rq->next == se)
3578 __clear_buddies_next(se);
3580 if (cfs_rq->skip == se)
3581 __clear_buddies_skip(se);
3584 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3587 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3590 * Update run-time statistics of the 'current'.
3592 update_curr(cfs_rq);
3595 * When dequeuing a sched_entity, we must:
3596 * - Update loads to have both entity and cfs_rq synced with now.
3597 * - Substract its load from the cfs_rq->runnable_avg.
3598 * - Substract its previous weight from cfs_rq->load.weight.
3599 * - For group entity, update its weight to reflect the new share
3600 * of its group cfs_rq.
3602 update_load_avg(se, UPDATE_TG);
3603 dequeue_entity_load_avg(cfs_rq, se);
3605 update_stats_dequeue(cfs_rq, se);
3606 if (flags & DEQUEUE_SLEEP) {
3607 #ifdef CONFIG_SCHEDSTATS
3608 if (entity_is_task(se)) {
3609 struct task_struct *tsk = task_of(se);
3611 if (tsk->state & TASK_INTERRUPTIBLE)
3612 se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
3613 if (tsk->state & TASK_UNINTERRUPTIBLE)
3614 se->statistics.block_start = rq_clock(rq_of(cfs_rq));
3619 clear_buddies(cfs_rq, se);
3621 if (se != cfs_rq->curr)
3622 __dequeue_entity(cfs_rq, se);
3624 account_entity_dequeue(cfs_rq, se);
3627 * Normalize the entity after updating the min_vruntime because the
3628 * update can refer to the ->curr item and we need to reflect this
3629 * movement in our normalized position.
3631 if (!(flags & DEQUEUE_SLEEP))
3632 se->vruntime -= cfs_rq->min_vruntime;
3634 /* return excess runtime on last dequeue */
3635 return_cfs_rq_runtime(cfs_rq);
3637 update_min_vruntime(cfs_rq);
3638 update_cfs_shares(se);
3642 * Preempt the current task with a newly woken task if needed:
3645 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3647 unsigned long ideal_runtime, delta_exec;
3648 struct sched_entity *se;
3651 ideal_runtime = sched_slice(cfs_rq, curr);
3652 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
3653 if (delta_exec > ideal_runtime) {
3654 resched_curr(rq_of(cfs_rq));
3656 * The current task ran long enough, ensure it doesn't get
3657 * re-elected due to buddy favours.
3659 clear_buddies(cfs_rq, curr);
3664 * Ensure that a task that missed wakeup preemption by a
3665 * narrow margin doesn't have to wait for a full slice.
3666 * This also mitigates buddy induced latencies under load.
3668 if (delta_exec < sysctl_sched_min_granularity)
3671 se = __pick_first_entity(cfs_rq);
3672 delta = curr->vruntime - se->vruntime;
3677 if (delta > ideal_runtime)
3678 resched_curr(rq_of(cfs_rq));
3682 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
3684 /* 'current' is not kept within the tree. */
3687 * Any task has to be enqueued before it get to execute on
3688 * a CPU. So account for the time it spent waiting on the
3691 update_stats_wait_end(cfs_rq, se);
3692 __dequeue_entity(cfs_rq, se);
3693 update_load_avg(se, UPDATE_TG);
3696 update_stats_curr_start(cfs_rq, se);
3698 #ifdef CONFIG_SCHEDSTATS
3700 * Track our maximum slice length, if the CPU's load is at
3701 * least twice that of our own weight (i.e. dont track it
3702 * when there are only lesser-weight tasks around):
3704 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
3705 se->statistics.slice_max = max(se->statistics.slice_max,
3706 se->sum_exec_runtime - se->prev_sum_exec_runtime);
3709 se->prev_sum_exec_runtime = se->sum_exec_runtime;
3713 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
3716 * Pick the next process, keeping these things in mind, in this order:
3717 * 1) keep things fair between processes/task groups
3718 * 2) pick the "next" process, since someone really wants that to run
3719 * 3) pick the "last" process, for cache locality
3720 * 4) do not run the "skip" process, if something else is available
3722 static struct sched_entity *
3723 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3725 struct sched_entity *left = __pick_first_entity(cfs_rq);
3726 struct sched_entity *se;
3729 * If curr is set we have to see if its left of the leftmost entity
3730 * still in the tree, provided there was anything in the tree at all.
3732 if (!left || (curr && entity_before(curr, left)))
3735 se = left; /* ideally we run the leftmost entity */
3738 * Avoid running the skip buddy, if running something else can
3739 * be done without getting too unfair.
3741 if (cfs_rq->skip == se) {
3742 struct sched_entity *second;
3745 second = __pick_first_entity(cfs_rq);
3747 second = __pick_next_entity(se);
3748 if (!second || (curr && entity_before(curr, second)))
3752 if (second && wakeup_preempt_entity(second, left) < 1)
3757 * Prefer last buddy, try to return the CPU to a preempted task.
3759 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
3763 * Someone really wants this to run. If it's not unfair, run it.
3765 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
3768 clear_buddies(cfs_rq, se);
3773 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3775 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
3778 * If still on the runqueue then deactivate_task()
3779 * was not called and update_curr() has to be done:
3782 update_curr(cfs_rq);
3784 /* throttle cfs_rqs exceeding runtime */
3785 check_cfs_rq_runtime(cfs_rq);
3787 check_spread(cfs_rq, prev);
3789 update_stats_wait_start(cfs_rq, prev);
3790 /* Put 'current' back into the tree. */
3791 __enqueue_entity(cfs_rq, prev);
3792 /* in !on_rq case, update occurred at dequeue */
3793 update_load_avg(prev, 0);
3795 cfs_rq->curr = NULL;
3799 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
3802 * Update run-time statistics of the 'current'.
3804 update_curr(cfs_rq);
3807 * Ensure that runnable average is periodically updated.
3809 update_load_avg(curr, UPDATE_TG);
3810 update_cfs_shares(curr);
3812 #ifdef CONFIG_SCHED_HRTICK
3814 * queued ticks are scheduled to match the slice, so don't bother
3815 * validating it and just reschedule.
3818 resched_curr(rq_of(cfs_rq));
3822 * don't let the period tick interfere with the hrtick preemption
3824 if (!sched_feat(DOUBLE_TICK) &&
3825 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3829 if (cfs_rq->nr_running > 1)
3830 check_preempt_tick(cfs_rq, curr);
3834 /**************************************************
3835 * CFS bandwidth control machinery
3838 #ifdef CONFIG_CFS_BANDWIDTH
3840 #ifdef HAVE_JUMP_LABEL
3841 static struct static_key __cfs_bandwidth_used;
3843 static inline bool cfs_bandwidth_used(void)
3845 return static_key_false(&__cfs_bandwidth_used);
3848 void cfs_bandwidth_usage_inc(void)
3850 static_key_slow_inc(&__cfs_bandwidth_used);
3853 void cfs_bandwidth_usage_dec(void)
3855 static_key_slow_dec(&__cfs_bandwidth_used);
3857 #else /* HAVE_JUMP_LABEL */
3858 static bool cfs_bandwidth_used(void)
3863 void cfs_bandwidth_usage_inc(void) {}
3864 void cfs_bandwidth_usage_dec(void) {}
3865 #endif /* HAVE_JUMP_LABEL */
3868 * default period for cfs group bandwidth.
3869 * default: 0.1s, units: nanoseconds
3871 static inline u64 default_cfs_period(void)
3873 return 100000000ULL;
3876 static inline u64 sched_cfs_bandwidth_slice(void)
3878 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3882 * Replenish runtime according to assigned quota and update expiration time.
3883 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3884 * additional synchronization around rq->lock.
3886 * requires cfs_b->lock
3888 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
3892 if (cfs_b->quota == RUNTIME_INF)
3895 now = sched_clock_cpu(smp_processor_id());
3896 cfs_b->runtime = cfs_b->quota;
3897 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3900 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3902 return &tg->cfs_bandwidth;
3905 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3906 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3908 if (unlikely(cfs_rq->throttle_count))
3909 return cfs_rq->throttled_clock_task;
3911 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
3914 /* returns 0 on failure to allocate runtime */
3915 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3917 struct task_group *tg = cfs_rq->tg;
3918 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
3919 u64 amount = 0, min_amount, expires;
3921 /* note: this is a positive sum as runtime_remaining <= 0 */
3922 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3924 raw_spin_lock(&cfs_b->lock);
3925 if (cfs_b->quota == RUNTIME_INF)
3926 amount = min_amount;
3928 start_cfs_bandwidth(cfs_b);
3930 if (cfs_b->runtime > 0) {
3931 amount = min(cfs_b->runtime, min_amount);
3932 cfs_b->runtime -= amount;
3936 expires = cfs_b->runtime_expires;
3937 raw_spin_unlock(&cfs_b->lock);
3939 cfs_rq->runtime_remaining += amount;
3941 * we may have advanced our local expiration to account for allowed
3942 * spread between our sched_clock and the one on which runtime was
3945 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3946 cfs_rq->runtime_expires = expires;
3948 return cfs_rq->runtime_remaining > 0;
3952 * Note: This depends on the synchronization provided by sched_clock and the
3953 * fact that rq->clock snapshots this value.
3955 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3957 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3959 /* if the deadline is ahead of our clock, nothing to do */
3960 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
3963 if (cfs_rq->runtime_remaining < 0)
3967 * If the local deadline has passed we have to consider the
3968 * possibility that our sched_clock is 'fast' and the global deadline
3969 * has not truly expired.
3971 * Fortunately we can check determine whether this the case by checking
3972 * whether the global deadline has advanced. It is valid to compare
3973 * cfs_b->runtime_expires without any locks since we only care about
3974 * exact equality, so a partial write will still work.
3977 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
3978 /* extend local deadline, drift is bounded above by 2 ticks */
3979 cfs_rq->runtime_expires += TICK_NSEC;
3981 /* global deadline is ahead, expiration has passed */
3982 cfs_rq->runtime_remaining = 0;
3986 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3988 /* dock delta_exec before expiring quota (as it could span periods) */
3989 cfs_rq->runtime_remaining -= delta_exec;
3990 expire_cfs_rq_runtime(cfs_rq);
3992 if (likely(cfs_rq->runtime_remaining > 0))
3996 * if we're unable to extend our runtime we resched so that the active
3997 * hierarchy can be throttled
3999 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
4000 resched_curr(rq_of(cfs_rq));
4003 static __always_inline
4004 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4006 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4009 __account_cfs_rq_runtime(cfs_rq, delta_exec);
4012 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4014 return cfs_bandwidth_used() && cfs_rq->throttled;
4017 /* check whether cfs_rq, or any parent, is throttled */
4018 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4020 return cfs_bandwidth_used() && cfs_rq->throttle_count;
4024 * Ensure that neither of the group entities corresponding to src_cpu or
4025 * dest_cpu are members of a throttled hierarchy when performing group
4026 * load-balance operations.
4028 static inline int throttled_lb_pair(struct task_group *tg,
4029 int src_cpu, int dest_cpu)
4031 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4033 src_cfs_rq = tg->cfs_rq[src_cpu];
4034 dest_cfs_rq = tg->cfs_rq[dest_cpu];
4036 return throttled_hierarchy(src_cfs_rq) ||
4037 throttled_hierarchy(dest_cfs_rq);
4040 /* updated child weight may affect parent so we have to do this bottom up */
4041 static int tg_unthrottle_up(struct task_group *tg, void *data)
4043 struct rq *rq = data;
4044 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4046 cfs_rq->throttle_count--;
4048 if (!cfs_rq->throttle_count) {
4049 /* adjust cfs_rq_clock_task() */
4050 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
4051 cfs_rq->throttled_clock_task;
4058 static int tg_throttle_down(struct task_group *tg, void *data)
4060 struct rq *rq = data;
4061 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4063 /* group is entering throttled state, stop time */
4064 if (!cfs_rq->throttle_count)
4065 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4066 cfs_rq->throttle_count++;
4071 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
4073 struct rq *rq = rq_of(cfs_rq);
4074 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4075 struct sched_entity *se;
4076 long task_delta, dequeue = 1;
4079 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4081 /* freeze hierarchy runnable averages while throttled */
4083 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4086 task_delta = cfs_rq->h_nr_running;
4087 for_each_sched_entity(se) {
4088 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4089 /* throttled entity or throttle-on-deactivate */
4094 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
4095 qcfs_rq->h_nr_running -= task_delta;
4097 if (qcfs_rq->load.weight)
4102 sub_nr_running(rq, task_delta);
4104 cfs_rq->throttled = 1;
4105 cfs_rq->throttled_clock = rq_clock(rq);
4106 raw_spin_lock(&cfs_b->lock);
4107 empty = list_empty(&cfs_b->throttled_cfs_rq);
4110 * Add to the _head_ of the list, so that an already-started
4111 * distribute_cfs_runtime will not see us. If disribute_cfs_runtime is
4112 * not running add to the tail so that later runqueues don't get starved.
4114 if (cfs_b->distribute_running)
4115 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4117 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4120 * If we're the first throttled task, make sure the bandwidth
4124 start_cfs_bandwidth(cfs_b);
4126 raw_spin_unlock(&cfs_b->lock);
4129 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
4131 struct rq *rq = rq_of(cfs_rq);
4132 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4133 struct sched_entity *se;
4137 se = cfs_rq->tg->se[cpu_of(rq)];
4139 cfs_rq->throttled = 0;
4141 update_rq_clock(rq);
4143 raw_spin_lock(&cfs_b->lock);
4144 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4145 list_del_rcu(&cfs_rq->throttled_list);
4146 raw_spin_unlock(&cfs_b->lock);
4148 /* update hierarchical throttle state */
4149 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4151 if (!cfs_rq->load.weight)
4154 task_delta = cfs_rq->h_nr_running;
4155 for_each_sched_entity(se) {
4159 cfs_rq = cfs_rq_of(se);
4161 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4162 cfs_rq->h_nr_running += task_delta;
4164 if (cfs_rq_throttled(cfs_rq))
4169 add_nr_running(rq, task_delta);
4171 /* determine whether we need to wake up potentially idle cpu */
4172 if (rq->curr == rq->idle && rq->cfs.nr_running)
4176 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
4177 u64 remaining, u64 expires)
4179 struct cfs_rq *cfs_rq;
4181 u64 starting_runtime = remaining;
4184 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4186 struct rq *rq = rq_of(cfs_rq);
4188 raw_spin_lock(&rq->lock);
4189 if (!cfs_rq_throttled(cfs_rq))
4192 runtime = -cfs_rq->runtime_remaining + 1;
4193 if (runtime > remaining)
4194 runtime = remaining;
4195 remaining -= runtime;
4197 cfs_rq->runtime_remaining += runtime;
4198 cfs_rq->runtime_expires = expires;
4200 /* we check whether we're throttled above */
4201 if (cfs_rq->runtime_remaining > 0)
4202 unthrottle_cfs_rq(cfs_rq);
4205 raw_spin_unlock(&rq->lock);
4212 return starting_runtime - remaining;
4216 * Responsible for refilling a task_group's bandwidth and unthrottling its
4217 * cfs_rqs as appropriate. If there has been no activity within the last
4218 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4219 * used to track this state.
4221 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
4223 u64 runtime, runtime_expires;
4226 /* no need to continue the timer with no bandwidth constraint */
4227 if (cfs_b->quota == RUNTIME_INF)
4228 goto out_deactivate;
4230 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4231 cfs_b->nr_periods += overrun;
4234 * idle depends on !throttled (for the case of a large deficit), and if
4235 * we're going inactive then everything else can be deferred
4237 if (cfs_b->idle && !throttled)
4238 goto out_deactivate;
4240 __refill_cfs_bandwidth_runtime(cfs_b);
4243 /* mark as potentially idle for the upcoming period */
4248 /* account preceding periods in which throttling occurred */
4249 cfs_b->nr_throttled += overrun;
4251 runtime_expires = cfs_b->runtime_expires;
4254 * This check is repeated as we are holding onto the new bandwidth while
4255 * we unthrottle. This can potentially race with an unthrottled group
4256 * trying to acquire new bandwidth from the global pool. This can result
4257 * in us over-using our runtime if it is all used during this loop, but
4258 * only by limited amounts in that extreme case.
4260 while (throttled && cfs_b->runtime > 0 && !cfs_b->distribute_running) {
4261 runtime = cfs_b->runtime;
4262 cfs_b->distribute_running = 1;
4263 raw_spin_unlock(&cfs_b->lock);
4264 /* we can't nest cfs_b->lock while distributing bandwidth */
4265 runtime = distribute_cfs_runtime(cfs_b, runtime,
4267 raw_spin_lock(&cfs_b->lock);
4269 cfs_b->distribute_running = 0;
4270 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4272 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4276 * While we are ensured activity in the period following an
4277 * unthrottle, this also covers the case in which the new bandwidth is
4278 * insufficient to cover the existing bandwidth deficit. (Forcing the
4279 * timer to remain active while there are any throttled entities.)
4289 /* a cfs_rq won't donate quota below this amount */
4290 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
4291 /* minimum remaining period time to redistribute slack quota */
4292 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
4293 /* how long we wait to gather additional slack before distributing */
4294 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
4297 * Are we near the end of the current quota period?
4299 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4300 * hrtimer base being cleared by hrtimer_start. In the case of
4301 * migrate_hrtimers, base is never cleared, so we are fine.
4303 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
4305 struct hrtimer *refresh_timer = &cfs_b->period_timer;
4308 /* if the call-back is running a quota refresh is already occurring */
4309 if (hrtimer_callback_running(refresh_timer))
4312 /* is a quota refresh about to occur? */
4313 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
4314 if (remaining < min_expire)
4320 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
4322 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
4324 /* if there's a quota refresh soon don't bother with slack */
4325 if (runtime_refresh_within(cfs_b, min_left))
4328 hrtimer_start(&cfs_b->slack_timer,
4329 ns_to_ktime(cfs_bandwidth_slack_period),
4333 /* we know any runtime found here is valid as update_curr() precedes return */
4334 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4336 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4337 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
4339 if (slack_runtime <= 0)
4342 raw_spin_lock(&cfs_b->lock);
4343 if (cfs_b->quota != RUNTIME_INF &&
4344 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
4345 cfs_b->runtime += slack_runtime;
4347 /* we are under rq->lock, defer unthrottling using a timer */
4348 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
4349 !list_empty(&cfs_b->throttled_cfs_rq))
4350 start_cfs_slack_bandwidth(cfs_b);
4352 raw_spin_unlock(&cfs_b->lock);
4354 /* even if it's not valid for return we don't want to try again */
4355 cfs_rq->runtime_remaining -= slack_runtime;
4358 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4360 if (!cfs_bandwidth_used())
4363 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
4366 __return_cfs_rq_runtime(cfs_rq);
4370 * This is done with a timer (instead of inline with bandwidth return) since
4371 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4373 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
4375 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
4378 /* confirm we're still not at a refresh boundary */
4379 raw_spin_lock(&cfs_b->lock);
4380 if (cfs_b->distribute_running) {
4381 raw_spin_unlock(&cfs_b->lock);
4385 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
4386 raw_spin_unlock(&cfs_b->lock);
4390 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
4391 runtime = cfs_b->runtime;
4393 expires = cfs_b->runtime_expires;
4395 cfs_b->distribute_running = 1;
4397 raw_spin_unlock(&cfs_b->lock);
4402 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
4404 raw_spin_lock(&cfs_b->lock);
4405 if (expires == cfs_b->runtime_expires)
4406 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4407 cfs_b->distribute_running = 0;
4408 raw_spin_unlock(&cfs_b->lock);
4412 * When a group wakes up we want to make sure that its quota is not already
4413 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4414 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4416 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
4418 if (!cfs_bandwidth_used())
4421 /* Synchronize hierarchical throttle counter: */
4422 if (unlikely(!cfs_rq->throttle_uptodate)) {
4423 struct rq *rq = rq_of(cfs_rq);
4424 struct cfs_rq *pcfs_rq;
4425 struct task_group *tg;
4427 cfs_rq->throttle_uptodate = 1;
4429 /* Get closest up-to-date node, because leaves go first: */
4430 for (tg = cfs_rq->tg->parent; tg; tg = tg->parent) {
4431 pcfs_rq = tg->cfs_rq[cpu_of(rq)];
4432 if (pcfs_rq->throttle_uptodate)
4436 cfs_rq->throttle_count = pcfs_rq->throttle_count;
4437 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4441 /* an active group must be handled by the update_curr()->put() path */
4442 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
4445 /* ensure the group is not already throttled */
4446 if (cfs_rq_throttled(cfs_rq))
4449 /* update runtime allocation */
4450 account_cfs_rq_runtime(cfs_rq, 0);
4451 if (cfs_rq->runtime_remaining <= 0)
4452 throttle_cfs_rq(cfs_rq);
4455 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4456 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4458 if (!cfs_bandwidth_used())
4461 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
4465 * it's possible for a throttled entity to be forced into a running
4466 * state (e.g. set_curr_task), in this case we're finished.
4468 if (cfs_rq_throttled(cfs_rq))
4471 throttle_cfs_rq(cfs_rq);
4475 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
4477 struct cfs_bandwidth *cfs_b =
4478 container_of(timer, struct cfs_bandwidth, slack_timer);
4480 do_sched_cfs_slack_timer(cfs_b);
4482 return HRTIMER_NORESTART;
4485 extern const u64 max_cfs_quota_period;
4487 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
4489 struct cfs_bandwidth *cfs_b =
4490 container_of(timer, struct cfs_bandwidth, period_timer);
4495 raw_spin_lock(&cfs_b->lock);
4497 overrun = hrtimer_forward_now(timer, cfs_b->period);
4502 u64 new, old = ktime_to_ns(cfs_b->period);
4504 new = (old * 147) / 128; /* ~115% */
4505 new = min(new, max_cfs_quota_period);
4507 cfs_b->period = ns_to_ktime(new);
4509 /* since max is 1s, this is limited to 1e9^2, which fits in u64 */
4510 cfs_b->quota *= new;
4511 cfs_b->quota = div64_u64(cfs_b->quota, old);
4513 pr_warn_ratelimited(
4514 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us %lld, cfs_quota_us = %lld)\n",
4516 div_u64(new, NSEC_PER_USEC),
4517 div_u64(cfs_b->quota, NSEC_PER_USEC));
4519 /* reset count so we don't come right back in here */
4523 idle = do_sched_cfs_period_timer(cfs_b, overrun);
4526 cfs_b->period_active = 0;
4527 raw_spin_unlock(&cfs_b->lock);
4529 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
4532 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4534 raw_spin_lock_init(&cfs_b->lock);
4536 cfs_b->quota = RUNTIME_INF;
4537 cfs_b->period = ns_to_ktime(default_cfs_period());
4539 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4540 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
4541 cfs_b->period_timer.function = sched_cfs_period_timer;
4542 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4543 cfs_b->slack_timer.function = sched_cfs_slack_timer;
4544 cfs_b->distribute_running = 0;
4547 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4549 cfs_rq->runtime_enabled = 0;
4550 INIT_LIST_HEAD(&cfs_rq->throttled_list);
4553 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4555 lockdep_assert_held(&cfs_b->lock);
4557 if (!cfs_b->period_active) {
4558 cfs_b->period_active = 1;
4559 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
4560 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
4564 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4566 /* init_cfs_bandwidth() was not called */
4567 if (!cfs_b->throttled_cfs_rq.next)
4570 hrtimer_cancel(&cfs_b->period_timer);
4571 hrtimer_cancel(&cfs_b->slack_timer);
4574 static void __maybe_unused update_runtime_enabled(struct rq *rq)
4576 struct cfs_rq *cfs_rq;
4578 for_each_leaf_cfs_rq(rq, cfs_rq) {
4579 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
4581 raw_spin_lock(&cfs_b->lock);
4582 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4583 raw_spin_unlock(&cfs_b->lock);
4587 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
4589 struct cfs_rq *cfs_rq;
4591 for_each_leaf_cfs_rq(rq, cfs_rq) {
4592 if (!cfs_rq->runtime_enabled)
4596 * clock_task is not advancing so we just need to make sure
4597 * there's some valid quota amount
4599 cfs_rq->runtime_remaining = 1;
4601 * Offline rq is schedulable till cpu is completely disabled
4602 * in take_cpu_down(), so we prevent new cfs throttling here.
4604 cfs_rq->runtime_enabled = 0;
4606 if (cfs_rq_throttled(cfs_rq))
4607 unthrottle_cfs_rq(cfs_rq);
4611 #else /* CONFIG_CFS_BANDWIDTH */
4612 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4614 return rq_clock_task(rq_of(cfs_rq));
4617 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
4618 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
4619 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
4620 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4622 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4627 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4632 static inline int throttled_lb_pair(struct task_group *tg,
4633 int src_cpu, int dest_cpu)
4638 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4640 #ifdef CONFIG_FAIR_GROUP_SCHED
4641 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4644 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4648 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4649 static inline void update_runtime_enabled(struct rq *rq) {}
4650 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
4652 #endif /* CONFIG_CFS_BANDWIDTH */
4654 /**************************************************
4655 * CFS operations on tasks:
4658 #ifdef CONFIG_SCHED_HRTICK
4659 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
4661 struct sched_entity *se = &p->se;
4662 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4664 WARN_ON(task_rq(p) != rq);
4666 if (cfs_rq->nr_running > 1) {
4667 u64 slice = sched_slice(cfs_rq, se);
4668 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
4669 s64 delta = slice - ran;
4676 hrtick_start(rq, delta);
4681 * called from enqueue/dequeue and updates the hrtick when the
4682 * current task is from our class and nr_running is low enough
4685 static void hrtick_update(struct rq *rq)
4687 struct task_struct *curr = rq->curr;
4689 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
4692 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
4693 hrtick_start_fair(rq, curr);
4695 #else /* !CONFIG_SCHED_HRTICK */
4697 hrtick_start_fair(struct rq *rq, struct task_struct *p)
4701 static inline void hrtick_update(struct rq *rq)
4707 static bool __cpu_overutilized(int cpu, int delta);
4708 static bool cpu_overutilized(int cpu);
4709 unsigned long boosted_cpu_util(int cpu);
4711 #define boosted_cpu_util(cpu) cpu_util_freq(cpu)
4715 * The enqueue_task method is called before nr_running is
4716 * increased. Here we update the fair scheduling stats and
4717 * then put the task into the rbtree:
4720 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4722 struct cfs_rq *cfs_rq;
4723 struct sched_entity *se = &p->se;
4725 int task_new = flags & ENQUEUE_WAKEUP_NEW;
4729 * If in_iowait is set, the code below may not trigger any cpufreq
4730 * utilization updates, so do it here explicitly with the IOWAIT flag
4734 cpufreq_update_this_cpu(rq, SCHED_CPUFREQ_IOWAIT);
4736 for_each_sched_entity(se) {
4739 cfs_rq = cfs_rq_of(se);
4740 enqueue_entity(cfs_rq, se, flags);
4743 * end evaluation on encountering a throttled cfs_rq
4745 * note: in the case of encountering a throttled cfs_rq we will
4746 * post the final h_nr_running increment below.
4748 if (cfs_rq_throttled(cfs_rq))
4750 cfs_rq->h_nr_running++;
4751 walt_inc_cfs_cumulative_runnable_avg(cfs_rq, p);
4753 flags = ENQUEUE_WAKEUP;
4756 for_each_sched_entity(se) {
4757 cfs_rq = cfs_rq_of(se);
4758 cfs_rq->h_nr_running++;
4759 walt_inc_cfs_cumulative_runnable_avg(cfs_rq, p);
4761 if (cfs_rq_throttled(cfs_rq))
4764 update_load_avg(se, UPDATE_TG);
4765 update_cfs_shares(se);
4769 add_nr_running(rq, 1);
4774 * Update SchedTune accounting.
4776 * We do it before updating the CPU capacity to ensure the
4777 * boost value of the current task is accounted for in the
4778 * selection of the OPP.
4780 * We do it also in the case where we enqueue a throttled task;
4781 * we could argue that a throttled task should not boost a CPU,
4783 * a) properly implementing CPU boosting considering throttled
4784 * tasks will increase a lot the complexity of the solution
4785 * b) it's not easy to quantify the benefits introduced by
4786 * such a more complex solution.
4787 * Thus, for the time being we go for the simple solution and boost
4788 * also for throttled RQs.
4790 schedtune_enqueue_task(p, cpu_of(rq));
4793 walt_inc_cumulative_runnable_avg(rq, p);
4794 if (!task_new && !rq->rd->overutilized &&
4795 cpu_overutilized(rq->cpu)) {
4796 rq->rd->overutilized = true;
4797 trace_sched_overutilized(true);
4801 #endif /* CONFIG_SMP */
4805 static void set_next_buddy(struct sched_entity *se);
4808 * The dequeue_task method is called before nr_running is
4809 * decreased. We remove the task from the rbtree and
4810 * update the fair scheduling stats:
4812 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4814 struct cfs_rq *cfs_rq;
4815 struct sched_entity *se = &p->se;
4816 int task_sleep = flags & DEQUEUE_SLEEP;
4818 for_each_sched_entity(se) {
4819 cfs_rq = cfs_rq_of(se);
4820 dequeue_entity(cfs_rq, se, flags);
4823 * end evaluation on encountering a throttled cfs_rq
4825 * note: in the case of encountering a throttled cfs_rq we will
4826 * post the final h_nr_running decrement below.
4828 if (cfs_rq_throttled(cfs_rq))
4830 cfs_rq->h_nr_running--;
4831 walt_dec_cfs_cumulative_runnable_avg(cfs_rq, p);
4833 /* Don't dequeue parent if it has other entities besides us */
4834 if (cfs_rq->load.weight) {
4835 /* Avoid re-evaluating load for this entity: */
4836 se = parent_entity(se);
4838 * Bias pick_next to pick a task from this cfs_rq, as
4839 * p is sleeping when it is within its sched_slice.
4841 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
4845 flags |= DEQUEUE_SLEEP;
4848 for_each_sched_entity(se) {
4849 cfs_rq = cfs_rq_of(se);
4850 cfs_rq->h_nr_running--;
4851 walt_dec_cfs_cumulative_runnable_avg(cfs_rq, p);
4853 if (cfs_rq_throttled(cfs_rq))
4856 update_load_avg(se, UPDATE_TG);
4857 update_cfs_shares(se);
4861 sub_nr_running(rq, 1);
4866 * Update SchedTune accounting
4868 * We do it before updating the CPU capacity to ensure the
4869 * boost value of the current task is accounted for in the
4870 * selection of the OPP.
4872 schedtune_dequeue_task(p, cpu_of(rq));
4875 walt_dec_cumulative_runnable_avg(rq, p);
4876 #endif /* CONFIG_SMP */
4884 * per rq 'load' arrray crap; XXX kill this.
4888 * The exact cpuload at various idx values, calculated at every tick would be
4889 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
4891 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
4892 * on nth tick when cpu may be busy, then we have:
4893 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
4894 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
4896 * decay_load_missed() below does efficient calculation of
4897 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
4898 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
4900 * The calculation is approximated on a 128 point scale.
4901 * degrade_zero_ticks is the number of ticks after which load at any
4902 * particular idx is approximated to be zero.
4903 * degrade_factor is a precomputed table, a row for each load idx.
4904 * Each column corresponds to degradation factor for a power of two ticks,
4905 * based on 128 point scale.
4907 * row 2, col 3 (=12) says that the degradation at load idx 2 after
4908 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
4910 * With this power of 2 load factors, we can degrade the load n times
4911 * by looking at 1 bits in n and doing as many mult/shift instead of
4912 * n mult/shifts needed by the exact degradation.
4914 #define DEGRADE_SHIFT 7
4915 static const unsigned char
4916 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
4917 static const unsigned char
4918 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
4919 {0, 0, 0, 0, 0, 0, 0, 0},
4920 {64, 32, 8, 0, 0, 0, 0, 0},
4921 {96, 72, 40, 12, 1, 0, 0},
4922 {112, 98, 75, 43, 15, 1, 0},
4923 {120, 112, 98, 76, 45, 16, 2} };
4926 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
4927 * would be when CPU is idle and so we just decay the old load without
4928 * adding any new load.
4930 static unsigned long
4931 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
4935 if (!missed_updates)
4938 if (missed_updates >= degrade_zero_ticks[idx])
4942 return load >> missed_updates;
4944 while (missed_updates) {
4945 if (missed_updates % 2)
4946 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
4948 missed_updates >>= 1;
4955 * Update rq->cpu_load[] statistics. This function is usually called every
4956 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
4957 * every tick. We fix it up based on jiffies.
4959 static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
4960 unsigned long pending_updates)
4964 this_rq->nr_load_updates++;
4966 /* Update our load: */
4967 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
4968 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
4969 unsigned long old_load, new_load;
4971 /* scale is effectively 1 << i now, and >> i divides by scale */
4973 old_load = this_rq->cpu_load[i];
4974 old_load = decay_load_missed(old_load, pending_updates - 1, i);
4975 new_load = this_load;
4977 * Round up the averaging division if load is increasing. This
4978 * prevents us from getting stuck on 9 if the load is 10, for
4981 if (new_load > old_load)
4982 new_load += scale - 1;
4984 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
4987 sched_avg_update(this_rq);
4990 /* Used instead of source_load when we know the type == 0 */
4991 static unsigned long weighted_cpuload(const int cpu)
4993 return cfs_rq_runnable_load_avg(&cpu_rq(cpu)->cfs);
4996 #ifdef CONFIG_NO_HZ_COMMON
4998 * There is no sane way to deal with nohz on smp when using jiffies because the
4999 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
5000 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
5002 * Therefore we cannot use the delta approach from the regular tick since that
5003 * would seriously skew the load calculation. However we'll make do for those
5004 * updates happening while idle (nohz_idle_balance) or coming out of idle
5005 * (tick_nohz_idle_exit).
5007 * This means we might still be one tick off for nohz periods.
5011 * Called from nohz_idle_balance() to update the load ratings before doing the
5014 static void update_idle_cpu_load(struct rq *this_rq)
5016 unsigned long curr_jiffies = READ_ONCE(jiffies);
5017 unsigned long load = weighted_cpuload(cpu_of(this_rq));
5018 unsigned long pending_updates;
5021 * bail if there's load or we're actually up-to-date.
5023 if (load || curr_jiffies == this_rq->last_load_update_tick)
5026 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
5027 this_rq->last_load_update_tick = curr_jiffies;
5029 __update_cpu_load(this_rq, load, pending_updates);
5033 * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
5035 void update_cpu_load_nohz(void)
5037 struct rq *this_rq = this_rq();
5038 unsigned long curr_jiffies = READ_ONCE(jiffies);
5039 unsigned long pending_updates;
5041 if (curr_jiffies == this_rq->last_load_update_tick)
5044 raw_spin_lock(&this_rq->lock);
5045 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
5046 if (pending_updates) {
5047 this_rq->last_load_update_tick = curr_jiffies;
5049 * We were idle, this means load 0, the current load might be
5050 * !0 due to remote wakeups and the sort.
5052 __update_cpu_load(this_rq, 0, pending_updates);
5054 raw_spin_unlock(&this_rq->lock);
5056 #endif /* CONFIG_NO_HZ */
5059 * Called from scheduler_tick()
5061 void update_cpu_load_active(struct rq *this_rq)
5063 unsigned long load = weighted_cpuload(cpu_of(this_rq));
5065 * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
5067 this_rq->last_load_update_tick = jiffies;
5068 __update_cpu_load(this_rq, load, 1);
5072 * Return a low guess at the load of a migration-source cpu weighted
5073 * according to the scheduling class and "nice" value.
5075 * We want to under-estimate the load of migration sources, to
5076 * balance conservatively.
5078 static unsigned long source_load(int cpu, int type)
5080 struct rq *rq = cpu_rq(cpu);
5081 unsigned long total = weighted_cpuload(cpu);
5083 if (type == 0 || !sched_feat(LB_BIAS))
5086 return min(rq->cpu_load[type-1], total);
5090 * Return a high guess at the load of a migration-target cpu weighted
5091 * according to the scheduling class and "nice" value.
5093 static unsigned long target_load(int cpu, int type)
5095 struct rq *rq = cpu_rq(cpu);
5096 unsigned long total = weighted_cpuload(cpu);
5098 if (type == 0 || !sched_feat(LB_BIAS))
5101 return max(rq->cpu_load[type-1], total);
5105 static unsigned long cpu_avg_load_per_task(int cpu)
5107 struct rq *rq = cpu_rq(cpu);
5108 unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
5109 unsigned long load_avg = weighted_cpuload(cpu);
5112 return load_avg / nr_running;
5117 static void record_wakee(struct task_struct *p)
5120 * Rough decay (wiping) for cost saving, don't worry
5121 * about the boundary, really active task won't care
5124 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5125 current->wakee_flips >>= 1;
5126 current->wakee_flip_decay_ts = jiffies;
5129 if (current->last_wakee != p) {
5130 current->last_wakee = p;
5131 current->wakee_flips++;
5135 static void task_waking_fair(struct task_struct *p)
5137 struct sched_entity *se = &p->se;
5138 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5141 #ifndef CONFIG_64BIT
5142 u64 min_vruntime_copy;
5145 min_vruntime_copy = cfs_rq->min_vruntime_copy;
5147 min_vruntime = cfs_rq->min_vruntime;
5148 } while (min_vruntime != min_vruntime_copy);
5150 min_vruntime = cfs_rq->min_vruntime;
5153 se->vruntime -= min_vruntime;
5157 #ifdef CONFIG_FAIR_GROUP_SCHED
5159 * effective_load() calculates the load change as seen from the root_task_group
5161 * Adding load to a group doesn't make a group heavier, but can cause movement
5162 * of group shares between cpus. Assuming the shares were perfectly aligned one
5163 * can calculate the shift in shares.
5165 * Calculate the effective load difference if @wl is added (subtracted) to @tg
5166 * on this @cpu and results in a total addition (subtraction) of @wg to the
5167 * total group weight.
5169 * Given a runqueue weight distribution (rw_i) we can compute a shares
5170 * distribution (s_i) using:
5172 * s_i = rw_i / \Sum rw_j (1)
5174 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
5175 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
5176 * shares distribution (s_i):
5178 * rw_i = { 2, 4, 1, 0 }
5179 * s_i = { 2/7, 4/7, 1/7, 0 }
5181 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
5182 * task used to run on and the CPU the waker is running on), we need to
5183 * compute the effect of waking a task on either CPU and, in case of a sync
5184 * wakeup, compute the effect of the current task going to sleep.
5186 * So for a change of @wl to the local @cpu with an overall group weight change
5187 * of @wl we can compute the new shares distribution (s'_i) using:
5189 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
5191 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
5192 * differences in waking a task to CPU 0. The additional task changes the
5193 * weight and shares distributions like:
5195 * rw'_i = { 3, 4, 1, 0 }
5196 * s'_i = { 3/8, 4/8, 1/8, 0 }
5198 * We can then compute the difference in effective weight by using:
5200 * dw_i = S * (s'_i - s_i) (3)
5202 * Where 'S' is the group weight as seen by its parent.
5204 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
5205 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
5206 * 4/7) times the weight of the group.
5208 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5210 struct sched_entity *se = tg->se[cpu];
5212 if (!tg->parent) /* the trivial, non-cgroup case */
5215 for_each_sched_entity(se) {
5216 struct cfs_rq *cfs_rq = se->my_q;
5217 long W, w = cfs_rq_load_avg(cfs_rq);
5222 * W = @wg + \Sum rw_j
5224 W = wg + atomic_long_read(&tg->load_avg);
5226 /* Ensure \Sum rw_j >= rw_i */
5227 W -= cfs_rq->tg_load_avg_contrib;
5236 * wl = S * s'_i; see (2)
5239 wl = (w * (long)tg->shares) / W;
5244 * Per the above, wl is the new se->load.weight value; since
5245 * those are clipped to [MIN_SHARES, ...) do so now. See
5246 * calc_cfs_shares().
5248 if (wl < MIN_SHARES)
5252 * wl = dw_i = S * (s'_i - s_i); see (3)
5254 wl -= se->avg.load_avg;
5257 * Recursively apply this logic to all parent groups to compute
5258 * the final effective load change on the root group. Since
5259 * only the @tg group gets extra weight, all parent groups can
5260 * only redistribute existing shares. @wl is the shift in shares
5261 * resulting from this level per the above.
5270 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5278 * Returns the current capacity of cpu after applying both
5279 * cpu and freq scaling.
5281 unsigned long capacity_curr_of(int cpu)
5283 return cpu_rq(cpu)->cpu_capacity_orig *
5284 arch_scale_freq_capacity(NULL, cpu)
5285 >> SCHED_CAPACITY_SHIFT;
5288 static inline bool energy_aware(void)
5290 return sched_feat(ENERGY_AWARE);
5294 struct sched_group *sg_top;
5295 struct sched_group *sg_cap;
5303 struct task_struct *task;
5317 static int cpu_util_wake(int cpu, struct task_struct *p);
5320 * __cpu_norm_util() returns the cpu util relative to a specific capacity,
5321 * i.e. it's busy ratio, in the range [0..SCHED_LOAD_SCALE], which is useful for
5322 * energy calculations.
5324 * Since util is a scale-invariant utilization defined as:
5326 * util ~ (curr_freq/max_freq)*1024 * capacity_orig/1024 * running_time/time
5328 * the normalized util can be found using the specific capacity.
5330 * capacity = capacity_orig * curr_freq/max_freq
5332 * norm_util = running_time/time ~ util/capacity
5334 static unsigned long __cpu_norm_util(unsigned long util, unsigned long capacity)
5336 if (util >= capacity)
5337 return SCHED_CAPACITY_SCALE;
5339 return (util << SCHED_CAPACITY_SHIFT)/capacity;
5342 static unsigned long group_max_util(struct energy_env *eenv)
5344 unsigned long max_util = 0;
5348 for_each_cpu(cpu, sched_group_cpus(eenv->sg_cap)) {
5349 util = cpu_util_wake(cpu, eenv->task);
5352 * If we are looking at the target CPU specified by the eenv,
5353 * then we should add the (estimated) utilization of the task
5354 * assuming we will wake it up on that CPU.
5356 if (unlikely(cpu == eenv->trg_cpu))
5357 util += eenv->util_delta;
5359 max_util = max(max_util, util);
5366 * group_norm_util() returns the approximated group util relative to it's
5367 * current capacity (busy ratio), in the range [0..SCHED_LOAD_SCALE], for use
5368 * in energy calculations.
5370 * Since task executions may or may not overlap in time in the group the true
5371 * normalized util is between MAX(cpu_norm_util(i)) and SUM(cpu_norm_util(i))
5372 * when iterating over all CPUs in the group.
5373 * The latter estimate is used as it leads to a more pessimistic energy
5374 * estimate (more busy).
5377 long group_norm_util(struct energy_env *eenv, struct sched_group *sg)
5379 unsigned long capacity = sg->sge->cap_states[eenv->cap_idx].cap;
5380 unsigned long util, util_sum = 0;
5383 for_each_cpu(cpu, sched_group_cpus(sg)) {
5384 util = cpu_util_wake(cpu, eenv->task);
5387 * If we are looking at the target CPU specified by the eenv,
5388 * then we should add the (estimated) utilization of the task
5389 * assuming we will wake it up on that CPU.
5391 if (unlikely(cpu == eenv->trg_cpu))
5392 util += eenv->util_delta;
5394 util_sum += __cpu_norm_util(util, capacity);
5397 return min_t(unsigned long, util_sum, SCHED_CAPACITY_SCALE);
5400 static int find_new_capacity(struct energy_env *eenv,
5401 const struct sched_group_energy * const sge)
5403 int idx, max_idx = sge->nr_cap_states - 1;
5404 unsigned long util = group_max_util(eenv);
5406 /* default is max_cap if we don't find a match */
5407 eenv->cap_idx = max_idx;
5409 for (idx = 0; idx < sge->nr_cap_states; idx++) {
5410 if (sge->cap_states[idx].cap >= util) {
5411 eenv->cap_idx = idx;
5416 return eenv->cap_idx;
5419 static int group_idle_state(struct energy_env *eenv, struct sched_group *sg)
5421 int i, state = INT_MAX;
5422 int src_in_grp, dst_in_grp;
5425 /* Find the shallowest idle state in the sched group. */
5426 for_each_cpu(i, sched_group_cpus(sg))
5427 state = min(state, idle_get_state_idx(cpu_rq(i)));
5429 /* Take non-cpuidle idling into account (active idle/arch_cpu_idle()) */
5432 src_in_grp = cpumask_test_cpu(eenv->src_cpu, sched_group_cpus(sg));
5433 dst_in_grp = cpumask_test_cpu(eenv->dst_cpu, sched_group_cpus(sg));
5434 if (src_in_grp == dst_in_grp) {
5435 /* both CPUs under consideration are in the same group or not in
5436 * either group, migration should leave idle state the same.
5442 * Try to estimate if a deeper idle state is
5443 * achievable when we move the task.
5445 for_each_cpu(i, sched_group_cpus(sg)) {
5446 grp_util += cpu_util_wake(i, eenv->task);
5447 if (unlikely(i == eenv->trg_cpu))
5448 grp_util += eenv->util_delta;
5452 ((long)sg->sgc->max_capacity * (int)sg->group_weight)) {
5453 /* after moving, this group is at most partly
5454 * occupied, so it should have some idle time.
5456 int max_idle_state_idx = sg->sge->nr_idle_states - 2;
5457 int new_state = grp_util * max_idle_state_idx;
5459 /* group will have no util, use lowest state */
5460 new_state = max_idle_state_idx + 1;
5462 /* for partially idle, linearly map util to idle
5463 * states, excluding the lowest one. This does not
5464 * correspond to the state we expect to enter in
5465 * reality, but an indication of what might happen.
5467 new_state = min(max_idle_state_idx, (int)
5468 (new_state / sg->sgc->max_capacity));
5469 new_state = max_idle_state_idx - new_state;
5473 /* After moving, the group will be fully occupied
5474 * so assume it will not be idle at all.
5483 * sched_group_energy(): Computes the absolute energy consumption of cpus
5484 * belonging to the sched_group including shared resources shared only by
5485 * members of the group. Iterates over all cpus in the hierarchy below the
5486 * sched_group starting from the bottom working it's way up before going to
5487 * the next cpu until all cpus are covered at all levels. The current
5488 * implementation is likely to gather the same util statistics multiple times.
5489 * This can probably be done in a faster but more complex way.
5490 * Note: sched_group_energy() may fail when racing with sched_domain updates.
5492 static int sched_group_energy(struct energy_env *eenv)
5494 struct cpumask visit_cpus;
5495 u64 total_energy = 0;
5498 WARN_ON(!eenv->sg_top->sge);
5500 cpumask_copy(&visit_cpus, sched_group_cpus(eenv->sg_top));
5501 /* If a cpu is hotplugged in while we are in this function,
5502 * it does not appear in the existing visit_cpus mask
5503 * which came from the sched_group pointer of the
5504 * sched_domain pointed at by sd_ea for either the prev
5505 * or next cpu and was dereferenced in __energy_diff.
5506 * Since we will dereference sd_scs later as we iterate
5507 * through the CPUs we expect to visit, new CPUs can
5508 * be present which are not in the visit_cpus mask.
5509 * Guard this with cpu_count.
5511 cpu_count = cpumask_weight(&visit_cpus);
5513 while (!cpumask_empty(&visit_cpus)) {
5514 struct sched_group *sg_shared_cap = NULL;
5515 int cpu = cpumask_first(&visit_cpus);
5516 struct sched_domain *sd;
5519 * Is the group utilization affected by cpus outside this
5521 * This sd may have groups with cpus which were not present
5522 * when we took visit_cpus.
5524 sd = rcu_dereference(per_cpu(sd_scs, cpu));
5526 if (sd && sd->parent)
5527 sg_shared_cap = sd->parent->groups;
5529 for_each_domain(cpu, sd) {
5530 struct sched_group *sg = sd->groups;
5532 /* Has this sched_domain already been visited? */
5533 if (sd->child && group_first_cpu(sg) != cpu)
5537 unsigned long group_util;
5538 int sg_busy_energy, sg_idle_energy;
5539 int cap_idx, idle_idx;
5541 if (sg_shared_cap && sg_shared_cap->group_weight >= sg->group_weight)
5542 eenv->sg_cap = sg_shared_cap;
5546 cap_idx = find_new_capacity(eenv, sg->sge);
5548 if (sg->group_weight == 1) {
5549 /* Remove capacity of src CPU (before task move) */
5550 if (eenv->trg_cpu == eenv->src_cpu &&
5551 cpumask_test_cpu(eenv->src_cpu, sched_group_cpus(sg))) {
5552 eenv->cap.before = sg->sge->cap_states[cap_idx].cap;
5553 eenv->cap.delta -= eenv->cap.before;
5555 /* Add capacity of dst CPU (after task move) */
5556 if (eenv->trg_cpu == eenv->dst_cpu &&
5557 cpumask_test_cpu(eenv->dst_cpu, sched_group_cpus(sg))) {
5558 eenv->cap.after = sg->sge->cap_states[cap_idx].cap;
5559 eenv->cap.delta += eenv->cap.after;
5563 idle_idx = group_idle_state(eenv, sg);
5564 group_util = group_norm_util(eenv, sg);
5566 sg_busy_energy = (group_util * sg->sge->cap_states[cap_idx].power);
5567 sg_idle_energy = ((SCHED_LOAD_SCALE-group_util)
5568 * sg->sge->idle_states[idle_idx].power);
5570 total_energy += sg_busy_energy + sg_idle_energy;
5574 * cpu_count here is the number of
5575 * cpus we expect to visit in this
5576 * calculation. If we race against
5577 * hotplug, we can have extra cpus
5578 * added to the groups we are
5579 * iterating which do not appear in
5580 * the visit_cpus mask. In that case
5581 * we are not able to calculate energy
5582 * without restarting so we will bail
5583 * out and use prev_cpu this time.
5587 cpumask_xor(&visit_cpus, &visit_cpus, sched_group_cpus(sg));
5591 if (cpumask_equal(sched_group_cpus(sg), sched_group_cpus(eenv->sg_top)))
5594 } while (sg = sg->next, sg != sd->groups);
5598 * If we raced with hotplug and got an sd NULL-pointer;
5599 * returning a wrong energy estimation is better than
5600 * entering an infinite loop.
5601 * Specifically: If a cpu is unplugged after we took
5602 * the visit_cpus mask, it no longer has an sd_scs
5603 * pointer, so when we dereference it, we get NULL.
5605 if (cpumask_test_cpu(cpu, &visit_cpus))
5608 cpumask_clear_cpu(cpu, &visit_cpus);
5612 eenv->energy = total_energy >> SCHED_CAPACITY_SHIFT;
5616 static inline bool cpu_in_sg(struct sched_group *sg, int cpu)
5618 return cpu != -1 && cpumask_test_cpu(cpu, sched_group_cpus(sg));
5621 static inline unsigned long task_util(struct task_struct *p);
5624 * energy_diff(): Estimate the energy impact of changing the utilization
5625 * distribution. eenv specifies the change: utilisation amount, source, and
5626 * destination cpu. Source or destination cpu may be -1 in which case the
5627 * utilization is removed from or added to the system (e.g. task wake-up). If
5628 * both are specified, the utilization is migrated.
5630 static inline int __energy_diff(struct energy_env *eenv)
5632 struct sched_domain *sd;
5633 struct sched_group *sg;
5634 int sd_cpu = -1, energy_before = 0, energy_after = 0;
5637 struct energy_env eenv_before = {
5638 .util_delta = task_util(eenv->task),
5639 .src_cpu = eenv->src_cpu,
5640 .dst_cpu = eenv->dst_cpu,
5641 .trg_cpu = eenv->src_cpu,
5642 .nrg = { 0, 0, 0, 0},
5647 if (eenv->src_cpu == eenv->dst_cpu)
5650 sd_cpu = (eenv->src_cpu != -1) ? eenv->src_cpu : eenv->dst_cpu;
5651 sd = rcu_dereference(per_cpu(sd_ea, sd_cpu));
5654 return 0; /* Error */
5659 if (cpu_in_sg(sg, eenv->src_cpu) || cpu_in_sg(sg, eenv->dst_cpu)) {
5660 eenv_before.sg_top = eenv->sg_top = sg;
5662 if (sched_group_energy(&eenv_before))
5663 return 0; /* Invalid result abort */
5664 energy_before += eenv_before.energy;
5666 /* Keep track of SRC cpu (before) capacity */
5667 eenv->cap.before = eenv_before.cap.before;
5668 eenv->cap.delta = eenv_before.cap.delta;
5670 if (sched_group_energy(eenv))
5671 return 0; /* Invalid result abort */
5672 energy_after += eenv->energy;
5674 } while (sg = sg->next, sg != sd->groups);
5676 eenv->nrg.before = energy_before;
5677 eenv->nrg.after = energy_after;
5678 eenv->nrg.diff = eenv->nrg.after - eenv->nrg.before;
5680 #ifndef CONFIG_SCHED_TUNE
5681 trace_sched_energy_diff(eenv->task,
5682 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5683 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5684 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5685 eenv->nrg.delta, eenv->payoff);
5688 * Dead-zone margin preventing too many migrations.
5691 margin = eenv->nrg.before >> 6; /* ~1.56% */
5693 diff = eenv->nrg.after - eenv->nrg.before;
5695 eenv->nrg.diff = (abs(diff) < margin) ? 0 : eenv->nrg.diff;
5697 return eenv->nrg.diff;
5700 #ifdef CONFIG_SCHED_TUNE
5702 struct target_nrg schedtune_target_nrg;
5704 #ifdef CONFIG_CGROUP_SCHEDTUNE
5705 extern bool schedtune_initialized;
5706 #endif /* CONFIG_CGROUP_SCHEDTUNE */
5709 * System energy normalization
5710 * Returns the normalized value, in the range [0..SCHED_CAPACITY_SCALE],
5711 * corresponding to the specified energy variation.
5714 normalize_energy(int energy_diff)
5718 #ifdef CONFIG_CGROUP_SCHEDTUNE
5719 /* during early setup, we don't know the extents */
5720 if (unlikely(!schedtune_initialized))
5721 return energy_diff < 0 ? -1 : 1 ;
5722 #endif /* CONFIG_CGROUP_SCHEDTUNE */
5724 #ifdef CONFIG_SCHED_DEBUG
5728 /* Check for boundaries */
5729 max_delta = schedtune_target_nrg.max_power;
5730 max_delta -= schedtune_target_nrg.min_power;
5731 WARN_ON(abs(energy_diff) >= max_delta);
5735 /* Do scaling using positive numbers to increase the range */
5736 normalized_nrg = (energy_diff < 0) ? -energy_diff : energy_diff;
5738 /* Scale by energy magnitude */
5739 normalized_nrg <<= SCHED_CAPACITY_SHIFT;
5741 /* Normalize on max energy for target platform */
5742 normalized_nrg = reciprocal_divide(
5743 normalized_nrg, schedtune_target_nrg.rdiv);
5745 return (energy_diff < 0) ? -normalized_nrg : normalized_nrg;
5749 energy_diff(struct energy_env *eenv)
5751 int boost = schedtune_task_boost(eenv->task);
5754 /* Conpute "absolute" energy diff */
5755 __energy_diff(eenv);
5757 /* Return energy diff when boost margin is 0 */
5759 trace_sched_energy_diff(eenv->task,
5760 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5761 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5762 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5763 0, -eenv->nrg.diff);
5764 return eenv->nrg.diff;
5767 /* Compute normalized energy diff */
5768 nrg_delta = normalize_energy(eenv->nrg.diff);
5769 eenv->nrg.delta = nrg_delta;
5771 eenv->payoff = schedtune_accept_deltas(
5776 trace_sched_energy_diff(eenv->task,
5777 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5778 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5779 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5780 eenv->nrg.delta, eenv->payoff);
5783 * When SchedTune is enabled, the energy_diff() function will return
5784 * the computed energy payoff value. Since the energy_diff() return
5785 * value is expected to be negative by its callers, this evaluation
5786 * function return a negative value each time the evaluation return a
5787 * positive payoff, which is the condition for the acceptance of
5788 * a scheduling decision
5790 return -eenv->payoff;
5792 #else /* CONFIG_SCHED_TUNE */
5793 #define energy_diff(eenv) __energy_diff(eenv)
5797 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5798 * A waker of many should wake a different task than the one last awakened
5799 * at a frequency roughly N times higher than one of its wakees. In order
5800 * to determine whether we should let the load spread vs consolodating to
5801 * shared cache, we look for a minimum 'flip' frequency of llc_size in one
5802 * partner, and a factor of lls_size higher frequency in the other. With
5803 * both conditions met, we can be relatively sure that the relationship is
5804 * non-monogamous, with partner count exceeding socket size. Waker/wakee
5805 * being client/server, worker/dispatcher, interrupt source or whatever is
5806 * irrelevant, spread criteria is apparent partner count exceeds socket size.
5808 static int wake_wide(struct task_struct *p, int sibling_count_hint)
5810 unsigned int master = current->wakee_flips;
5811 unsigned int slave = p->wakee_flips;
5812 int llc_size = this_cpu_read(sd_llc_size);
5814 if (sibling_count_hint >= llc_size)
5818 swap(master, slave);
5819 if (slave < llc_size || master < slave * llc_size)
5824 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5825 int prev_cpu, int sync)
5827 s64 this_load, load;
5828 s64 this_eff_load, prev_eff_load;
5830 struct task_group *tg;
5831 unsigned long weight;
5835 this_cpu = smp_processor_id();
5836 load = source_load(prev_cpu, idx);
5837 this_load = target_load(this_cpu, idx);
5840 * If sync wakeup then subtract the (maximum possible)
5841 * effect of the currently running task from the load
5842 * of the current CPU:
5845 tg = task_group(current);
5846 weight = current->se.avg.load_avg;
5848 this_load += effective_load(tg, this_cpu, -weight, -weight);
5849 load += effective_load(tg, prev_cpu, 0, -weight);
5853 weight = p->se.avg.load_avg;
5856 * In low-load situations, where prev_cpu is idle and this_cpu is idle
5857 * due to the sync cause above having dropped this_load to 0, we'll
5858 * always have an imbalance, but there's really nothing you can do
5859 * about that, so that's good too.
5861 * Otherwise check if either cpus are near enough in load to allow this
5862 * task to be woken on this_cpu.
5864 this_eff_load = 100;
5865 this_eff_load *= capacity_of(prev_cpu);
5867 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
5868 prev_eff_load *= capacity_of(this_cpu);
5870 if (this_load > 0) {
5871 this_eff_load *= this_load +
5872 effective_load(tg, this_cpu, weight, weight);
5874 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
5877 balanced = this_eff_load <= prev_eff_load;
5879 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
5884 schedstat_inc(sd, ttwu_move_affine);
5885 schedstat_inc(p, se.statistics.nr_wakeups_affine);
5890 static inline unsigned long task_util(struct task_struct *p)
5892 #ifdef CONFIG_SCHED_WALT
5893 if (!walt_disabled && sysctl_sched_use_walt_task_util) {
5894 unsigned long demand = p->ravg.demand;
5895 return (demand << 10) / walt_ravg_window;
5898 return p->se.avg.util_avg;
5901 static inline unsigned long boosted_task_util(struct task_struct *task);
5903 static inline bool __task_fits(struct task_struct *p, int cpu, int util)
5905 unsigned long capacity = capacity_of(cpu);
5907 util += boosted_task_util(p);
5909 return (capacity * 1024) > (util * capacity_margin);
5912 static inline bool task_fits_max(struct task_struct *p, int cpu)
5914 unsigned long capacity = capacity_of(cpu);
5915 unsigned long max_capacity = cpu_rq(cpu)->rd->max_cpu_capacity.val;
5917 if (capacity == max_capacity)
5920 if (capacity * capacity_margin > max_capacity * 1024)
5923 return __task_fits(p, cpu, 0);
5926 static bool __cpu_overutilized(int cpu, int delta)
5928 return (capacity_of(cpu) * 1024) < ((cpu_util(cpu) + delta) * capacity_margin);
5931 static bool cpu_overutilized(int cpu)
5933 return __cpu_overutilized(cpu, 0);
5936 #ifdef CONFIG_SCHED_TUNE
5938 struct reciprocal_value schedtune_spc_rdiv;
5941 schedtune_margin(unsigned long signal, long boost)
5943 long long margin = 0;
5946 * Signal proportional compensation (SPC)
5948 * The Boost (B) value is used to compute a Margin (M) which is
5949 * proportional to the complement of the original Signal (S):
5950 * M = B * (SCHED_CAPACITY_SCALE - S)
5951 * The obtained M could be used by the caller to "boost" S.
5954 margin = SCHED_CAPACITY_SCALE - signal;
5957 margin = -signal * boost;
5959 margin = reciprocal_divide(margin, schedtune_spc_rdiv);
5967 schedtune_cpu_margin(unsigned long util, int cpu)
5969 int boost = schedtune_cpu_boost(cpu);
5974 return schedtune_margin(util, boost);
5978 schedtune_task_margin(struct task_struct *task)
5980 int boost = schedtune_task_boost(task);
5987 util = task_util(task);
5988 margin = schedtune_margin(util, boost);
5993 #else /* CONFIG_SCHED_TUNE */
5996 schedtune_cpu_margin(unsigned long util, int cpu)
6002 schedtune_task_margin(struct task_struct *task)
6007 #endif /* CONFIG_SCHED_TUNE */
6010 boosted_cpu_util(int cpu)
6012 unsigned long util = cpu_util_freq(cpu);
6013 long margin = schedtune_cpu_margin(util, cpu);
6015 trace_sched_boost_cpu(cpu, util, margin);
6017 return util + margin;
6020 static inline unsigned long
6021 boosted_task_util(struct task_struct *task)
6023 unsigned long util = task_util(task);
6024 long margin = schedtune_task_margin(task);
6026 trace_sched_boost_task(task, util, margin);
6028 return util + margin;
6031 static unsigned long capacity_spare_wake(int cpu, struct task_struct *p)
6033 return max_t(long, capacity_of(cpu) - cpu_util_wake(cpu, p), 0);
6037 * find_idlest_group finds and returns the least busy CPU group within the
6040 * Assumes p is allowed on at least one CPU in sd.
6042 static struct sched_group *
6043 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
6044 int this_cpu, int sd_flag)
6046 struct sched_group *idlest = NULL, *group = sd->groups;
6047 struct sched_group *most_spare_sg = NULL;
6048 unsigned long min_load = ULONG_MAX, this_load = ULONG_MAX;
6049 unsigned long most_spare = 0, this_spare = 0;
6050 int load_idx = sd->forkexec_idx;
6051 int imbalance = 100 + (sd->imbalance_pct-100)/2;
6053 if (sd_flag & SD_BALANCE_WAKE)
6054 load_idx = sd->wake_idx;
6057 unsigned long load, avg_load, spare_cap, max_spare_cap;
6061 /* Skip over this group if it has no CPUs allowed */
6062 if (!cpumask_intersects(sched_group_cpus(group),
6063 tsk_cpus_allowed(p)))
6066 local_group = cpumask_test_cpu(this_cpu,
6067 sched_group_cpus(group));
6070 * Tally up the load of all CPUs in the group and find
6071 * the group containing the CPU with most spare capacity.
6076 for_each_cpu(i, sched_group_cpus(group)) {
6077 /* Bias balancing toward cpus of our domain */
6079 load = source_load(i, load_idx);
6081 load = target_load(i, load_idx);
6085 spare_cap = capacity_spare_wake(i, p);
6087 if (spare_cap > max_spare_cap)
6088 max_spare_cap = spare_cap;
6091 /* Adjust by relative CPU capacity of the group */
6092 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
6095 this_load = avg_load;
6096 this_spare = max_spare_cap;
6098 if (avg_load < min_load) {
6099 min_load = avg_load;
6103 if (most_spare < max_spare_cap) {
6104 most_spare = max_spare_cap;
6105 most_spare_sg = group;
6108 } while (group = group->next, group != sd->groups);
6111 * The cross-over point between using spare capacity or least load
6112 * is too conservative for high utilization tasks on partially
6113 * utilized systems if we require spare_capacity > task_util(p),
6114 * so we allow for some task stuffing by using
6115 * spare_capacity > task_util(p)/2.
6117 * Spare capacity can't be used for fork because the utilization has
6118 * not been set yet, we must first select a rq to compute the initial
6121 if (sd_flag & SD_BALANCE_FORK)
6124 if (this_spare > task_util(p) / 2 &&
6125 imbalance*this_spare > 100*most_spare)
6127 else if (most_spare > task_util(p) / 2)
6128 return most_spare_sg;
6131 if (!idlest || 100*this_load < imbalance*min_load)
6137 * find_idlest_group_cpu - find the idlest cpu among the cpus in group.
6140 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6142 unsigned long load, min_load = ULONG_MAX;
6143 unsigned int min_exit_latency = UINT_MAX;
6144 u64 latest_idle_timestamp = 0;
6145 int least_loaded_cpu = this_cpu;
6146 int shallowest_idle_cpu = -1;
6149 /* Check if we have any choice: */
6150 if (group->group_weight == 1)
6151 return cpumask_first(sched_group_cpus(group));
6153 /* Traverse only the allowed CPUs */
6154 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
6156 struct rq *rq = cpu_rq(i);
6157 struct cpuidle_state *idle = idle_get_state(rq);
6158 if (idle && idle->exit_latency < min_exit_latency) {
6160 * We give priority to a CPU whose idle state
6161 * has the smallest exit latency irrespective
6162 * of any idle timestamp.
6164 min_exit_latency = idle->exit_latency;
6165 latest_idle_timestamp = rq->idle_stamp;
6166 shallowest_idle_cpu = i;
6167 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6168 rq->idle_stamp > latest_idle_timestamp) {
6170 * If equal or no active idle state, then
6171 * the most recently idled CPU might have
6174 latest_idle_timestamp = rq->idle_stamp;
6175 shallowest_idle_cpu = i;
6177 } else if (shallowest_idle_cpu == -1) {
6178 load = weighted_cpuload(i);
6179 if (load < min_load || (load == min_load && i == this_cpu)) {
6181 least_loaded_cpu = i;
6186 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6189 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6190 int cpu, int prev_cpu, int sd_flag)
6193 int wu = sd_flag & SD_BALANCE_WAKE;
6197 schedstat_inc(p, se.statistics.nr_wakeups_cas_attempts);
6198 schedstat_inc(this_rq(), eas_stats.cas_attempts);
6201 if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
6205 struct sched_group *group;
6206 struct sched_domain *tmp;
6210 schedstat_inc(sd, eas_stats.cas_attempts);
6212 if (!(sd->flags & sd_flag)) {
6217 group = find_idlest_group(sd, p, cpu, sd_flag);
6223 new_cpu = find_idlest_group_cpu(group, p, cpu);
6224 if (new_cpu == cpu) {
6225 /* Now try balancing at a lower domain level of cpu */
6230 /* Now try balancing at a lower domain level of new_cpu */
6231 cpu = cas_cpu = new_cpu;
6232 weight = sd->span_weight;
6234 for_each_domain(cpu, tmp) {
6235 if (weight <= tmp->span_weight)
6237 if (tmp->flags & sd_flag)
6240 /* while loop will break here if sd == NULL */
6243 if (wu && (cas_cpu >= 0)) {
6244 schedstat_inc(p, se.statistics.nr_wakeups_cas_count);
6245 schedstat_inc(this_rq(), eas_stats.cas_count);
6252 * Try and locate an idle CPU in the sched_domain.
6254 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6256 struct sched_domain *sd;
6257 struct sched_group *sg;
6258 int best_idle_cpu = -1;
6259 int best_idle_cstate = INT_MAX;
6260 unsigned long best_idle_capacity = ULONG_MAX;
6262 schedstat_inc(p, se.statistics.nr_wakeups_sis_attempts);
6263 schedstat_inc(this_rq(), eas_stats.sis_attempts);
6265 if (!sysctl_sched_cstate_aware) {
6266 if (idle_cpu(target)) {
6267 schedstat_inc(p, se.statistics.nr_wakeups_sis_idle);
6268 schedstat_inc(this_rq(), eas_stats.sis_idle);
6273 * If the prevous cpu is cache affine and idle, don't be stupid.
6275 if (prev != target && cpus_share_cache(prev, target) && idle_cpu(prev)) {
6276 schedstat_inc(p, se.statistics.nr_wakeups_sis_cache_affine);
6277 schedstat_inc(this_rq(), eas_stats.sis_cache_affine);
6283 * Otherwise, iterate the domains and find an elegible idle cpu.
6285 sd = rcu_dereference(per_cpu(sd_llc, target));
6286 for_each_lower_domain(sd) {
6290 if (!cpumask_intersects(sched_group_cpus(sg),
6291 tsk_cpus_allowed(p)))
6294 if (sysctl_sched_cstate_aware) {
6295 for_each_cpu_and(i, tsk_cpus_allowed(p), sched_group_cpus(sg)) {
6296 int idle_idx = idle_get_state_idx(cpu_rq(i));
6297 unsigned long new_usage = boosted_task_util(p);
6298 unsigned long capacity_orig = capacity_orig_of(i);
6300 if (new_usage > capacity_orig || !idle_cpu(i))
6303 if (i == target && new_usage <= capacity_curr_of(target)) {
6304 schedstat_inc(p, se.statistics.nr_wakeups_sis_suff_cap);
6305 schedstat_inc(this_rq(), eas_stats.sis_suff_cap);
6306 schedstat_inc(sd, eas_stats.sis_suff_cap);
6310 if (idle_idx < best_idle_cstate &&
6311 capacity_orig <= best_idle_capacity) {
6313 best_idle_cstate = idle_idx;
6314 best_idle_capacity = capacity_orig;
6318 for_each_cpu(i, sched_group_cpus(sg)) {
6319 if (i == target || !idle_cpu(i))
6323 target = cpumask_first_and(sched_group_cpus(sg),
6324 tsk_cpus_allowed(p));
6325 schedstat_inc(p, se.statistics.nr_wakeups_sis_idle_cpu);
6326 schedstat_inc(this_rq(), eas_stats.sis_idle_cpu);
6327 schedstat_inc(sd, eas_stats.sis_idle_cpu);
6332 } while (sg != sd->groups);
6335 if (best_idle_cpu >= 0)
6336 target = best_idle_cpu;
6339 schedstat_inc(p, se.statistics.nr_wakeups_sis_count);
6340 schedstat_inc(this_rq(), eas_stats.sis_count);
6346 * cpu_util_wake: Compute cpu utilization with any contributions from
6347 * the waking task p removed. check_for_migration() looks for a better CPU of
6348 * rq->curr. For that case we should return cpu util with contributions from
6349 * currently running task p removed.
6351 static int cpu_util_wake(int cpu, struct task_struct *p)
6353 unsigned long util, capacity;
6355 #ifdef CONFIG_SCHED_WALT
6357 * WALT does not decay idle tasks in the same manner
6358 * as PELT, so it makes little sense to subtract task
6359 * utilization from cpu utilization. Instead just use
6360 * cpu_util for this case.
6362 if (!walt_disabled && sysctl_sched_use_walt_cpu_util &&
6363 p->state == TASK_WAKING)
6364 return cpu_util(cpu);
6366 /* Task has no contribution or is new */
6367 if (cpu != task_cpu(p) || !p->se.avg.last_update_time)
6368 return cpu_util(cpu);
6370 capacity = capacity_orig_of(cpu);
6371 util = max_t(long, cpu_util(cpu) - task_util(p), 0);
6373 return (util >= capacity) ? capacity : util;
6376 static int start_cpu(bool boosted)
6378 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6380 return boosted ? rd->max_cap_orig_cpu : rd->min_cap_orig_cpu;
6383 static inline int find_best_target(struct task_struct *p, int *backup_cpu,
6384 bool boosted, bool prefer_idle)
6386 unsigned long best_idle_min_cap_orig = ULONG_MAX;
6387 unsigned long min_util = boosted_task_util(p);
6388 unsigned long target_capacity = ULONG_MAX;
6389 unsigned long min_wake_util = ULONG_MAX;
6390 unsigned long target_max_spare_cap = 0;
6391 unsigned long best_active_util = ULONG_MAX;
6392 int best_idle_cstate = INT_MAX;
6393 struct sched_domain *sd;
6394 struct sched_group *sg;
6395 int best_active_cpu = -1;
6396 int best_idle_cpu = -1;
6397 int target_cpu = -1;
6402 schedstat_inc(p, se.statistics.nr_wakeups_fbt_attempts);
6403 schedstat_inc(this_rq(), eas_stats.fbt_attempts);
6405 /* Find start CPU based on boost value */
6406 cpu = start_cpu(boosted);
6408 schedstat_inc(p, se.statistics.nr_wakeups_fbt_no_cpu);
6409 schedstat_inc(this_rq(), eas_stats.fbt_no_cpu);
6413 /* Find SD for the start CPU */
6414 sd = rcu_dereference(per_cpu(sd_ea, cpu));
6416 schedstat_inc(p, se.statistics.nr_wakeups_fbt_no_sd);
6417 schedstat_inc(this_rq(), eas_stats.fbt_no_sd);
6421 /* Scan CPUs in all SDs */
6424 for_each_cpu_and(i, tsk_cpus_allowed(p), sched_group_cpus(sg)) {
6425 unsigned long capacity_curr = capacity_curr_of(i);
6426 unsigned long capacity_orig = capacity_orig_of(i);
6427 unsigned long wake_util, new_util;
6432 if (walt_cpu_high_irqload(i))
6436 * p's blocked utilization is still accounted for on prev_cpu
6437 * so prev_cpu will receive a negative bias due to the double
6438 * accounting. However, the blocked utilization may be zero.
6440 wake_util = cpu_util_wake(i, p);
6441 new_util = wake_util + task_util(p);
6444 * Ensure minimum capacity to grant the required boost.
6445 * The target CPU can be already at a capacity level higher
6446 * than the one required to boost the task.
6448 new_util = max(min_util, new_util);
6449 if (new_util > capacity_orig)
6453 * Case A) Latency sensitive tasks
6455 * Unconditionally favoring tasks that prefer idle CPU to
6459 * - an idle CPU, whatever its idle_state is, since
6460 * the first CPUs we explore are more likely to be
6461 * reserved for latency sensitive tasks.
6462 * - a non idle CPU where the task fits in its current
6463 * capacity and has the maximum spare capacity.
6464 * - a non idle CPU with lower contention from other
6465 * tasks and running at the lowest possible OPP.
6467 * The last two goals tries to favor a non idle CPU
6468 * where the task can run as if it is "almost alone".
6469 * A maximum spare capacity CPU is favoured since
6470 * the task already fits into that CPU's capacity
6471 * without waiting for an OPP chance.
6473 * The following code path is the only one in the CPUs
6474 * exploration loop which is always used by
6475 * prefer_idle tasks. It exits the loop with wither a
6476 * best_active_cpu or a target_cpu which should
6477 * represent an optimal choice for latency sensitive
6483 * Case A.1: IDLE CPU
6484 * Return the first IDLE CPU we find.
6487 schedstat_inc(p, se.statistics.nr_wakeups_fbt_pref_idle);
6488 schedstat_inc(this_rq(), eas_stats.fbt_pref_idle);
6490 trace_sched_find_best_target(p,
6491 prefer_idle, min_util,
6493 best_active_cpu, i);
6499 * Case A.2: Target ACTIVE CPU
6500 * Favor CPUs with max spare capacity.
6502 if ((capacity_curr > new_util) &&
6503 (capacity_orig - new_util > target_max_spare_cap)) {
6504 target_max_spare_cap = capacity_orig - new_util;
6508 if (target_cpu != -1)
6513 * Case A.3: Backup ACTIVE CPU
6515 * - lower utilization due to other tasks
6516 * - lower utilization with the task in
6518 if (wake_util > min_wake_util)
6520 if (new_util > best_active_util)
6522 min_wake_util = wake_util;
6523 best_active_util = new_util;
6524 best_active_cpu = i;
6531 * For non latency sensitive tasks, skip CPUs that
6532 * will be overutilized by moving the task there.
6534 * The goal here is to remain in EAS mode as long as
6535 * possible at least for !prefer_idle tasks.
6537 if ((new_util * capacity_margin) >
6538 (capacity_orig * SCHED_CAPACITY_SCALE))
6542 * Case B) Non latency sensitive tasks on IDLE CPUs.
6544 * Find an optimal backup IDLE CPU for non latency
6548 * - minimizing the capacity_orig,
6549 * i.e. preferring LITTLE CPUs
6550 * - favoring shallowest idle states
6551 * i.e. avoid to wakeup deep-idle CPUs
6553 * The following code path is used by non latency
6554 * sensitive tasks if IDLE CPUs are available. If at
6555 * least one of such CPUs are available it sets the
6556 * best_idle_cpu to the most suitable idle CPU to be
6559 * If idle CPUs are available, favour these CPUs to
6560 * improve performances by spreading tasks.
6561 * Indeed, the energy_diff() computed by the caller
6562 * will take care to ensure the minimization of energy
6563 * consumptions without affecting performance.
6566 int idle_idx = idle_get_state_idx(cpu_rq(i));
6568 /* Select idle CPU with lower cap_orig */
6569 if (capacity_orig > best_idle_min_cap_orig)
6573 * Skip CPUs in deeper idle state, but only
6574 * if they are also less energy efficient.
6575 * IOW, prefer a deep IDLE LITTLE CPU vs a
6576 * shallow idle big CPU.
6578 if (sysctl_sched_cstate_aware &&
6579 best_idle_cstate <= idle_idx)
6582 /* Keep track of best idle CPU */
6583 best_idle_min_cap_orig = capacity_orig;
6584 best_idle_cstate = idle_idx;
6590 * Case C) Non latency sensitive tasks on ACTIVE CPUs.
6592 * Pack tasks in the most energy efficient capacities.
6594 * This task packing strategy prefers more energy
6595 * efficient CPUs (i.e. pack on smaller maximum
6596 * capacity CPUs) while also trying to spread tasks to
6597 * run them all at the lower OPP.
6599 * This assumes for example that it's more energy
6600 * efficient to run two tasks on two CPUs at a lower
6601 * OPP than packing both on a single CPU but running
6602 * that CPU at an higher OPP.
6604 * Thus, this case keep track of the CPU with the
6605 * smallest maximum capacity and highest spare maximum
6609 /* Favor CPUs with smaller capacity */
6610 if (capacity_orig > target_capacity)
6613 /* Favor CPUs with maximum spare capacity */
6614 if ((capacity_orig - new_util) < target_max_spare_cap)
6617 target_max_spare_cap = capacity_orig - new_util;
6618 target_capacity = capacity_orig;
6622 } while (sg = sg->next, sg != sd->groups);
6625 * For non latency sensitive tasks, cases B and C in the previous loop,
6626 * we pick the best IDLE CPU only if we was not able to find a target
6629 * Policies priorities:
6631 * - prefer_idle tasks:
6633 * a) IDLE CPU available, we return immediately
6634 * b) ACTIVE CPU where task fits and has the bigger maximum spare
6635 * capacity (i.e. target_cpu)
6636 * c) ACTIVE CPU with less contention due to other tasks
6637 * (i.e. best_active_cpu)
6639 * - NON prefer_idle tasks:
6641 * a) ACTIVE CPU: target_cpu
6642 * b) IDLE CPU: best_idle_cpu
6644 if (target_cpu == -1)
6645 target_cpu = prefer_idle
6649 *backup_cpu = prefer_idle
6653 trace_sched_find_best_target(p, prefer_idle, min_util, cpu,
6654 best_idle_cpu, best_active_cpu,
6657 schedstat_inc(p, se.statistics.nr_wakeups_fbt_count);
6658 schedstat_inc(this_rq(), eas_stats.fbt_count);
6664 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
6665 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
6667 * In that case WAKE_AFFINE doesn't make sense and we'll let
6668 * BALANCE_WAKE sort things out.
6670 static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
6672 long min_cap, max_cap;
6674 min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
6675 max_cap = cpu_rq(cpu)->rd->max_cpu_capacity.val;
6677 /* Minimum capacity is close to max, no need to abort wake_affine */
6678 if (max_cap - min_cap < max_cap >> 3)
6681 /* Bring task utilization in sync with prev_cpu */
6682 sync_entity_load_avg(&p->se);
6684 return min_cap * 1024 < task_util(p) * capacity_margin;
6687 static int select_energy_cpu_brute(struct task_struct *p, int prev_cpu, int sync)
6689 struct sched_domain *sd;
6690 int target_cpu = prev_cpu, tmp_target, tmp_backup;
6691 bool boosted, prefer_idle;
6693 schedstat_inc(p, se.statistics.nr_wakeups_secb_attempts);
6694 schedstat_inc(this_rq(), eas_stats.secb_attempts);
6696 if (sysctl_sched_sync_hint_enable && sync) {
6697 int cpu = smp_processor_id();
6699 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
6700 schedstat_inc(p, se.statistics.nr_wakeups_secb_sync);
6701 schedstat_inc(this_rq(), eas_stats.secb_sync);
6707 #ifdef CONFIG_CGROUP_SCHEDTUNE
6708 boosted = schedtune_task_boost(p) > 0;
6709 prefer_idle = schedtune_prefer_idle(p) > 0;
6711 boosted = get_sysctl_sched_cfs_boost() > 0;
6715 sync_entity_load_avg(&p->se);
6717 sd = rcu_dereference(per_cpu(sd_ea, prev_cpu));
6718 /* Find a cpu with sufficient capacity */
6719 tmp_target = find_best_target(p, &tmp_backup, boosted, prefer_idle);
6723 if (tmp_target >= 0) {
6724 target_cpu = tmp_target;
6725 if ((boosted || prefer_idle) && idle_cpu(target_cpu)) {
6726 schedstat_inc(p, se.statistics.nr_wakeups_secb_idle_bt);
6727 schedstat_inc(this_rq(), eas_stats.secb_idle_bt);
6732 if (target_cpu != prev_cpu) {
6734 struct energy_env eenv = {
6735 .util_delta = task_util(p),
6736 .src_cpu = prev_cpu,
6737 .dst_cpu = target_cpu,
6739 .trg_cpu = target_cpu,
6743 #ifdef CONFIG_SCHED_WALT
6744 if (!walt_disabled && sysctl_sched_use_walt_cpu_util &&
6745 p->state == TASK_WAKING)
6746 delta = task_util(p);
6748 /* Not enough spare capacity on previous cpu */
6749 if (__cpu_overutilized(prev_cpu, delta)) {
6750 schedstat_inc(p, se.statistics.nr_wakeups_secb_insuff_cap);
6751 schedstat_inc(this_rq(), eas_stats.secb_insuff_cap);
6755 if (energy_diff(&eenv) >= 0) {
6756 /* No energy saving for target_cpu, try backup */
6757 target_cpu = tmp_backup;
6758 eenv.dst_cpu = target_cpu;
6759 eenv.trg_cpu = target_cpu;
6760 if (tmp_backup < 0 ||
6761 tmp_backup == prev_cpu ||
6762 energy_diff(&eenv) >= 0) {
6763 schedstat_inc(p, se.statistics.nr_wakeups_secb_no_nrg_sav);
6764 schedstat_inc(this_rq(), eas_stats.secb_no_nrg_sav);
6765 target_cpu = prev_cpu;
6770 schedstat_inc(p, se.statistics.nr_wakeups_secb_nrg_sav);
6771 schedstat_inc(this_rq(), eas_stats.secb_nrg_sav);
6775 schedstat_inc(p, se.statistics.nr_wakeups_secb_count);
6776 schedstat_inc(this_rq(), eas_stats.secb_count);
6785 * select_task_rq_fair: Select target runqueue for the waking task in domains
6786 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
6787 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
6789 * Balances load by selecting the idlest cpu in the idlest group, or under
6790 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
6792 * Returns the target cpu number.
6794 * preempt must be disabled.
6797 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags,
6798 int sibling_count_hint)
6800 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
6801 int cpu = smp_processor_id();
6802 int new_cpu = prev_cpu;
6803 int want_affine = 0;
6804 int sync = wake_flags & WF_SYNC;
6806 if (sd_flag & SD_BALANCE_WAKE) {
6808 want_affine = !wake_wide(p, sibling_count_hint) &&
6809 !wake_cap(p, cpu, prev_cpu) &&
6810 cpumask_test_cpu(cpu, &p->cpus_allowed);
6813 if (energy_aware() && !(cpu_rq(prev_cpu)->rd->overutilized))
6814 return select_energy_cpu_brute(p, prev_cpu, sync);
6817 for_each_domain(cpu, tmp) {
6818 if (!(tmp->flags & SD_LOAD_BALANCE))
6822 * If both cpu and prev_cpu are part of this domain,
6823 * cpu is a valid SD_WAKE_AFFINE target.
6825 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6826 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
6831 if (tmp->flags & sd_flag)
6833 else if (!want_affine)
6838 sd = NULL; /* Prefer wake_affine over balance flags */
6839 if (cpu != prev_cpu && wake_affine(affine_sd, p, prev_cpu, sync))
6843 if (sd && !(sd_flag & SD_BALANCE_FORK)) {
6845 * We're going to need the task's util for capacity_spare_wake
6846 * in find_idlest_group. Sync it up to prev_cpu's
6849 sync_entity_load_avg(&p->se);
6853 if (sd_flag & SD_BALANCE_WAKE) /* XXX always ? */
6854 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6857 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
6865 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
6866 * cfs_rq_of(p) references at time of call are still valid and identify the
6867 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
6868 * other assumptions, including the state of rq->lock, should be made.
6870 static void migrate_task_rq_fair(struct task_struct *p)
6873 * We are supposed to update the task to "current" time, then its up to date
6874 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
6875 * what current time is, so simply throw away the out-of-date time. This
6876 * will result in the wakee task is less decayed, but giving the wakee more
6877 * load sounds not bad.
6879 remove_entity_load_avg(&p->se);
6881 /* Tell new CPU we are migrated */
6882 p->se.avg.last_update_time = 0;
6884 /* We have migrated, no longer consider this task hot */
6885 p->se.exec_start = 0;
6888 static void task_dead_fair(struct task_struct *p)
6890 remove_entity_load_avg(&p->se);
6893 #define task_fits_max(p, cpu) true
6894 #endif /* CONFIG_SMP */
6896 static unsigned long
6897 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
6899 unsigned long gran = sysctl_sched_wakeup_granularity;
6902 * Since its curr running now, convert the gran from real-time
6903 * to virtual-time in his units.
6905 * By using 'se' instead of 'curr' we penalize light tasks, so
6906 * they get preempted easier. That is, if 'se' < 'curr' then
6907 * the resulting gran will be larger, therefore penalizing the
6908 * lighter, if otoh 'se' > 'curr' then the resulting gran will
6909 * be smaller, again penalizing the lighter task.
6911 * This is especially important for buddies when the leftmost
6912 * task is higher priority than the buddy.
6914 return calc_delta_fair(gran, se);
6918 * Should 'se' preempt 'curr'.
6932 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
6934 s64 gran, vdiff = curr->vruntime - se->vruntime;
6939 gran = wakeup_gran(curr, se);
6946 static void set_last_buddy(struct sched_entity *se)
6948 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
6951 for_each_sched_entity(se)
6952 cfs_rq_of(se)->last = se;
6955 static void set_next_buddy(struct sched_entity *se)
6957 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
6960 for_each_sched_entity(se)
6961 cfs_rq_of(se)->next = se;
6964 static void set_skip_buddy(struct sched_entity *se)
6966 for_each_sched_entity(se)
6967 cfs_rq_of(se)->skip = se;
6971 * Preempt the current task with a newly woken task if needed:
6973 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
6975 struct task_struct *curr = rq->curr;
6976 struct sched_entity *se = &curr->se, *pse = &p->se;
6977 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6978 int scale = cfs_rq->nr_running >= sched_nr_latency;
6979 int next_buddy_marked = 0;
6981 if (unlikely(se == pse))
6985 * This is possible from callers such as attach_tasks(), in which we
6986 * unconditionally check_prempt_curr() after an enqueue (which may have
6987 * lead to a throttle). This both saves work and prevents false
6988 * next-buddy nomination below.
6990 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
6993 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
6994 set_next_buddy(pse);
6995 next_buddy_marked = 1;
6999 * We can come here with TIF_NEED_RESCHED already set from new task
7002 * Note: this also catches the edge-case of curr being in a throttled
7003 * group (e.g. via set_curr_task), since update_curr() (in the
7004 * enqueue of curr) will have resulted in resched being set. This
7005 * prevents us from potentially nominating it as a false LAST_BUDDY
7008 if (test_tsk_need_resched(curr))
7011 /* Idle tasks are by definition preempted by non-idle tasks. */
7012 if (unlikely(curr->policy == SCHED_IDLE) &&
7013 likely(p->policy != SCHED_IDLE))
7017 * Batch and idle tasks do not preempt non-idle tasks (their preemption
7018 * is driven by the tick):
7020 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
7023 find_matching_se(&se, &pse);
7024 update_curr(cfs_rq_of(se));
7026 if (wakeup_preempt_entity(se, pse) == 1) {
7028 * Bias pick_next to pick the sched entity that is
7029 * triggering this preemption.
7031 if (!next_buddy_marked)
7032 set_next_buddy(pse);
7041 * Only set the backward buddy when the current task is still
7042 * on the rq. This can happen when a wakeup gets interleaved
7043 * with schedule on the ->pre_schedule() or idle_balance()
7044 * point, either of which can * drop the rq lock.
7046 * Also, during early boot the idle thread is in the fair class,
7047 * for obvious reasons its a bad idea to schedule back to it.
7049 if (unlikely(!se->on_rq || curr == rq->idle))
7052 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7056 static struct task_struct *
7057 pick_next_task_fair(struct rq *rq, struct task_struct *prev)
7059 struct cfs_rq *cfs_rq = &rq->cfs;
7060 struct sched_entity *se;
7061 struct task_struct *p;
7065 #ifdef CONFIG_FAIR_GROUP_SCHED
7066 if (!cfs_rq->nr_running)
7069 if (prev->sched_class != &fair_sched_class)
7073 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7074 * likely that a next task is from the same cgroup as the current.
7076 * Therefore attempt to avoid putting and setting the entire cgroup
7077 * hierarchy, only change the part that actually changes.
7081 struct sched_entity *curr = cfs_rq->curr;
7084 * Since we got here without doing put_prev_entity() we also
7085 * have to consider cfs_rq->curr. If it is still a runnable
7086 * entity, update_curr() will update its vruntime, otherwise
7087 * forget we've ever seen it.
7091 update_curr(cfs_rq);
7096 * This call to check_cfs_rq_runtime() will do the
7097 * throttle and dequeue its entity in the parent(s).
7098 * Therefore the 'simple' nr_running test will indeed
7101 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
7105 se = pick_next_entity(cfs_rq, curr);
7106 cfs_rq = group_cfs_rq(se);
7112 * Since we haven't yet done put_prev_entity and if the selected task
7113 * is a different task than we started out with, try and touch the
7114 * least amount of cfs_rqs.
7117 struct sched_entity *pse = &prev->se;
7119 while (!(cfs_rq = is_same_group(se, pse))) {
7120 int se_depth = se->depth;
7121 int pse_depth = pse->depth;
7123 if (se_depth <= pse_depth) {
7124 put_prev_entity(cfs_rq_of(pse), pse);
7125 pse = parent_entity(pse);
7127 if (se_depth >= pse_depth) {
7128 set_next_entity(cfs_rq_of(se), se);
7129 se = parent_entity(se);
7133 put_prev_entity(cfs_rq, pse);
7134 set_next_entity(cfs_rq, se);
7137 if (hrtick_enabled(rq))
7138 hrtick_start_fair(rq, p);
7140 rq->misfit_task = !task_fits_max(p, rq->cpu);
7147 if (!cfs_rq->nr_running)
7150 put_prev_task(rq, prev);
7153 se = pick_next_entity(cfs_rq, NULL);
7154 set_next_entity(cfs_rq, se);
7155 cfs_rq = group_cfs_rq(se);
7160 if (hrtick_enabled(rq))
7161 hrtick_start_fair(rq, p);
7163 rq->misfit_task = !task_fits_max(p, rq->cpu);
7168 rq->misfit_task = 0;
7170 * This is OK, because current is on_cpu, which avoids it being picked
7171 * for load-balance and preemption/IRQs are still disabled avoiding
7172 * further scheduler activity on it and we're being very careful to
7173 * re-start the picking loop.
7175 lockdep_unpin_lock(&rq->lock);
7176 new_tasks = idle_balance(rq);
7177 lockdep_pin_lock(&rq->lock);
7179 * Because idle_balance() releases (and re-acquires) rq->lock, it is
7180 * possible for any higher priority task to appear. In that case we
7181 * must re-start the pick_next_entity() loop.
7193 * Account for a descheduled task:
7195 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
7197 struct sched_entity *se = &prev->se;
7198 struct cfs_rq *cfs_rq;
7200 for_each_sched_entity(se) {
7201 cfs_rq = cfs_rq_of(se);
7202 put_prev_entity(cfs_rq, se);
7207 * sched_yield() is very simple
7209 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7211 static void yield_task_fair(struct rq *rq)
7213 struct task_struct *curr = rq->curr;
7214 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7215 struct sched_entity *se = &curr->se;
7218 * Are we the only task in the tree?
7220 if (unlikely(rq->nr_running == 1))
7223 clear_buddies(cfs_rq, se);
7225 if (curr->policy != SCHED_BATCH) {
7226 update_rq_clock(rq);
7228 * Update run-time statistics of the 'current'.
7230 update_curr(cfs_rq);
7232 * Tell update_rq_clock() that we've just updated,
7233 * so we don't do microscopic update in schedule()
7234 * and double the fastpath cost.
7236 rq_clock_skip_update(rq, true);
7242 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
7244 struct sched_entity *se = &p->se;
7246 /* throttled hierarchies are not runnable */
7247 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
7250 /* Tell the scheduler that we'd really like pse to run next. */
7253 yield_task_fair(rq);
7259 /**************************************************
7260 * Fair scheduling class load-balancing methods.
7264 * The purpose of load-balancing is to achieve the same basic fairness the
7265 * per-cpu scheduler provides, namely provide a proportional amount of compute
7266 * time to each task. This is expressed in the following equation:
7268 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
7270 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
7271 * W_i,0 is defined as:
7273 * W_i,0 = \Sum_j w_i,j (2)
7275 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
7276 * is derived from the nice value as per prio_to_weight[].
7278 * The weight average is an exponential decay average of the instantaneous
7281 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
7283 * C_i is the compute capacity of cpu i, typically it is the
7284 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7285 * can also include other factors [XXX].
7287 * To achieve this balance we define a measure of imbalance which follows
7288 * directly from (1):
7290 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
7292 * We them move tasks around to minimize the imbalance. In the continuous
7293 * function space it is obvious this converges, in the discrete case we get
7294 * a few fun cases generally called infeasible weight scenarios.
7297 * - infeasible weights;
7298 * - local vs global optima in the discrete case. ]
7303 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
7304 * for all i,j solution, we create a tree of cpus that follows the hardware
7305 * topology where each level pairs two lower groups (or better). This results
7306 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
7307 * tree to only the first of the previous level and we decrease the frequency
7308 * of load-balance at each level inv. proportional to the number of cpus in
7314 * \Sum { --- * --- * 2^i } = O(n) (5)
7316 * `- size of each group
7317 * | | `- number of cpus doing load-balance
7319 * `- sum over all levels
7321 * Coupled with a limit on how many tasks we can migrate every balance pass,
7322 * this makes (5) the runtime complexity of the balancer.
7324 * An important property here is that each CPU is still (indirectly) connected
7325 * to every other cpu in at most O(log n) steps:
7327 * The adjacency matrix of the resulting graph is given by:
7330 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
7333 * And you'll find that:
7335 * A^(log_2 n)_i,j != 0 for all i,j (7)
7337 * Showing there's indeed a path between every cpu in at most O(log n) steps.
7338 * The task movement gives a factor of O(m), giving a convergence complexity
7341 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
7346 * In order to avoid CPUs going idle while there's still work to do, new idle
7347 * balancing is more aggressive and has the newly idle cpu iterate up the domain
7348 * tree itself instead of relying on other CPUs to bring it work.
7350 * This adds some complexity to both (5) and (8) but it reduces the total idle
7358 * Cgroups make a horror show out of (2), instead of a simple sum we get:
7361 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
7366 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
7368 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
7370 * The big problem is S_k, its a global sum needed to compute a local (W_i)
7373 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7374 * rewrite all of this once again.]
7377 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7379 enum fbq_type { regular, remote, all };
7388 #define LBF_ALL_PINNED 0x01
7389 #define LBF_NEED_BREAK 0x02
7390 #define LBF_DST_PINNED 0x04
7391 #define LBF_SOME_PINNED 0x08
7394 struct sched_domain *sd;
7402 struct cpumask *dst_grpmask;
7404 enum cpu_idle_type idle;
7406 unsigned int src_grp_nr_running;
7407 /* The set of CPUs under consideration for load-balancing */
7408 struct cpumask *cpus;
7413 unsigned int loop_break;
7414 unsigned int loop_max;
7416 enum fbq_type fbq_type;
7417 enum group_type busiest_group_type;
7418 struct list_head tasks;
7422 * Is this task likely cache-hot:
7424 static int task_hot(struct task_struct *p, struct lb_env *env)
7428 lockdep_assert_held(&env->src_rq->lock);
7430 if (p->sched_class != &fair_sched_class)
7433 if (unlikely(p->policy == SCHED_IDLE))
7437 * Buddy candidates are cache hot:
7439 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
7440 (&p->se == cfs_rq_of(&p->se)->next ||
7441 &p->se == cfs_rq_of(&p->se)->last))
7444 if (sysctl_sched_migration_cost == -1)
7446 if (sysctl_sched_migration_cost == 0)
7449 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
7451 return delta < (s64)sysctl_sched_migration_cost;
7454 #ifdef CONFIG_NUMA_BALANCING
7456 * Returns 1, if task migration degrades locality
7457 * Returns 0, if task migration improves locality i.e migration preferred.
7458 * Returns -1, if task migration is not affected by locality.
7460 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
7462 struct numa_group *numa_group = rcu_dereference(p->numa_group);
7463 unsigned long src_faults, dst_faults;
7464 int src_nid, dst_nid;
7466 if (!static_branch_likely(&sched_numa_balancing))
7469 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
7472 src_nid = cpu_to_node(env->src_cpu);
7473 dst_nid = cpu_to_node(env->dst_cpu);
7475 if (src_nid == dst_nid)
7478 /* Migrating away from the preferred node is always bad. */
7479 if (src_nid == p->numa_preferred_nid) {
7480 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7486 /* Encourage migration to the preferred node. */
7487 if (dst_nid == p->numa_preferred_nid)
7491 src_faults = group_faults(p, src_nid);
7492 dst_faults = group_faults(p, dst_nid);
7494 src_faults = task_faults(p, src_nid);
7495 dst_faults = task_faults(p, dst_nid);
7498 return dst_faults < src_faults;
7502 static inline int migrate_degrades_locality(struct task_struct *p,
7510 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7513 int can_migrate_task(struct task_struct *p, struct lb_env *env)
7517 lockdep_assert_held(&env->src_rq->lock);
7520 * We do not migrate tasks that are:
7521 * 1) throttled_lb_pair, or
7522 * 2) cannot be migrated to this CPU due to cpus_allowed, or
7523 * 3) running (obviously), or
7524 * 4) are cache-hot on their current CPU.
7526 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7529 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
7532 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
7534 env->flags |= LBF_SOME_PINNED;
7537 * Remember if this task can be migrated to any other cpu in
7538 * our sched_group. We may want to revisit it if we couldn't
7539 * meet load balance goals by pulling other tasks on src_cpu.
7541 * Also avoid computing new_dst_cpu if we have already computed
7542 * one in current iteration.
7544 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
7547 /* Prevent to re-select dst_cpu via env's cpus */
7548 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
7549 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
7550 env->flags |= LBF_DST_PINNED;
7551 env->new_dst_cpu = cpu;
7559 /* Record that we found atleast one task that could run on dst_cpu */
7560 env->flags &= ~LBF_ALL_PINNED;
7562 if (task_running(env->src_rq, p)) {
7563 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
7568 * Aggressive migration if:
7569 * 1) destination numa is preferred
7570 * 2) task is cache cold, or
7571 * 3) too many balance attempts have failed.
7573 tsk_cache_hot = migrate_degrades_locality(p, env);
7574 if (tsk_cache_hot == -1)
7575 tsk_cache_hot = task_hot(p, env);
7577 if (tsk_cache_hot <= 0 ||
7578 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
7579 if (tsk_cache_hot == 1) {
7580 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
7581 schedstat_inc(p, se.statistics.nr_forced_migrations);
7586 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
7591 * detach_task() -- detach the task for the migration specified in env
7593 static void detach_task(struct task_struct *p, struct lb_env *env)
7595 lockdep_assert_held(&env->src_rq->lock);
7597 deactivate_task(env->src_rq, p, 0);
7598 p->on_rq = TASK_ON_RQ_MIGRATING;
7599 double_lock_balance(env->src_rq, env->dst_rq);
7600 set_task_cpu(p, env->dst_cpu);
7601 double_unlock_balance(env->src_rq, env->dst_rq);
7605 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
7606 * part of active balancing operations within "domain".
7608 * Returns a task if successful and NULL otherwise.
7610 static struct task_struct *detach_one_task(struct lb_env *env)
7612 struct task_struct *p, *n;
7614 lockdep_assert_held(&env->src_rq->lock);
7616 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
7617 if (!can_migrate_task(p, env))
7620 detach_task(p, env);
7623 * Right now, this is only the second place where
7624 * lb_gained[env->idle] is updated (other is detach_tasks)
7625 * so we can safely collect stats here rather than
7626 * inside detach_tasks().
7628 schedstat_inc(env->sd, lb_gained[env->idle]);
7634 static const unsigned int sched_nr_migrate_break = 32;
7637 * detach_tasks() -- tries to detach up to imbalance weighted load from
7638 * busiest_rq, as part of a balancing operation within domain "sd".
7640 * Returns number of detached tasks if successful and 0 otherwise.
7642 static int detach_tasks(struct lb_env *env)
7644 struct list_head *tasks = &env->src_rq->cfs_tasks;
7645 struct task_struct *p;
7649 lockdep_assert_held(&env->src_rq->lock);
7651 if (env->imbalance <= 0)
7654 while (!list_empty(tasks)) {
7656 * We don't want to steal all, otherwise we may be treated likewise,
7657 * which could at worst lead to a livelock crash.
7659 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
7662 p = list_first_entry(tasks, struct task_struct, se.group_node);
7665 /* We've more or less seen every task there is, call it quits */
7666 if (env->loop > env->loop_max)
7669 /* take a breather every nr_migrate tasks */
7670 if (env->loop > env->loop_break) {
7671 env->loop_break += sched_nr_migrate_break;
7672 env->flags |= LBF_NEED_BREAK;
7676 if (!can_migrate_task(p, env))
7679 load = task_h_load(p);
7681 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
7684 if ((load / 2) > env->imbalance)
7687 detach_task(p, env);
7688 list_add(&p->se.group_node, &env->tasks);
7691 env->imbalance -= load;
7693 #ifdef CONFIG_PREEMPT
7695 * NEWIDLE balancing is a source of latency, so preemptible
7696 * kernels will stop after the first task is detached to minimize
7697 * the critical section.
7699 if (env->idle == CPU_NEWLY_IDLE)
7704 * We only want to steal up to the prescribed amount of
7707 if (env->imbalance <= 0)
7712 list_move_tail(&p->se.group_node, tasks);
7716 * Right now, this is one of only two places we collect this stat
7717 * so we can safely collect detach_one_task() stats here rather
7718 * than inside detach_one_task().
7720 schedstat_add(env->sd, lb_gained[env->idle], detached);
7726 * attach_task() -- attach the task detached by detach_task() to its new rq.
7728 static void attach_task(struct rq *rq, struct task_struct *p)
7730 lockdep_assert_held(&rq->lock);
7732 BUG_ON(task_rq(p) != rq);
7733 p->on_rq = TASK_ON_RQ_QUEUED;
7734 activate_task(rq, p, 0);
7735 check_preempt_curr(rq, p, 0);
7739 * attach_one_task() -- attaches the task returned from detach_one_task() to
7742 static void attach_one_task(struct rq *rq, struct task_struct *p)
7744 raw_spin_lock(&rq->lock);
7746 raw_spin_unlock(&rq->lock);
7750 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
7753 static void attach_tasks(struct lb_env *env)
7755 struct list_head *tasks = &env->tasks;
7756 struct task_struct *p;
7758 raw_spin_lock(&env->dst_rq->lock);
7760 while (!list_empty(tasks)) {
7761 p = list_first_entry(tasks, struct task_struct, se.group_node);
7762 list_del_init(&p->se.group_node);
7764 attach_task(env->dst_rq, p);
7767 raw_spin_unlock(&env->dst_rq->lock);
7770 #ifdef CONFIG_FAIR_GROUP_SCHED
7771 static void update_blocked_averages(int cpu)
7773 struct rq *rq = cpu_rq(cpu);
7774 struct cfs_rq *cfs_rq;
7775 unsigned long flags;
7777 raw_spin_lock_irqsave(&rq->lock, flags);
7778 update_rq_clock(rq);
7781 * Iterates the task_group tree in a bottom up fashion, see
7782 * list_add_leaf_cfs_rq() for details.
7784 for_each_leaf_cfs_rq(rq, cfs_rq) {
7785 /* throttled entities do not contribute to load */
7786 if (throttled_hierarchy(cfs_rq))
7789 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq,
7791 update_tg_load_avg(cfs_rq, 0);
7793 /* Propagate pending load changes to the parent */
7794 if (cfs_rq->tg->se[cpu])
7795 update_load_avg(cfs_rq->tg->se[cpu], 0);
7797 raw_spin_unlock_irqrestore(&rq->lock, flags);
7801 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
7802 * This needs to be done in a top-down fashion because the load of a child
7803 * group is a fraction of its parents load.
7805 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
7807 struct rq *rq = rq_of(cfs_rq);
7808 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
7809 unsigned long now = jiffies;
7812 if (cfs_rq->last_h_load_update == now)
7815 WRITE_ONCE(cfs_rq->h_load_next, NULL);
7816 for_each_sched_entity(se) {
7817 cfs_rq = cfs_rq_of(se);
7818 WRITE_ONCE(cfs_rq->h_load_next, se);
7819 if (cfs_rq->last_h_load_update == now)
7824 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
7825 cfs_rq->last_h_load_update = now;
7828 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
7829 load = cfs_rq->h_load;
7830 load = div64_ul(load * se->avg.load_avg,
7831 cfs_rq_load_avg(cfs_rq) + 1);
7832 cfs_rq = group_cfs_rq(se);
7833 cfs_rq->h_load = load;
7834 cfs_rq->last_h_load_update = now;
7838 static unsigned long task_h_load(struct task_struct *p)
7840 struct cfs_rq *cfs_rq = task_cfs_rq(p);
7842 update_cfs_rq_h_load(cfs_rq);
7843 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
7844 cfs_rq_load_avg(cfs_rq) + 1);
7847 static inline void update_blocked_averages(int cpu)
7849 struct rq *rq = cpu_rq(cpu);
7850 struct cfs_rq *cfs_rq = &rq->cfs;
7851 unsigned long flags;
7853 raw_spin_lock_irqsave(&rq->lock, flags);
7854 update_rq_clock(rq);
7855 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true);
7856 raw_spin_unlock_irqrestore(&rq->lock, flags);
7859 static unsigned long task_h_load(struct task_struct *p)
7861 return p->se.avg.load_avg;
7865 /********** Helpers for find_busiest_group ************************/
7868 * sg_lb_stats - stats of a sched_group required for load_balancing
7870 struct sg_lb_stats {
7871 unsigned long avg_load; /*Avg load across the CPUs of the group */
7872 unsigned long group_load; /* Total load over the CPUs of the group */
7873 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
7874 unsigned long load_per_task;
7875 unsigned long group_capacity;
7876 unsigned long group_util; /* Total utilization of the group */
7877 unsigned int sum_nr_running; /* Nr tasks running in the group */
7878 unsigned int idle_cpus;
7879 unsigned int group_weight;
7880 enum group_type group_type;
7881 int group_no_capacity;
7882 int group_misfit_task; /* A cpu has a task too big for its capacity */
7883 #ifdef CONFIG_NUMA_BALANCING
7884 unsigned int nr_numa_running;
7885 unsigned int nr_preferred_running;
7890 * sd_lb_stats - Structure to store the statistics of a sched_domain
7891 * during load balancing.
7893 struct sd_lb_stats {
7894 struct sched_group *busiest; /* Busiest group in this sd */
7895 struct sched_group *local; /* Local group in this sd */
7896 unsigned long total_load; /* Total load of all groups in sd */
7897 unsigned long total_capacity; /* Total capacity of all groups in sd */
7898 unsigned long avg_load; /* Average load across all groups in sd */
7900 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
7901 struct sg_lb_stats local_stat; /* Statistics of the local group */
7904 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
7907 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
7908 * local_stat because update_sg_lb_stats() does a full clear/assignment.
7909 * We must however clear busiest_stat::avg_load because
7910 * update_sd_pick_busiest() reads this before assignment.
7912 *sds = (struct sd_lb_stats){
7916 .total_capacity = 0UL,
7919 .sum_nr_running = 0,
7920 .group_type = group_other,
7926 * get_sd_load_idx - Obtain the load index for a given sched domain.
7927 * @sd: The sched_domain whose load_idx is to be obtained.
7928 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
7930 * Return: The load index.
7932 static inline int get_sd_load_idx(struct sched_domain *sd,
7933 enum cpu_idle_type idle)
7939 load_idx = sd->busy_idx;
7942 case CPU_NEWLY_IDLE:
7943 load_idx = sd->newidle_idx;
7946 load_idx = sd->idle_idx;
7953 static unsigned long scale_rt_capacity(int cpu)
7955 struct rq *rq = cpu_rq(cpu);
7956 u64 total, used, age_stamp, avg;
7960 * Since we're reading these variables without serialization make sure
7961 * we read them once before doing sanity checks on them.
7963 age_stamp = READ_ONCE(rq->age_stamp);
7964 avg = READ_ONCE(rq->rt_avg);
7965 delta = __rq_clock_broken(rq) - age_stamp;
7967 if (unlikely(delta < 0))
7970 total = sched_avg_period() + delta;
7972 used = div_u64(avg, total);
7975 * deadline bandwidth is defined at system level so we must
7976 * weight this bandwidth with the max capacity of the system.
7977 * As a reminder, avg_bw is 20bits width and
7978 * scale_cpu_capacity is 10 bits width
7980 used += div_u64(rq->dl.avg_bw, arch_scale_cpu_capacity(NULL, cpu));
7982 if (likely(used < SCHED_CAPACITY_SCALE))
7983 return SCHED_CAPACITY_SCALE - used;
7988 void init_max_cpu_capacity(struct max_cpu_capacity *mcc)
7990 raw_spin_lock_init(&mcc->lock);
7995 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
7997 unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
7998 struct sched_group *sdg = sd->groups;
7999 struct max_cpu_capacity *mcc;
8000 unsigned long max_capacity;
8002 unsigned long flags;
8004 cpu_rq(cpu)->cpu_capacity_orig = capacity;
8006 mcc = &cpu_rq(cpu)->rd->max_cpu_capacity;
8008 raw_spin_lock_irqsave(&mcc->lock, flags);
8009 max_capacity = mcc->val;
8010 max_cap_cpu = mcc->cpu;
8012 if ((max_capacity > capacity && max_cap_cpu == cpu) ||
8013 (max_capacity < capacity)) {
8014 mcc->val = capacity;
8016 #ifdef CONFIG_SCHED_DEBUG
8017 raw_spin_unlock_irqrestore(&mcc->lock, flags);
8018 printk_deferred(KERN_INFO "CPU%d: update max cpu_capacity %lu\n",
8023 raw_spin_unlock_irqrestore(&mcc->lock, flags);
8025 skip_unlock: __attribute__ ((unused));
8026 capacity *= scale_rt_capacity(cpu);
8027 capacity >>= SCHED_CAPACITY_SHIFT;
8032 cpu_rq(cpu)->cpu_capacity = capacity;
8033 sdg->sgc->capacity = capacity;
8034 sdg->sgc->max_capacity = capacity;
8035 sdg->sgc->min_capacity = capacity;
8038 void update_group_capacity(struct sched_domain *sd, int cpu)
8040 struct sched_domain *child = sd->child;
8041 struct sched_group *group, *sdg = sd->groups;
8042 unsigned long capacity, max_capacity, min_capacity;
8043 unsigned long interval;
8045 interval = msecs_to_jiffies(sd->balance_interval);
8046 interval = clamp(interval, 1UL, max_load_balance_interval);
8047 sdg->sgc->next_update = jiffies + interval;
8050 update_cpu_capacity(sd, cpu);
8056 min_capacity = ULONG_MAX;
8058 if (child->flags & SD_OVERLAP) {
8060 * SD_OVERLAP domains cannot assume that child groups
8061 * span the current group.
8064 for_each_cpu(cpu, sched_group_cpus(sdg)) {
8065 struct sched_group_capacity *sgc;
8066 struct rq *rq = cpu_rq(cpu);
8069 * build_sched_domains() -> init_sched_groups_capacity()
8070 * gets here before we've attached the domains to the
8073 * Use capacity_of(), which is set irrespective of domains
8074 * in update_cpu_capacity().
8076 * This avoids capacity from being 0 and
8077 * causing divide-by-zero issues on boot.
8079 if (unlikely(!rq->sd)) {
8080 capacity += capacity_of(cpu);
8082 sgc = rq->sd->groups->sgc;
8083 capacity += sgc->capacity;
8086 max_capacity = max(capacity, max_capacity);
8087 min_capacity = min(capacity, min_capacity);
8091 * !SD_OVERLAP domains can assume that child groups
8092 * span the current group.
8095 group = child->groups;
8097 struct sched_group_capacity *sgc = group->sgc;
8099 capacity += sgc->capacity;
8100 max_capacity = max(sgc->max_capacity, max_capacity);
8101 min_capacity = min(sgc->min_capacity, min_capacity);
8102 group = group->next;
8103 } while (group != child->groups);
8106 sdg->sgc->capacity = capacity;
8107 sdg->sgc->max_capacity = max_capacity;
8108 sdg->sgc->min_capacity = min_capacity;
8112 * Check whether the capacity of the rq has been noticeably reduced by side
8113 * activity. The imbalance_pct is used for the threshold.
8114 * Return true is the capacity is reduced
8117 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
8119 return ((rq->cpu_capacity * sd->imbalance_pct) <
8120 (rq->cpu_capacity_orig * 100));
8124 * Group imbalance indicates (and tries to solve) the problem where balancing
8125 * groups is inadequate due to tsk_cpus_allowed() constraints.
8127 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
8128 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
8131 * { 0 1 2 3 } { 4 5 6 7 }
8134 * If we were to balance group-wise we'd place two tasks in the first group and
8135 * two tasks in the second group. Clearly this is undesired as it will overload
8136 * cpu 3 and leave one of the cpus in the second group unused.
8138 * The current solution to this issue is detecting the skew in the first group
8139 * by noticing the lower domain failed to reach balance and had difficulty
8140 * moving tasks due to affinity constraints.
8142 * When this is so detected; this group becomes a candidate for busiest; see
8143 * update_sd_pick_busiest(). And calculate_imbalance() and
8144 * find_busiest_group() avoid some of the usual balance conditions to allow it
8145 * to create an effective group imbalance.
8147 * This is a somewhat tricky proposition since the next run might not find the
8148 * group imbalance and decide the groups need to be balanced again. A most
8149 * subtle and fragile situation.
8152 static inline int sg_imbalanced(struct sched_group *group)
8154 return group->sgc->imbalance;
8158 * group_has_capacity returns true if the group has spare capacity that could
8159 * be used by some tasks.
8160 * We consider that a group has spare capacity if the * number of task is
8161 * smaller than the number of CPUs or if the utilization is lower than the
8162 * available capacity for CFS tasks.
8163 * For the latter, we use a threshold to stabilize the state, to take into
8164 * account the variance of the tasks' load and to return true if the available
8165 * capacity in meaningful for the load balancer.
8166 * As an example, an available capacity of 1% can appear but it doesn't make
8167 * any benefit for the load balance.
8170 group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
8172 if (sgs->sum_nr_running < sgs->group_weight)
8175 if ((sgs->group_capacity * 100) >
8176 (sgs->group_util * env->sd->imbalance_pct))
8183 * group_is_overloaded returns true if the group has more tasks than it can
8185 * group_is_overloaded is not equals to !group_has_capacity because a group
8186 * with the exact right number of tasks, has no more spare capacity but is not
8187 * overloaded so both group_has_capacity and group_is_overloaded return
8191 group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
8193 if (sgs->sum_nr_running <= sgs->group_weight)
8196 if ((sgs->group_capacity * 100) <
8197 (sgs->group_util * env->sd->imbalance_pct))
8205 * group_smaller_cpu_capacity: Returns true if sched_group sg has smaller
8206 * per-cpu capacity than sched_group ref.
8209 group_smaller_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8211 return sg->sgc->max_capacity + capacity_margin - SCHED_LOAD_SCALE <
8212 ref->sgc->max_capacity;
8216 group_type group_classify(struct sched_group *group,
8217 struct sg_lb_stats *sgs)
8219 if (sgs->group_no_capacity)
8220 return group_overloaded;
8222 if (sg_imbalanced(group))
8223 return group_imbalanced;
8225 if (sgs->group_misfit_task)
8226 return group_misfit_task;
8231 #ifdef CONFIG_NO_HZ_COMMON
8233 * idle load balancing data
8234 * - used by the nohz balance, but we want it available here
8235 * so that we can see which CPUs have no tick.
8238 cpumask_var_t idle_cpus_mask;
8240 unsigned long next_balance; /* in jiffy units */
8241 } nohz ____cacheline_aligned;
8243 static inline void update_cpu_stats_if_tickless(struct rq *rq)
8245 /* only called from update_sg_lb_stats when irqs are disabled */
8246 if (cpumask_test_cpu(rq->cpu, nohz.idle_cpus_mask)) {
8247 /* rate limit updates to once-per-jiffie at most */
8248 if (READ_ONCE(jiffies) <= rq->last_load_update_tick)
8251 raw_spin_lock(&rq->lock);
8252 update_rq_clock(rq);
8253 update_idle_cpu_load(rq);
8254 update_cfs_rq_load_avg(rq->clock_task, &rq->cfs, false);
8255 raw_spin_unlock(&rq->lock);
8260 static inline void update_cpu_stats_if_tickless(struct rq *rq) { }
8264 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
8265 * @env: The load balancing environment.
8266 * @group: sched_group whose statistics are to be updated.
8267 * @load_idx: Load index of sched_domain of this_cpu for load calc.
8268 * @local_group: Does group contain this_cpu.
8269 * @sgs: variable to hold the statistics for this group.
8270 * @overload: Indicate more than one runnable task for any CPU.
8271 * @overutilized: Indicate overutilization for any CPU.
8273 static inline void update_sg_lb_stats(struct lb_env *env,
8274 struct sched_group *group, int load_idx,
8275 int local_group, struct sg_lb_stats *sgs,
8276 bool *overload, bool *overutilized)
8281 memset(sgs, 0, sizeof(*sgs));
8283 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
8284 struct rq *rq = cpu_rq(i);
8286 /* if we are entering idle and there are CPUs with
8287 * their tick stopped, do an update for them
8289 if (env->idle == CPU_NEWLY_IDLE)
8290 update_cpu_stats_if_tickless(rq);
8292 /* Bias balancing toward cpus of our domain */
8294 load = target_load(i, load_idx);
8296 load = source_load(i, load_idx);
8298 sgs->group_load += load;
8299 sgs->group_util += cpu_util(i);
8300 sgs->sum_nr_running += rq->cfs.h_nr_running;
8302 nr_running = rq->nr_running;
8306 #ifdef CONFIG_NUMA_BALANCING
8307 sgs->nr_numa_running += rq->nr_numa_running;
8308 sgs->nr_preferred_running += rq->nr_preferred_running;
8310 sgs->sum_weighted_load += weighted_cpuload(i);
8312 * No need to call idle_cpu() if nr_running is not 0
8314 if (!nr_running && idle_cpu(i))
8317 if (cpu_overutilized(i)) {
8318 *overutilized = true;
8319 if (!sgs->group_misfit_task && rq->misfit_task)
8320 sgs->group_misfit_task = capacity_of(i);
8324 /* Adjust by relative CPU capacity of the group */
8325 sgs->group_capacity = group->sgc->capacity;
8326 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
8328 if (sgs->sum_nr_running)
8329 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
8331 sgs->group_weight = group->group_weight;
8333 sgs->group_no_capacity = group_is_overloaded(env, sgs);
8334 sgs->group_type = group_classify(group, sgs);
8338 * update_sd_pick_busiest - return 1 on busiest group
8339 * @env: The load balancing environment.
8340 * @sds: sched_domain statistics
8341 * @sg: sched_group candidate to be checked for being the busiest
8342 * @sgs: sched_group statistics
8344 * Determine if @sg is a busier group than the previously selected
8347 * Return: %true if @sg is a busier group than the previously selected
8348 * busiest group. %false otherwise.
8350 static bool update_sd_pick_busiest(struct lb_env *env,
8351 struct sd_lb_stats *sds,
8352 struct sched_group *sg,
8353 struct sg_lb_stats *sgs)
8355 struct sg_lb_stats *busiest = &sds->busiest_stat;
8357 if (sgs->group_type > busiest->group_type)
8360 if (sgs->group_type < busiest->group_type)
8364 * Candidate sg doesn't face any serious load-balance problems
8365 * so don't pick it if the local sg is already filled up.
8367 if (sgs->group_type == group_other &&
8368 !group_has_capacity(env, &sds->local_stat))
8371 if (sgs->avg_load <= busiest->avg_load)
8374 if (!(env->sd->flags & SD_ASYM_CPUCAPACITY))
8378 * Candidate sg has no more than one task per CPU and
8379 * has higher per-CPU capacity. Migrating tasks to less
8380 * capable CPUs may harm throughput. Maximize throughput,
8381 * power/energy consequences are not considered.
8383 if (sgs->sum_nr_running <= sgs->group_weight &&
8384 group_smaller_cpu_capacity(sds->local, sg))
8388 /* This is the busiest node in its class. */
8389 if (!(env->sd->flags & SD_ASYM_PACKING))
8393 * ASYM_PACKING needs to move all the work to the lowest
8394 * numbered CPUs in the group, therefore mark all groups
8395 * higher than ourself as busy.
8397 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
8401 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
8408 #ifdef CONFIG_NUMA_BALANCING
8409 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8411 if (sgs->sum_nr_running > sgs->nr_numa_running)
8413 if (sgs->sum_nr_running > sgs->nr_preferred_running)
8418 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8420 if (rq->nr_running > rq->nr_numa_running)
8422 if (rq->nr_running > rq->nr_preferred_running)
8427 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8432 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8436 #endif /* CONFIG_NUMA_BALANCING */
8438 #define lb_sd_parent(sd) \
8439 (sd->parent && sd->parent->groups != sd->parent->groups->next)
8442 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
8443 * @env: The load balancing environment.
8444 * @sds: variable to hold the statistics for this sched_domain.
8446 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
8448 struct sched_domain *child = env->sd->child;
8449 struct sched_group *sg = env->sd->groups;
8450 struct sg_lb_stats tmp_sgs;
8451 int load_idx, prefer_sibling = 0;
8452 bool overload = false, overutilized = false;
8454 if (child && child->flags & SD_PREFER_SIBLING)
8457 load_idx = get_sd_load_idx(env->sd, env->idle);
8460 struct sg_lb_stats *sgs = &tmp_sgs;
8463 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
8466 sgs = &sds->local_stat;
8468 if (env->idle != CPU_NEWLY_IDLE ||
8469 time_after_eq(jiffies, sg->sgc->next_update))
8470 update_group_capacity(env->sd, env->dst_cpu);
8473 update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
8474 &overload, &overutilized);
8480 * In case the child domain prefers tasks go to siblings
8481 * first, lower the sg capacity so that we'll try
8482 * and move all the excess tasks away. We lower the capacity
8483 * of a group only if the local group has the capacity to fit
8484 * these excess tasks. The extra check prevents the case where
8485 * you always pull from the heaviest group when it is already
8486 * under-utilized (possible with a large weight task outweighs
8487 * the tasks on the system).
8489 if (prefer_sibling && sds->local &&
8490 group_has_capacity(env, &sds->local_stat) &&
8491 (sgs->sum_nr_running > 1)) {
8492 sgs->group_no_capacity = 1;
8493 sgs->group_type = group_classify(sg, sgs);
8497 * Ignore task groups with misfit tasks if local group has no
8498 * capacity or if per-cpu capacity isn't higher.
8500 if (sgs->group_type == group_misfit_task &&
8501 (!group_has_capacity(env, &sds->local_stat) ||
8502 !group_smaller_cpu_capacity(sg, sds->local)))
8503 sgs->group_type = group_other;
8505 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
8507 sds->busiest_stat = *sgs;
8511 /* Now, start updating sd_lb_stats */
8512 sds->total_load += sgs->group_load;
8513 sds->total_capacity += sgs->group_capacity;
8516 } while (sg != env->sd->groups);
8518 if (env->sd->flags & SD_NUMA)
8519 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
8521 env->src_grp_nr_running = sds->busiest_stat.sum_nr_running;
8523 if (!lb_sd_parent(env->sd)) {
8524 /* update overload indicator if we are at root domain */
8525 if (env->dst_rq->rd->overload != overload)
8526 env->dst_rq->rd->overload = overload;
8528 /* Update over-utilization (tipping point, U >= 0) indicator */
8529 if (env->dst_rq->rd->overutilized != overutilized) {
8530 env->dst_rq->rd->overutilized = overutilized;
8531 trace_sched_overutilized(overutilized);
8534 if (!env->dst_rq->rd->overutilized && overutilized) {
8535 env->dst_rq->rd->overutilized = true;
8536 trace_sched_overutilized(true);
8543 * check_asym_packing - Check to see if the group is packed into the
8546 * This is primarily intended to used at the sibling level. Some
8547 * cores like POWER7 prefer to use lower numbered SMT threads. In the
8548 * case of POWER7, it can move to lower SMT modes only when higher
8549 * threads are idle. When in lower SMT modes, the threads will
8550 * perform better since they share less core resources. Hence when we
8551 * have idle threads, we want them to be the higher ones.
8553 * This packing function is run on idle threads. It checks to see if
8554 * the busiest CPU in this domain (core in the P7 case) has a higher
8555 * CPU number than the packing function is being run on. Here we are
8556 * assuming lower CPU number will be equivalent to lower a SMT thread
8559 * Return: 1 when packing is required and a task should be moved to
8560 * this CPU. The amount of the imbalance is returned in *imbalance.
8562 * @env: The load balancing environment.
8563 * @sds: Statistics of the sched_domain which is to be packed
8565 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
8569 if (!(env->sd->flags & SD_ASYM_PACKING))
8575 busiest_cpu = group_first_cpu(sds->busiest);
8576 if (env->dst_cpu > busiest_cpu)
8579 env->imbalance = DIV_ROUND_CLOSEST(
8580 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
8581 SCHED_CAPACITY_SCALE);
8587 * fix_small_imbalance - Calculate the minor imbalance that exists
8588 * amongst the groups of a sched_domain, during
8590 * @env: The load balancing environment.
8591 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
8594 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
8596 unsigned long tmp, capa_now = 0, capa_move = 0;
8597 unsigned int imbn = 2;
8598 unsigned long scaled_busy_load_per_task;
8599 struct sg_lb_stats *local, *busiest;
8601 local = &sds->local_stat;
8602 busiest = &sds->busiest_stat;
8604 if (!local->sum_nr_running)
8605 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
8606 else if (busiest->load_per_task > local->load_per_task)
8609 scaled_busy_load_per_task =
8610 (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
8611 busiest->group_capacity;
8613 if (busiest->avg_load + scaled_busy_load_per_task >=
8614 local->avg_load + (scaled_busy_load_per_task * imbn)) {
8615 env->imbalance = busiest->load_per_task;
8620 * OK, we don't have enough imbalance to justify moving tasks,
8621 * however we may be able to increase total CPU capacity used by
8625 capa_now += busiest->group_capacity *
8626 min(busiest->load_per_task, busiest->avg_load);
8627 capa_now += local->group_capacity *
8628 min(local->load_per_task, local->avg_load);
8629 capa_now /= SCHED_CAPACITY_SCALE;
8631 /* Amount of load we'd subtract */
8632 if (busiest->avg_load > scaled_busy_load_per_task) {
8633 capa_move += busiest->group_capacity *
8634 min(busiest->load_per_task,
8635 busiest->avg_load - scaled_busy_load_per_task);
8638 /* Amount of load we'd add */
8639 if (busiest->avg_load * busiest->group_capacity <
8640 busiest->load_per_task * SCHED_CAPACITY_SCALE) {
8641 tmp = (busiest->avg_load * busiest->group_capacity) /
8642 local->group_capacity;
8644 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
8645 local->group_capacity;
8647 capa_move += local->group_capacity *
8648 min(local->load_per_task, local->avg_load + tmp);
8649 capa_move /= SCHED_CAPACITY_SCALE;
8651 /* Move if we gain throughput */
8652 if (capa_move > capa_now)
8653 env->imbalance = busiest->load_per_task;
8657 * calculate_imbalance - Calculate the amount of imbalance present within the
8658 * groups of a given sched_domain during load balance.
8659 * @env: load balance environment
8660 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
8662 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
8664 unsigned long max_pull, load_above_capacity = ~0UL;
8665 struct sg_lb_stats *local, *busiest;
8667 local = &sds->local_stat;
8668 busiest = &sds->busiest_stat;
8670 if (busiest->group_type == group_imbalanced) {
8672 * In the group_imb case we cannot rely on group-wide averages
8673 * to ensure cpu-load equilibrium, look at wider averages. XXX
8675 busiest->load_per_task =
8676 min(busiest->load_per_task, sds->avg_load);
8680 * In the presence of smp nice balancing, certain scenarios can have
8681 * max load less than avg load(as we skip the groups at or below
8682 * its cpu_capacity, while calculating max_load..)
8684 if (busiest->avg_load <= sds->avg_load ||
8685 local->avg_load >= sds->avg_load) {
8686 /* Misfitting tasks should be migrated in any case */
8687 if (busiest->group_type == group_misfit_task) {
8688 env->imbalance = busiest->group_misfit_task;
8693 * Busiest group is overloaded, local is not, use the spare
8694 * cycles to maximize throughput
8696 if (busiest->group_type == group_overloaded &&
8697 local->group_type <= group_misfit_task) {
8698 env->imbalance = busiest->load_per_task;
8703 return fix_small_imbalance(env, sds);
8707 * If there aren't any idle cpus, avoid creating some.
8709 if (busiest->group_type == group_overloaded &&
8710 local->group_type == group_overloaded) {
8711 load_above_capacity = busiest->sum_nr_running *
8713 if (load_above_capacity > busiest->group_capacity)
8714 load_above_capacity -= busiest->group_capacity;
8716 load_above_capacity = ~0UL;
8720 * We're trying to get all the cpus to the average_load, so we don't
8721 * want to push ourselves above the average load, nor do we wish to
8722 * reduce the max loaded cpu below the average load. At the same time,
8723 * we also don't want to reduce the group load below the group capacity
8724 * (so that we can implement power-savings policies etc). Thus we look
8725 * for the minimum possible imbalance.
8727 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
8729 /* How much load to actually move to equalise the imbalance */
8730 env->imbalance = min(
8731 max_pull * busiest->group_capacity,
8732 (sds->avg_load - local->avg_load) * local->group_capacity
8733 ) / SCHED_CAPACITY_SCALE;
8735 /* Boost imbalance to allow misfit task to be balanced. */
8736 if (busiest->group_type == group_misfit_task)
8737 env->imbalance = max_t(long, env->imbalance,
8738 busiest->group_misfit_task);
8741 * if *imbalance is less than the average load per runnable task
8742 * there is no guarantee that any tasks will be moved so we'll have
8743 * a think about bumping its value to force at least one task to be
8746 if (env->imbalance < busiest->load_per_task)
8747 return fix_small_imbalance(env, sds);
8750 /******* find_busiest_group() helpers end here *********************/
8753 * find_busiest_group - Returns the busiest group within the sched_domain
8754 * if there is an imbalance. If there isn't an imbalance, and
8755 * the user has opted for power-savings, it returns a group whose
8756 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
8757 * such a group exists.
8759 * Also calculates the amount of weighted load which should be moved
8760 * to restore balance.
8762 * @env: The load balancing environment.
8764 * Return: - The busiest group if imbalance exists.
8765 * - If no imbalance and user has opted for power-savings balance,
8766 * return the least loaded group whose CPUs can be
8767 * put to idle by rebalancing its tasks onto our group.
8769 static struct sched_group *find_busiest_group(struct lb_env *env)
8771 struct sg_lb_stats *local, *busiest;
8772 struct sd_lb_stats sds;
8774 init_sd_lb_stats(&sds);
8777 * Compute the various statistics relavent for load balancing at
8780 update_sd_lb_stats(env, &sds);
8782 if (energy_aware() && !env->dst_rq->rd->overutilized)
8785 local = &sds.local_stat;
8786 busiest = &sds.busiest_stat;
8788 /* ASYM feature bypasses nice load balance check */
8789 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
8790 check_asym_packing(env, &sds))
8793 /* There is no busy sibling group to pull tasks from */
8794 if (!sds.busiest || busiest->sum_nr_running == 0)
8797 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
8798 / sds.total_capacity;
8801 * If the busiest group is imbalanced the below checks don't
8802 * work because they assume all things are equal, which typically
8803 * isn't true due to cpus_allowed constraints and the like.
8805 if (busiest->group_type == group_imbalanced)
8809 * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
8810 * capacities from resulting in underutilization due to avg_load.
8812 if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
8813 busiest->group_no_capacity)
8816 /* Misfitting tasks should be dealt with regardless of the avg load */
8817 if (busiest->group_type == group_misfit_task) {
8822 * If the local group is busier than the selected busiest group
8823 * don't try and pull any tasks.
8825 if (local->avg_load >= busiest->avg_load)
8829 * Don't pull any tasks if this group is already above the domain
8832 if (local->avg_load >= sds.avg_load)
8835 if (env->idle == CPU_IDLE) {
8837 * This cpu is idle. If the busiest group is not overloaded
8838 * and there is no imbalance between this and busiest group
8839 * wrt idle cpus, it is balanced. The imbalance becomes
8840 * significant if the diff is greater than 1 otherwise we
8841 * might end up to just move the imbalance on another group
8843 if ((busiest->group_type != group_overloaded) &&
8844 (local->idle_cpus <= (busiest->idle_cpus + 1)) &&
8845 !group_smaller_cpu_capacity(sds.busiest, sds.local))
8849 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
8850 * imbalance_pct to be conservative.
8852 if (100 * busiest->avg_load <=
8853 env->sd->imbalance_pct * local->avg_load)
8858 env->busiest_group_type = busiest->group_type;
8859 /* Looks like there is an imbalance. Compute it */
8860 calculate_imbalance(env, &sds);
8869 * find_busiest_queue - find the busiest runqueue among the cpus in group.
8871 static struct rq *find_busiest_queue(struct lb_env *env,
8872 struct sched_group *group)
8874 struct rq *busiest = NULL, *rq;
8875 unsigned long busiest_load = 0, busiest_capacity = 1;
8878 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
8879 unsigned long capacity, wl;
8883 rt = fbq_classify_rq(rq);
8886 * We classify groups/runqueues into three groups:
8887 * - regular: there are !numa tasks
8888 * - remote: there are numa tasks that run on the 'wrong' node
8889 * - all: there is no distinction
8891 * In order to avoid migrating ideally placed numa tasks,
8892 * ignore those when there's better options.
8894 * If we ignore the actual busiest queue to migrate another
8895 * task, the next balance pass can still reduce the busiest
8896 * queue by moving tasks around inside the node.
8898 * If we cannot move enough load due to this classification
8899 * the next pass will adjust the group classification and
8900 * allow migration of more tasks.
8902 * Both cases only affect the total convergence complexity.
8904 if (rt > env->fbq_type)
8907 capacity = capacity_of(i);
8909 wl = weighted_cpuload(i);
8912 * When comparing with imbalance, use weighted_cpuload()
8913 * which is not scaled with the cpu capacity.
8916 if (rq->nr_running == 1 && wl > env->imbalance &&
8917 !check_cpu_capacity(rq, env->sd) &&
8918 env->busiest_group_type != group_misfit_task)
8922 * For the load comparisons with the other cpu's, consider
8923 * the weighted_cpuload() scaled with the cpu capacity, so
8924 * that the load can be moved away from the cpu that is
8925 * potentially running at a lower capacity.
8927 * Thus we're looking for max(wl_i / capacity_i), crosswise
8928 * multiplication to rid ourselves of the division works out
8929 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
8930 * our previous maximum.
8932 if (wl * busiest_capacity > busiest_load * capacity) {
8934 busiest_capacity = capacity;
8943 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
8944 * so long as it is large enough.
8946 #define MAX_PINNED_INTERVAL 512
8948 /* Working cpumask for load_balance and load_balance_newidle. */
8949 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
8951 static int need_active_balance(struct lb_env *env)
8953 struct sched_domain *sd = env->sd;
8955 if (env->idle == CPU_NEWLY_IDLE) {
8958 * ASYM_PACKING needs to force migrate tasks from busy but
8959 * higher numbered CPUs in order to pack all tasks in the
8960 * lowest numbered CPUs.
8962 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
8967 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
8968 * It's worth migrating the task if the src_cpu's capacity is reduced
8969 * because of other sched_class or IRQs if more capacity stays
8970 * available on dst_cpu.
8972 if ((env->idle != CPU_NOT_IDLE) &&
8973 (env->src_rq->cfs.h_nr_running == 1)) {
8974 if ((check_cpu_capacity(env->src_rq, sd)) &&
8975 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
8979 if ((capacity_of(env->src_cpu) < capacity_of(env->dst_cpu)) &&
8980 ((capacity_orig_of(env->src_cpu) < capacity_orig_of(env->dst_cpu))) &&
8981 env->src_rq->cfs.h_nr_running == 1 &&
8982 cpu_overutilized(env->src_cpu) &&
8983 !cpu_overutilized(env->dst_cpu)) {
8987 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
8990 static int active_load_balance_cpu_stop(void *data);
8992 static int should_we_balance(struct lb_env *env)
8994 struct sched_group *sg = env->sd->groups;
8995 struct cpumask *sg_cpus, *sg_mask;
8996 int cpu, balance_cpu = -1;
8999 * In the newly idle case, we will allow all the cpu's
9000 * to do the newly idle load balance.
9002 if (env->idle == CPU_NEWLY_IDLE)
9005 sg_cpus = sched_group_cpus(sg);
9006 sg_mask = sched_group_mask(sg);
9007 /* Try to find first idle cpu */
9008 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
9009 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
9016 if (balance_cpu == -1)
9017 balance_cpu = group_balance_cpu(sg);
9020 * First idle cpu or the first cpu(busiest) in this sched group
9021 * is eligible for doing load balancing at this and above domains.
9023 return balance_cpu == env->dst_cpu;
9027 * Check this_cpu to ensure it is balanced within domain. Attempt to move
9028 * tasks if there is an imbalance.
9030 static int load_balance(int this_cpu, struct rq *this_rq,
9031 struct sched_domain *sd, enum cpu_idle_type idle,
9032 int *continue_balancing)
9034 int ld_moved, cur_ld_moved, active_balance = 0;
9035 struct sched_domain *sd_parent = lb_sd_parent(sd) ? sd->parent : NULL;
9036 struct sched_group *group;
9038 unsigned long flags;
9039 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
9041 struct lb_env env = {
9043 .dst_cpu = this_cpu,
9045 .dst_grpmask = sched_group_cpus(sd->groups),
9047 .loop_break = sched_nr_migrate_break,
9050 .tasks = LIST_HEAD_INIT(env.tasks),
9054 * For NEWLY_IDLE load_balancing, we don't need to consider
9055 * other cpus in our group
9057 if (idle == CPU_NEWLY_IDLE)
9058 env.dst_grpmask = NULL;
9060 cpumask_copy(cpus, cpu_active_mask);
9062 schedstat_inc(sd, lb_count[idle]);
9065 if (!should_we_balance(&env)) {
9066 *continue_balancing = 0;
9070 group = find_busiest_group(&env);
9072 schedstat_inc(sd, lb_nobusyg[idle]);
9076 busiest = find_busiest_queue(&env, group);
9078 schedstat_inc(sd, lb_nobusyq[idle]);
9082 BUG_ON(busiest == env.dst_rq);
9084 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
9086 env.src_cpu = busiest->cpu;
9087 env.src_rq = busiest;
9090 if (busiest->nr_running > 1) {
9092 * Attempt to move tasks. If find_busiest_group has found
9093 * an imbalance but busiest->nr_running <= 1, the group is
9094 * still unbalanced. ld_moved simply stays zero, so it is
9095 * correctly treated as an imbalance.
9097 env.flags |= LBF_ALL_PINNED;
9098 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
9101 raw_spin_lock_irqsave(&busiest->lock, flags);
9102 update_rq_clock(busiest);
9105 * cur_ld_moved - load moved in current iteration
9106 * ld_moved - cumulative load moved across iterations
9108 cur_ld_moved = detach_tasks(&env);
9111 * We've detached some tasks from busiest_rq. Every
9112 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9113 * unlock busiest->lock, and we are able to be sure
9114 * that nobody can manipulate the tasks in parallel.
9115 * See task_rq_lock() family for the details.
9118 raw_spin_unlock(&busiest->lock);
9122 ld_moved += cur_ld_moved;
9125 local_irq_restore(flags);
9127 if (env.flags & LBF_NEED_BREAK) {
9128 env.flags &= ~LBF_NEED_BREAK;
9133 * Revisit (affine) tasks on src_cpu that couldn't be moved to
9134 * us and move them to an alternate dst_cpu in our sched_group
9135 * where they can run. The upper limit on how many times we
9136 * iterate on same src_cpu is dependent on number of cpus in our
9139 * This changes load balance semantics a bit on who can move
9140 * load to a given_cpu. In addition to the given_cpu itself
9141 * (or a ilb_cpu acting on its behalf where given_cpu is
9142 * nohz-idle), we now have balance_cpu in a position to move
9143 * load to given_cpu. In rare situations, this may cause
9144 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
9145 * _independently_ and at _same_ time to move some load to
9146 * given_cpu) causing exceess load to be moved to given_cpu.
9147 * This however should not happen so much in practice and
9148 * moreover subsequent load balance cycles should correct the
9149 * excess load moved.
9151 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
9153 /* Prevent to re-select dst_cpu via env's cpus */
9154 cpumask_clear_cpu(env.dst_cpu, env.cpus);
9156 env.dst_rq = cpu_rq(env.new_dst_cpu);
9157 env.dst_cpu = env.new_dst_cpu;
9158 env.flags &= ~LBF_DST_PINNED;
9160 env.loop_break = sched_nr_migrate_break;
9163 * Go back to "more_balance" rather than "redo" since we
9164 * need to continue with same src_cpu.
9170 * We failed to reach balance because of affinity.
9173 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9175 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
9176 *group_imbalance = 1;
9179 /* All tasks on this runqueue were pinned by CPU affinity */
9180 if (unlikely(env.flags & LBF_ALL_PINNED)) {
9181 cpumask_clear_cpu(cpu_of(busiest), cpus);
9182 if (!cpumask_empty(cpus)) {
9184 env.loop_break = sched_nr_migrate_break;
9187 goto out_all_pinned;
9192 schedstat_inc(sd, lb_failed[idle]);
9194 * Increment the failure counter only on periodic balance.
9195 * We do not want newidle balance, which can be very
9196 * frequent, pollute the failure counter causing
9197 * excessive cache_hot migrations and active balances.
9199 if (idle != CPU_NEWLY_IDLE)
9200 if (env.src_grp_nr_running > 1)
9201 sd->nr_balance_failed++;
9203 if (need_active_balance(&env)) {
9204 raw_spin_lock_irqsave(&busiest->lock, flags);
9206 /* don't kick the active_load_balance_cpu_stop,
9207 * if the curr task on busiest cpu can't be
9210 if (!cpumask_test_cpu(this_cpu,
9211 tsk_cpus_allowed(busiest->curr))) {
9212 raw_spin_unlock_irqrestore(&busiest->lock,
9214 env.flags |= LBF_ALL_PINNED;
9215 goto out_one_pinned;
9219 * ->active_balance synchronizes accesses to
9220 * ->active_balance_work. Once set, it's cleared
9221 * only after active load balance is finished.
9223 if (!busiest->active_balance) {
9224 busiest->active_balance = 1;
9225 busiest->push_cpu = this_cpu;
9228 raw_spin_unlock_irqrestore(&busiest->lock, flags);
9230 if (active_balance) {
9231 stop_one_cpu_nowait(cpu_of(busiest),
9232 active_load_balance_cpu_stop, busiest,
9233 &busiest->active_balance_work);
9237 * We've kicked active balancing, reset the failure
9240 sd->nr_balance_failed = sd->cache_nice_tries+1;
9243 sd->nr_balance_failed = 0;
9245 if (likely(!active_balance)) {
9246 /* We were unbalanced, so reset the balancing interval */
9247 sd->balance_interval = sd->min_interval;
9250 * If we've begun active balancing, start to back off. This
9251 * case may not be covered by the all_pinned logic if there
9252 * is only 1 task on the busy runqueue (because we don't call
9255 if (sd->balance_interval < sd->max_interval)
9256 sd->balance_interval *= 2;
9263 * We reach balance although we may have faced some affinity
9264 * constraints. Clear the imbalance flag if it was set.
9267 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9269 if (*group_imbalance)
9270 *group_imbalance = 0;
9275 * We reach balance because all tasks are pinned at this level so
9276 * we can't migrate them. Let the imbalance flag set so parent level
9277 * can try to migrate them.
9279 schedstat_inc(sd, lb_balanced[idle]);
9281 sd->nr_balance_failed = 0;
9284 /* tune up the balancing interval */
9285 if (((env.flags & LBF_ALL_PINNED) &&
9286 sd->balance_interval < MAX_PINNED_INTERVAL) ||
9287 (sd->balance_interval < sd->max_interval))
9288 sd->balance_interval *= 2;
9295 static inline unsigned long
9296 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
9298 unsigned long interval = sd->balance_interval;
9301 interval *= sd->busy_factor;
9303 /* scale ms to jiffies */
9304 interval = msecs_to_jiffies(interval);
9305 interval = clamp(interval, 1UL, max_load_balance_interval);
9311 update_next_balance(struct sched_domain *sd, int cpu_busy, unsigned long *next_balance)
9313 unsigned long interval, next;
9315 interval = get_sd_balance_interval(sd, cpu_busy);
9316 next = sd->last_balance + interval;
9318 if (time_after(*next_balance, next))
9319 *next_balance = next;
9323 * idle_balance is called by schedule() if this_cpu is about to become
9324 * idle. Attempts to pull tasks from other CPUs.
9326 static int idle_balance(struct rq *this_rq)
9328 unsigned long next_balance = jiffies + HZ;
9329 int this_cpu = this_rq->cpu;
9330 struct sched_domain *sd;
9331 int pulled_task = 0;
9334 idle_enter_fair(this_rq);
9337 * We must set idle_stamp _before_ calling idle_balance(), such that we
9338 * measure the duration of idle_balance() as idle time.
9340 this_rq->idle_stamp = rq_clock(this_rq);
9342 if (!energy_aware() &&
9343 (this_rq->avg_idle < sysctl_sched_migration_cost ||
9344 !this_rq->rd->overload)) {
9346 sd = rcu_dereference_check_sched_domain(this_rq->sd);
9348 update_next_balance(sd, 0, &next_balance);
9354 raw_spin_unlock(&this_rq->lock);
9356 update_blocked_averages(this_cpu);
9358 for_each_domain(this_cpu, sd) {
9359 int continue_balancing = 1;
9360 u64 t0, domain_cost;
9362 if (!(sd->flags & SD_LOAD_BALANCE))
9365 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
9366 update_next_balance(sd, 0, &next_balance);
9370 if (sd->flags & SD_BALANCE_NEWIDLE) {
9371 t0 = sched_clock_cpu(this_cpu);
9373 pulled_task = load_balance(this_cpu, this_rq,
9375 &continue_balancing);
9377 domain_cost = sched_clock_cpu(this_cpu) - t0;
9378 if (domain_cost > sd->max_newidle_lb_cost)
9379 sd->max_newidle_lb_cost = domain_cost;
9381 curr_cost += domain_cost;
9384 update_next_balance(sd, 0, &next_balance);
9387 * Stop searching for tasks to pull if there are
9388 * now runnable tasks on this rq.
9390 if (pulled_task || this_rq->nr_running > 0)
9395 raw_spin_lock(&this_rq->lock);
9397 if (curr_cost > this_rq->max_idle_balance_cost)
9398 this_rq->max_idle_balance_cost = curr_cost;
9401 * While browsing the domains, we released the rq lock, a task could
9402 * have been enqueued in the meantime. Since we're not going idle,
9403 * pretend we pulled a task.
9405 if (this_rq->cfs.h_nr_running && !pulled_task)
9409 /* Move the next balance forward */
9410 if (time_after(this_rq->next_balance, next_balance))
9411 this_rq->next_balance = next_balance;
9413 /* Is there a task of a high priority class? */
9414 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
9418 idle_exit_fair(this_rq);
9419 this_rq->idle_stamp = 0;
9426 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
9427 * running tasks off the busiest CPU onto idle CPUs. It requires at
9428 * least 1 task to be running on each physical CPU where possible, and
9429 * avoids physical / logical imbalances.
9431 static int active_load_balance_cpu_stop(void *data)
9433 struct rq *busiest_rq = data;
9434 int busiest_cpu = cpu_of(busiest_rq);
9435 int target_cpu = busiest_rq->push_cpu;
9436 struct rq *target_rq = cpu_rq(target_cpu);
9437 struct sched_domain *sd = NULL;
9438 struct task_struct *p = NULL;
9439 struct task_struct *push_task = NULL;
9440 int push_task_detached = 0;
9441 struct lb_env env = {
9443 .dst_cpu = target_cpu,
9444 .dst_rq = target_rq,
9445 .src_cpu = busiest_rq->cpu,
9446 .src_rq = busiest_rq,
9450 raw_spin_lock_irq(&busiest_rq->lock);
9452 /* make sure the requested cpu hasn't gone down in the meantime */
9453 if (unlikely(busiest_cpu != smp_processor_id() ||
9454 !busiest_rq->active_balance))
9457 /* Is there any task to move? */
9458 if (busiest_rq->nr_running <= 1)
9462 * This condition is "impossible", if it occurs
9463 * we need to fix it. Originally reported by
9464 * Bjorn Helgaas on a 128-cpu setup.
9466 BUG_ON(busiest_rq == target_rq);
9468 push_task = busiest_rq->push_task;
9470 if (task_on_rq_queued(push_task) &&
9471 task_cpu(push_task) == busiest_cpu &&
9472 cpu_online(target_cpu)) {
9473 detach_task(push_task, &env);
9474 push_task_detached = 1;
9479 /* Search for an sd spanning us and the target CPU. */
9481 for_each_domain(target_cpu, sd) {
9482 if ((sd->flags & SD_LOAD_BALANCE) &&
9483 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
9489 schedstat_inc(sd, alb_count);
9490 update_rq_clock(busiest_rq);
9492 p = detach_one_task(&env);
9494 schedstat_inc(sd, alb_pushed);
9496 schedstat_inc(sd, alb_failed);
9500 busiest_rq->active_balance = 0;
9503 busiest_rq->push_task = NULL;
9505 raw_spin_unlock(&busiest_rq->lock);
9508 if (push_task_detached)
9509 attach_one_task(target_rq, push_task);
9510 put_task_struct(push_task);
9514 attach_one_task(target_rq, p);
9521 static inline int on_null_domain(struct rq *rq)
9523 return unlikely(!rcu_dereference_sched(rq->sd));
9526 #ifdef CONFIG_NO_HZ_COMMON
9528 * idle load balancing details
9529 * - When one of the busy CPUs notice that there may be an idle rebalancing
9530 * needed, they will kick the idle load balancer, which then does idle
9531 * load balancing for all the idle CPUs.
9533 static inline int find_new_ilb(void)
9535 int ilb = cpumask_first(nohz.idle_cpus_mask);
9537 if (ilb < nr_cpu_ids && idle_cpu(ilb))
9544 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
9545 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
9546 * CPU (if there is one).
9548 static void nohz_balancer_kick(void)
9552 nohz.next_balance++;
9554 ilb_cpu = find_new_ilb();
9556 if (ilb_cpu >= nr_cpu_ids)
9559 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
9562 * Use smp_send_reschedule() instead of resched_cpu().
9563 * This way we generate a sched IPI on the target cpu which
9564 * is idle. And the softirq performing nohz idle load balance
9565 * will be run before returning from the IPI.
9567 smp_send_reschedule(ilb_cpu);
9571 static inline void nohz_balance_exit_idle(int cpu)
9573 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
9575 * Completely isolated CPUs don't ever set, so we must test.
9577 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
9578 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
9579 atomic_dec(&nohz.nr_cpus);
9581 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
9585 static inline void set_cpu_sd_state_busy(void)
9587 struct sched_domain *sd;
9588 int cpu = smp_processor_id();
9591 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9593 if (!sd || !sd->nohz_idle)
9597 atomic_inc(&sd->groups->sgc->nr_busy_cpus);
9602 void set_cpu_sd_state_idle(void)
9604 struct sched_domain *sd;
9605 int cpu = smp_processor_id();
9608 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9610 if (!sd || sd->nohz_idle)
9614 atomic_dec(&sd->groups->sgc->nr_busy_cpus);
9620 * This routine will record that the cpu is going idle with tick stopped.
9621 * This info will be used in performing idle load balancing in the future.
9623 void nohz_balance_enter_idle(int cpu)
9626 * If this cpu is going down, then nothing needs to be done.
9628 if (!cpu_active(cpu))
9631 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
9635 * If we're a completely isolated CPU, we don't play.
9637 if (on_null_domain(cpu_rq(cpu)))
9640 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
9641 atomic_inc(&nohz.nr_cpus);
9642 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
9645 static int sched_ilb_notifier(struct notifier_block *nfb,
9646 unsigned long action, void *hcpu)
9648 switch (action & ~CPU_TASKS_FROZEN) {
9650 nohz_balance_exit_idle(smp_processor_id());
9658 static DEFINE_SPINLOCK(balancing);
9661 * Scale the max load_balance interval with the number of CPUs in the system.
9662 * This trades load-balance latency on larger machines for less cross talk.
9664 void update_max_interval(void)
9666 max_load_balance_interval = HZ*num_online_cpus()/10;
9670 * It checks each scheduling domain to see if it is due to be balanced,
9671 * and initiates a balancing operation if so.
9673 * Balancing parameters are set up in init_sched_domains.
9675 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
9677 int continue_balancing = 1;
9679 unsigned long interval;
9680 struct sched_domain *sd;
9681 /* Earliest time when we have to do rebalance again */
9682 unsigned long next_balance = jiffies + 60*HZ;
9683 int update_next_balance = 0;
9684 int need_serialize, need_decay = 0;
9687 update_blocked_averages(cpu);
9690 for_each_domain(cpu, sd) {
9692 * Decay the newidle max times here because this is a regular
9693 * visit to all the domains. Decay ~1% per second.
9695 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
9696 sd->max_newidle_lb_cost =
9697 (sd->max_newidle_lb_cost * 253) / 256;
9698 sd->next_decay_max_lb_cost = jiffies + HZ;
9701 max_cost += sd->max_newidle_lb_cost;
9703 if (!(sd->flags & SD_LOAD_BALANCE))
9707 * Stop the load balance at this level. There is another
9708 * CPU in our sched group which is doing load balancing more
9711 if (!continue_balancing) {
9717 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
9719 need_serialize = sd->flags & SD_SERIALIZE;
9720 if (need_serialize) {
9721 if (!spin_trylock(&balancing))
9725 if (time_after_eq(jiffies, sd->last_balance + interval)) {
9726 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
9728 * The LBF_DST_PINNED logic could have changed
9729 * env->dst_cpu, so we can't know our idle
9730 * state even if we migrated tasks. Update it.
9732 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
9734 sd->last_balance = jiffies;
9735 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
9738 spin_unlock(&balancing);
9740 if (time_after(next_balance, sd->last_balance + interval)) {
9741 next_balance = sd->last_balance + interval;
9742 update_next_balance = 1;
9747 * Ensure the rq-wide value also decays but keep it at a
9748 * reasonable floor to avoid funnies with rq->avg_idle.
9750 rq->max_idle_balance_cost =
9751 max((u64)sysctl_sched_migration_cost, max_cost);
9756 * next_balance will be updated only when there is a need.
9757 * When the cpu is attached to null domain for ex, it will not be
9760 if (likely(update_next_balance)) {
9761 rq->next_balance = next_balance;
9763 #ifdef CONFIG_NO_HZ_COMMON
9765 * If this CPU has been elected to perform the nohz idle
9766 * balance. Other idle CPUs have already rebalanced with
9767 * nohz_idle_balance() and nohz.next_balance has been
9768 * updated accordingly. This CPU is now running the idle load
9769 * balance for itself and we need to update the
9770 * nohz.next_balance accordingly.
9772 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
9773 nohz.next_balance = rq->next_balance;
9778 #ifdef CONFIG_NO_HZ_COMMON
9780 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
9781 * rebalancing for all the cpus for whom scheduler ticks are stopped.
9783 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
9785 int this_cpu = this_rq->cpu;
9788 /* Earliest time when we have to do rebalance again */
9789 unsigned long next_balance = jiffies + 60*HZ;
9790 int update_next_balance = 0;
9792 if (idle != CPU_IDLE ||
9793 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
9796 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
9797 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
9801 * If this cpu gets work to do, stop the load balancing
9802 * work being done for other cpus. Next load
9803 * balancing owner will pick it up.
9808 rq = cpu_rq(balance_cpu);
9811 * If time for next balance is due,
9814 if (time_after_eq(jiffies, rq->next_balance)) {
9815 raw_spin_lock_irq(&rq->lock);
9816 update_rq_clock(rq);
9817 update_idle_cpu_load(rq);
9818 raw_spin_unlock_irq(&rq->lock);
9819 rebalance_domains(rq, CPU_IDLE);
9822 if (time_after(next_balance, rq->next_balance)) {
9823 next_balance = rq->next_balance;
9824 update_next_balance = 1;
9829 * next_balance will be updated only when there is a need.
9830 * When the CPU is attached to null domain for ex, it will not be
9833 if (likely(update_next_balance))
9834 nohz.next_balance = next_balance;
9836 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
9840 * Current heuristic for kicking the idle load balancer in the presence
9841 * of an idle cpu in the system.
9842 * - This rq has more than one task.
9843 * - This rq has at least one CFS task and the capacity of the CPU is
9844 * significantly reduced because of RT tasks or IRQs.
9845 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
9846 * multiple busy cpu.
9847 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
9848 * domain span are idle.
9850 static inline bool nohz_kick_needed(struct rq *rq)
9852 unsigned long now = jiffies;
9853 struct sched_domain *sd;
9854 struct sched_group_capacity *sgc;
9855 int nr_busy, cpu = rq->cpu;
9858 if (unlikely(rq->idle_balance))
9862 * We may be recently in ticked or tickless idle mode. At the first
9863 * busy tick after returning from idle, we will update the busy stats.
9865 set_cpu_sd_state_busy();
9866 nohz_balance_exit_idle(cpu);
9869 * None are in tickless mode and hence no need for NOHZ idle load
9872 if (likely(!atomic_read(&nohz.nr_cpus)))
9875 if (time_before(now, nohz.next_balance))
9878 if (rq->nr_running >= 2 &&
9879 (!energy_aware() || cpu_overutilized(cpu)))
9882 /* Do idle load balance if there have misfit task */
9884 return rq->misfit_task;
9887 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9889 sgc = sd->groups->sgc;
9890 nr_busy = atomic_read(&sgc->nr_busy_cpus);
9899 sd = rcu_dereference(rq->sd);
9901 if ((rq->cfs.h_nr_running >= 1) &&
9902 check_cpu_capacity(rq, sd)) {
9908 sd = rcu_dereference(per_cpu(sd_asym, cpu));
9909 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
9910 sched_domain_span(sd)) < cpu)) {
9920 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
9924 * run_rebalance_domains is triggered when needed from the scheduler tick.
9925 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
9927 static void run_rebalance_domains(struct softirq_action *h)
9929 struct rq *this_rq = this_rq();
9930 enum cpu_idle_type idle = this_rq->idle_balance ?
9931 CPU_IDLE : CPU_NOT_IDLE;
9934 * If this cpu has a pending nohz_balance_kick, then do the
9935 * balancing on behalf of the other idle cpus whose ticks are
9936 * stopped. Do nohz_idle_balance *before* rebalance_domains to
9937 * give the idle cpus a chance to load balance. Else we may
9938 * load balance only within the local sched_domain hierarchy
9939 * and abort nohz_idle_balance altogether if we pull some load.
9941 nohz_idle_balance(this_rq, idle);
9942 rebalance_domains(this_rq, idle);
9946 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
9948 void trigger_load_balance(struct rq *rq)
9950 /* Don't need to rebalance while attached to NULL domain */
9951 if (unlikely(on_null_domain(rq)))
9954 if (time_after_eq(jiffies, rq->next_balance))
9955 raise_softirq(SCHED_SOFTIRQ);
9956 #ifdef CONFIG_NO_HZ_COMMON
9957 if (nohz_kick_needed(rq))
9958 nohz_balancer_kick();
9962 static void rq_online_fair(struct rq *rq)
9966 update_runtime_enabled(rq);
9969 static void rq_offline_fair(struct rq *rq)
9973 /* Ensure any throttled groups are reachable by pick_next_task */
9974 unthrottle_offline_cfs_rqs(rq);
9978 kick_active_balance(struct rq *rq, struct task_struct *p, int new_cpu)
9982 /* Invoke active balance to force migrate currently running task */
9983 raw_spin_lock(&rq->lock);
9984 if (!rq->active_balance) {
9985 rq->active_balance = 1;
9986 rq->push_cpu = new_cpu;
9991 raw_spin_unlock(&rq->lock);
9996 void check_for_migration(struct rq *rq, struct task_struct *p)
10000 int cpu = task_cpu(p);
10002 if (energy_aware() && rq->misfit_task) {
10003 if (rq->curr->state != TASK_RUNNING ||
10004 rq->curr->nr_cpus_allowed == 1)
10007 new_cpu = select_energy_cpu_brute(p, cpu, 0);
10008 if (capacity_orig_of(new_cpu) > capacity_orig_of(cpu)) {
10009 active_balance = kick_active_balance(rq, p, new_cpu);
10010 if (active_balance)
10011 stop_one_cpu_nowait(cpu,
10012 active_load_balance_cpu_stop,
10013 rq, &rq->active_balance_work);
10018 #endif /* CONFIG_SMP */
10021 * scheduler tick hitting a task of our scheduling class:
10023 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
10025 struct cfs_rq *cfs_rq;
10026 struct sched_entity *se = &curr->se;
10028 for_each_sched_entity(se) {
10029 cfs_rq = cfs_rq_of(se);
10030 entity_tick(cfs_rq, se, queued);
10033 if (static_branch_unlikely(&sched_numa_balancing))
10034 task_tick_numa(rq, curr);
10037 if (!rq->rd->overutilized && cpu_overutilized(task_cpu(curr))) {
10038 rq->rd->overutilized = true;
10039 trace_sched_overutilized(true);
10042 rq->misfit_task = !task_fits_max(curr, rq->cpu);
10048 * called on fork with the child task as argument from the parent's context
10049 * - child not yet on the tasklist
10050 * - preemption disabled
10052 static void task_fork_fair(struct task_struct *p)
10054 struct cfs_rq *cfs_rq;
10055 struct sched_entity *se = &p->se, *curr;
10056 struct rq *rq = this_rq();
10058 raw_spin_lock(&rq->lock);
10059 update_rq_clock(rq);
10061 cfs_rq = task_cfs_rq(current);
10062 curr = cfs_rq->curr;
10064 update_curr(cfs_rq);
10065 se->vruntime = curr->vruntime;
10067 place_entity(cfs_rq, se, 1);
10069 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
10071 * Upon rescheduling, sched_class::put_prev_task() will place
10072 * 'current' within the tree based on its new key value.
10074 swap(curr->vruntime, se->vruntime);
10078 se->vruntime -= cfs_rq->min_vruntime;
10079 raw_spin_unlock(&rq->lock);
10083 * Priority of the task has changed. Check to see if we preempt
10084 * the current task.
10087 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
10089 if (!task_on_rq_queued(p))
10093 * Reschedule if we are currently running on this runqueue and
10094 * our priority decreased, or if we are not currently running on
10095 * this runqueue and our priority is higher than the current's
10097 if (rq->curr == p) {
10098 if (p->prio > oldprio)
10101 check_preempt_curr(rq, p, 0);
10104 static inline bool vruntime_normalized(struct task_struct *p)
10106 struct sched_entity *se = &p->se;
10109 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
10110 * the dequeue_entity(.flags=0) will already have normalized the
10117 * When !on_rq, vruntime of the task has usually NOT been normalized.
10118 * But there are some cases where it has already been normalized:
10120 * - A forked child which is waiting for being woken up by
10121 * wake_up_new_task().
10122 * - A task which has been woken up by try_to_wake_up() and
10123 * waiting for actually being woken up by sched_ttwu_pending().
10125 if (!se->sum_exec_runtime || p->state == TASK_WAKING)
10131 #ifdef CONFIG_FAIR_GROUP_SCHED
10133 * Propagate the changes of the sched_entity across the tg tree to make it
10134 * visible to the root
10136 static void propagate_entity_cfs_rq(struct sched_entity *se)
10138 struct cfs_rq *cfs_rq;
10140 /* Start to propagate at parent */
10143 for_each_sched_entity(se) {
10144 cfs_rq = cfs_rq_of(se);
10146 if (cfs_rq_throttled(cfs_rq))
10149 update_load_avg(se, UPDATE_TG);
10153 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
10156 static void detach_entity_cfs_rq(struct sched_entity *se)
10158 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10160 /* Catch up with the cfs_rq and remove our load when we leave */
10161 update_load_avg(se, 0);
10162 detach_entity_load_avg(cfs_rq, se);
10163 update_tg_load_avg(cfs_rq, false);
10164 propagate_entity_cfs_rq(se);
10167 static void attach_entity_cfs_rq(struct sched_entity *se)
10169 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10171 #ifdef CONFIG_FAIR_GROUP_SCHED
10173 * Since the real-depth could have been changed (only FAIR
10174 * class maintain depth value), reset depth properly.
10176 se->depth = se->parent ? se->parent->depth + 1 : 0;
10179 /* Synchronize entity with its cfs_rq */
10180 update_load_avg(se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
10181 attach_entity_load_avg(cfs_rq, se);
10182 update_tg_load_avg(cfs_rq, false);
10183 propagate_entity_cfs_rq(se);
10186 static void detach_task_cfs_rq(struct task_struct *p)
10188 struct sched_entity *se = &p->se;
10189 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10191 if (!vruntime_normalized(p)) {
10193 * Fix up our vruntime so that the current sleep doesn't
10194 * cause 'unlimited' sleep bonus.
10196 place_entity(cfs_rq, se, 0);
10197 se->vruntime -= cfs_rq->min_vruntime;
10200 detach_entity_cfs_rq(se);
10203 static void attach_task_cfs_rq(struct task_struct *p)
10205 struct sched_entity *se = &p->se;
10206 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10208 attach_entity_cfs_rq(se);
10210 if (!vruntime_normalized(p))
10211 se->vruntime += cfs_rq->min_vruntime;
10214 static void switched_from_fair(struct rq *rq, struct task_struct *p)
10216 detach_task_cfs_rq(p);
10219 static void switched_to_fair(struct rq *rq, struct task_struct *p)
10221 attach_task_cfs_rq(p);
10223 if (task_on_rq_queued(p)) {
10225 * We were most likely switched from sched_rt, so
10226 * kick off the schedule if running, otherwise just see
10227 * if we can still preempt the current task.
10232 check_preempt_curr(rq, p, 0);
10236 /* Account for a task changing its policy or group.
10238 * This routine is mostly called to set cfs_rq->curr field when a task
10239 * migrates between groups/classes.
10241 static void set_curr_task_fair(struct rq *rq)
10243 struct sched_entity *se = &rq->curr->se;
10245 for_each_sched_entity(se) {
10246 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10248 set_next_entity(cfs_rq, se);
10249 /* ensure bandwidth has been allocated on our new cfs_rq */
10250 account_cfs_rq_runtime(cfs_rq, 0);
10254 void init_cfs_rq(struct cfs_rq *cfs_rq)
10256 cfs_rq->tasks_timeline = RB_ROOT;
10257 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
10258 #ifndef CONFIG_64BIT
10259 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
10262 #ifdef CONFIG_FAIR_GROUP_SCHED
10263 cfs_rq->propagate_avg = 0;
10265 atomic_long_set(&cfs_rq->removed_load_avg, 0);
10266 atomic_long_set(&cfs_rq->removed_util_avg, 0);
10270 #ifdef CONFIG_FAIR_GROUP_SCHED
10271 static void task_set_group_fair(struct task_struct *p)
10273 struct sched_entity *se = &p->se;
10275 set_task_rq(p, task_cpu(p));
10276 se->depth = se->parent ? se->parent->depth + 1 : 0;
10279 static void task_move_group_fair(struct task_struct *p)
10281 detach_task_cfs_rq(p);
10282 set_task_rq(p, task_cpu(p));
10285 /* Tell se's cfs_rq has been changed -- migrated */
10286 p->se.avg.last_update_time = 0;
10288 attach_task_cfs_rq(p);
10291 static void task_change_group_fair(struct task_struct *p, int type)
10294 case TASK_SET_GROUP:
10295 task_set_group_fair(p);
10298 case TASK_MOVE_GROUP:
10299 task_move_group_fair(p);
10304 void free_fair_sched_group(struct task_group *tg)
10308 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
10310 for_each_possible_cpu(i) {
10312 kfree(tg->cfs_rq[i]);
10321 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
10323 struct sched_entity *se;
10324 struct cfs_rq *cfs_rq;
10328 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
10331 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
10335 tg->shares = NICE_0_LOAD;
10337 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
10339 for_each_possible_cpu(i) {
10342 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
10343 GFP_KERNEL, cpu_to_node(i));
10347 se = kzalloc_node(sizeof(struct sched_entity),
10348 GFP_KERNEL, cpu_to_node(i));
10352 init_cfs_rq(cfs_rq);
10353 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
10354 init_entity_runnable_average(se);
10356 raw_spin_lock_irq(&rq->lock);
10357 post_init_entity_util_avg(se);
10358 raw_spin_unlock_irq(&rq->lock);
10369 void unregister_fair_sched_group(struct task_group *tg)
10371 unsigned long flags;
10375 for_each_possible_cpu(cpu) {
10377 remove_entity_load_avg(tg->se[cpu]);
10380 * Only empty task groups can be destroyed; so we can speculatively
10381 * check on_list without danger of it being re-added.
10383 if (!tg->cfs_rq[cpu]->on_list)
10388 raw_spin_lock_irqsave(&rq->lock, flags);
10389 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
10390 raw_spin_unlock_irqrestore(&rq->lock, flags);
10394 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
10395 struct sched_entity *se, int cpu,
10396 struct sched_entity *parent)
10398 struct rq *rq = cpu_rq(cpu);
10402 init_cfs_rq_runtime(cfs_rq);
10404 tg->cfs_rq[cpu] = cfs_rq;
10407 /* se could be NULL for root_task_group */
10412 se->cfs_rq = &rq->cfs;
10415 se->cfs_rq = parent->my_q;
10416 se->depth = parent->depth + 1;
10420 /* guarantee group entities always have weight */
10421 update_load_set(&se->load, NICE_0_LOAD);
10422 se->parent = parent;
10425 static DEFINE_MUTEX(shares_mutex);
10427 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10430 unsigned long flags;
10433 * We can't change the weight of the root cgroup.
10438 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
10440 mutex_lock(&shares_mutex);
10441 if (tg->shares == shares)
10444 tg->shares = shares;
10445 for_each_possible_cpu(i) {
10446 struct rq *rq = cpu_rq(i);
10447 struct sched_entity *se;
10450 /* Propagate contribution to hierarchy */
10451 raw_spin_lock_irqsave(&rq->lock, flags);
10453 /* Possible calls to update_curr() need rq clock */
10454 update_rq_clock(rq);
10455 for_each_sched_entity(se) {
10456 update_load_avg(se, UPDATE_TG);
10457 update_cfs_shares(se);
10459 raw_spin_unlock_irqrestore(&rq->lock, flags);
10463 mutex_unlock(&shares_mutex);
10466 #else /* CONFIG_FAIR_GROUP_SCHED */
10468 void free_fair_sched_group(struct task_group *tg) { }
10470 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
10475 void unregister_fair_sched_group(struct task_group *tg) { }
10477 #endif /* CONFIG_FAIR_GROUP_SCHED */
10480 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
10482 struct sched_entity *se = &task->se;
10483 unsigned int rr_interval = 0;
10486 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
10489 if (rq->cfs.load.weight)
10490 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
10492 return rr_interval;
10496 * All the scheduling class methods:
10498 const struct sched_class fair_sched_class = {
10499 .next = &idle_sched_class,
10500 .enqueue_task = enqueue_task_fair,
10501 .dequeue_task = dequeue_task_fair,
10502 .yield_task = yield_task_fair,
10503 .yield_to_task = yield_to_task_fair,
10505 .check_preempt_curr = check_preempt_wakeup,
10507 .pick_next_task = pick_next_task_fair,
10508 .put_prev_task = put_prev_task_fair,
10511 .select_task_rq = select_task_rq_fair,
10512 .migrate_task_rq = migrate_task_rq_fair,
10514 .rq_online = rq_online_fair,
10515 .rq_offline = rq_offline_fair,
10517 .task_waking = task_waking_fair,
10518 .task_dead = task_dead_fair,
10519 .set_cpus_allowed = set_cpus_allowed_common,
10522 .set_curr_task = set_curr_task_fair,
10523 .task_tick = task_tick_fair,
10524 .task_fork = task_fork_fair,
10526 .prio_changed = prio_changed_fair,
10527 .switched_from = switched_from_fair,
10528 .switched_to = switched_to_fair,
10530 .get_rr_interval = get_rr_interval_fair,
10532 .update_curr = update_curr_fair,
10534 #ifdef CONFIG_FAIR_GROUP_SCHED
10535 .task_change_group = task_change_group_fair,
10539 #ifdef CONFIG_SCHED_DEBUG
10540 void print_cfs_stats(struct seq_file *m, int cpu)
10542 struct cfs_rq *cfs_rq;
10545 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
10546 print_cfs_rq(m, cpu, cfs_rq);
10550 #ifdef CONFIG_NUMA_BALANCING
10551 void show_numa_stats(struct task_struct *p, struct seq_file *m)
10554 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
10556 for_each_online_node(node) {
10557 if (p->numa_faults) {
10558 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
10559 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
10561 if (p->numa_group) {
10562 gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
10563 gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
10565 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
10568 #endif /* CONFIG_NUMA_BALANCING */
10569 #endif /* CONFIG_SCHED_DEBUG */
10571 __init void init_sched_fair_class(void)
10574 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
10576 #ifdef CONFIG_NO_HZ_COMMON
10577 nohz.next_balance = jiffies;
10578 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
10579 cpu_notifier(sched_ilb_notifier, 0);