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 delta = p->se.avg.load_sum / p->se.load.weight;
1883 *period = LOAD_AVG_MAX;
1886 p->last_sum_exec_runtime = runtime;
1887 p->last_task_numa_placement = now;
1893 * Determine the preferred nid for a task in a numa_group. This needs to
1894 * be done in a way that produces consistent results with group_weight,
1895 * otherwise workloads might not converge.
1897 static int preferred_group_nid(struct task_struct *p, int nid)
1902 /* Direct connections between all NUMA nodes. */
1903 if (sched_numa_topology_type == NUMA_DIRECT)
1907 * On a system with glueless mesh NUMA topology, group_weight
1908 * scores nodes according to the number of NUMA hinting faults on
1909 * both the node itself, and on nearby nodes.
1911 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1912 unsigned long score, max_score = 0;
1913 int node, max_node = nid;
1915 dist = sched_max_numa_distance;
1917 for_each_online_node(node) {
1918 score = group_weight(p, node, dist);
1919 if (score > max_score) {
1928 * Finding the preferred nid in a system with NUMA backplane
1929 * interconnect topology is more involved. The goal is to locate
1930 * tasks from numa_groups near each other in the system, and
1931 * untangle workloads from different sides of the system. This requires
1932 * searching down the hierarchy of node groups, recursively searching
1933 * inside the highest scoring group of nodes. The nodemask tricks
1934 * keep the complexity of the search down.
1936 nodes = node_online_map;
1937 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
1938 unsigned long max_faults = 0;
1939 nodemask_t max_group = NODE_MASK_NONE;
1942 /* Are there nodes at this distance from each other? */
1943 if (!find_numa_distance(dist))
1946 for_each_node_mask(a, nodes) {
1947 unsigned long faults = 0;
1948 nodemask_t this_group;
1949 nodes_clear(this_group);
1951 /* Sum group's NUMA faults; includes a==b case. */
1952 for_each_node_mask(b, nodes) {
1953 if (node_distance(a, b) < dist) {
1954 faults += group_faults(p, b);
1955 node_set(b, this_group);
1956 node_clear(b, nodes);
1960 /* Remember the top group. */
1961 if (faults > max_faults) {
1962 max_faults = faults;
1963 max_group = this_group;
1965 * subtle: at the smallest distance there is
1966 * just one node left in each "group", the
1967 * winner is the preferred nid.
1972 /* Next round, evaluate the nodes within max_group. */
1980 static void task_numa_placement(struct task_struct *p)
1982 int seq, nid, max_nid = -1, max_group_nid = -1;
1983 unsigned long max_faults = 0, max_group_faults = 0;
1984 unsigned long fault_types[2] = { 0, 0 };
1985 unsigned long total_faults;
1986 u64 runtime, period;
1987 spinlock_t *group_lock = NULL;
1990 * The p->mm->numa_scan_seq field gets updated without
1991 * exclusive access. Use READ_ONCE() here to ensure
1992 * that the field is read in a single access:
1994 seq = READ_ONCE(p->mm->numa_scan_seq);
1995 if (p->numa_scan_seq == seq)
1997 p->numa_scan_seq = seq;
1998 p->numa_scan_period_max = task_scan_max(p);
2000 total_faults = p->numa_faults_locality[0] +
2001 p->numa_faults_locality[1];
2002 runtime = numa_get_avg_runtime(p, &period);
2004 /* If the task is part of a group prevent parallel updates to group stats */
2005 if (p->numa_group) {
2006 group_lock = &p->numa_group->lock;
2007 spin_lock_irq(group_lock);
2010 /* Find the node with the highest number of faults */
2011 for_each_online_node(nid) {
2012 /* Keep track of the offsets in numa_faults array */
2013 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2014 unsigned long faults = 0, group_faults = 0;
2017 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2018 long diff, f_diff, f_weight;
2020 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2021 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2022 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2023 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2025 /* Decay existing window, copy faults since last scan */
2026 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2027 fault_types[priv] += p->numa_faults[membuf_idx];
2028 p->numa_faults[membuf_idx] = 0;
2031 * Normalize the faults_from, so all tasks in a group
2032 * count according to CPU use, instead of by the raw
2033 * number of faults. Tasks with little runtime have
2034 * little over-all impact on throughput, and thus their
2035 * faults are less important.
2037 f_weight = div64_u64(runtime << 16, period + 1);
2038 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2040 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2041 p->numa_faults[cpubuf_idx] = 0;
2043 p->numa_faults[mem_idx] += diff;
2044 p->numa_faults[cpu_idx] += f_diff;
2045 faults += p->numa_faults[mem_idx];
2046 p->total_numa_faults += diff;
2047 if (p->numa_group) {
2049 * safe because we can only change our own group
2051 * mem_idx represents the offset for a given
2052 * nid and priv in a specific region because it
2053 * is at the beginning of the numa_faults array.
2055 p->numa_group->faults[mem_idx] += diff;
2056 p->numa_group->faults_cpu[mem_idx] += f_diff;
2057 p->numa_group->total_faults += diff;
2058 group_faults += p->numa_group->faults[mem_idx];
2062 if (faults > max_faults) {
2063 max_faults = faults;
2067 if (group_faults > max_group_faults) {
2068 max_group_faults = group_faults;
2069 max_group_nid = nid;
2073 update_task_scan_period(p, fault_types[0], fault_types[1]);
2075 if (p->numa_group) {
2076 update_numa_active_node_mask(p->numa_group);
2077 spin_unlock_irq(group_lock);
2078 max_nid = preferred_group_nid(p, max_group_nid);
2082 /* Set the new preferred node */
2083 if (max_nid != p->numa_preferred_nid)
2084 sched_setnuma(p, max_nid);
2086 if (task_node(p) != p->numa_preferred_nid)
2087 numa_migrate_preferred(p);
2091 static inline int get_numa_group(struct numa_group *grp)
2093 return atomic_inc_not_zero(&grp->refcount);
2096 static inline void put_numa_group(struct numa_group *grp)
2098 if (atomic_dec_and_test(&grp->refcount))
2099 kfree_rcu(grp, rcu);
2102 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2105 struct numa_group *grp, *my_grp;
2106 struct task_struct *tsk;
2108 int cpu = cpupid_to_cpu(cpupid);
2111 if (unlikely(!p->numa_group)) {
2112 unsigned int size = sizeof(struct numa_group) +
2113 4*nr_node_ids*sizeof(unsigned long);
2115 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2119 atomic_set(&grp->refcount, 1);
2120 spin_lock_init(&grp->lock);
2122 /* Second half of the array tracks nids where faults happen */
2123 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2126 node_set(task_node(current), grp->active_nodes);
2128 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2129 grp->faults[i] = p->numa_faults[i];
2131 grp->total_faults = p->total_numa_faults;
2134 rcu_assign_pointer(p->numa_group, grp);
2138 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2140 if (!cpupid_match_pid(tsk, cpupid))
2143 grp = rcu_dereference(tsk->numa_group);
2147 my_grp = p->numa_group;
2152 * Only join the other group if its bigger; if we're the bigger group,
2153 * the other task will join us.
2155 if (my_grp->nr_tasks > grp->nr_tasks)
2159 * Tie-break on the grp address.
2161 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2164 /* Always join threads in the same process. */
2165 if (tsk->mm == current->mm)
2168 /* Simple filter to avoid false positives due to PID collisions */
2169 if (flags & TNF_SHARED)
2172 /* Update priv based on whether false sharing was detected */
2175 if (join && !get_numa_group(grp))
2183 BUG_ON(irqs_disabled());
2184 double_lock_irq(&my_grp->lock, &grp->lock);
2186 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2187 my_grp->faults[i] -= p->numa_faults[i];
2188 grp->faults[i] += p->numa_faults[i];
2190 my_grp->total_faults -= p->total_numa_faults;
2191 grp->total_faults += p->total_numa_faults;
2196 spin_unlock(&my_grp->lock);
2197 spin_unlock_irq(&grp->lock);
2199 rcu_assign_pointer(p->numa_group, grp);
2201 put_numa_group(my_grp);
2209 void task_numa_free(struct task_struct *p)
2211 struct numa_group *grp = p->numa_group;
2212 void *numa_faults = p->numa_faults;
2213 unsigned long flags;
2217 spin_lock_irqsave(&grp->lock, flags);
2218 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2219 grp->faults[i] -= p->numa_faults[i];
2220 grp->total_faults -= p->total_numa_faults;
2223 spin_unlock_irqrestore(&grp->lock, flags);
2224 RCU_INIT_POINTER(p->numa_group, NULL);
2225 put_numa_group(grp);
2228 p->numa_faults = NULL;
2233 * Got a PROT_NONE fault for a page on @node.
2235 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2237 struct task_struct *p = current;
2238 bool migrated = flags & TNF_MIGRATED;
2239 int cpu_node = task_node(current);
2240 int local = !!(flags & TNF_FAULT_LOCAL);
2243 if (!static_branch_likely(&sched_numa_balancing))
2246 /* for example, ksmd faulting in a user's mm */
2250 /* Allocate buffer to track faults on a per-node basis */
2251 if (unlikely(!p->numa_faults)) {
2252 int size = sizeof(*p->numa_faults) *
2253 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2255 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2256 if (!p->numa_faults)
2259 p->total_numa_faults = 0;
2260 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2264 * First accesses are treated as private, otherwise consider accesses
2265 * to be private if the accessing pid has not changed
2267 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2270 priv = cpupid_match_pid(p, last_cpupid);
2271 if (!priv && !(flags & TNF_NO_GROUP))
2272 task_numa_group(p, last_cpupid, flags, &priv);
2276 * If a workload spans multiple NUMA nodes, a shared fault that
2277 * occurs wholly within the set of nodes that the workload is
2278 * actively using should be counted as local. This allows the
2279 * scan rate to slow down when a workload has settled down.
2281 if (!priv && !local && p->numa_group &&
2282 node_isset(cpu_node, p->numa_group->active_nodes) &&
2283 node_isset(mem_node, p->numa_group->active_nodes))
2286 task_numa_placement(p);
2289 * Retry task to preferred node migration periodically, in case it
2290 * case it previously failed, or the scheduler moved us.
2292 if (time_after(jiffies, p->numa_migrate_retry))
2293 numa_migrate_preferred(p);
2296 p->numa_pages_migrated += pages;
2297 if (flags & TNF_MIGRATE_FAIL)
2298 p->numa_faults_locality[2] += pages;
2300 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2301 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2302 p->numa_faults_locality[local] += pages;
2305 static void reset_ptenuma_scan(struct task_struct *p)
2308 * We only did a read acquisition of the mmap sem, so
2309 * p->mm->numa_scan_seq is written to without exclusive access
2310 * and the update is not guaranteed to be atomic. That's not
2311 * much of an issue though, since this is just used for
2312 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2313 * expensive, to avoid any form of compiler optimizations:
2315 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
2316 p->mm->numa_scan_offset = 0;
2320 * The expensive part of numa migration is done from task_work context.
2321 * Triggered from task_tick_numa().
2323 void task_numa_work(struct callback_head *work)
2325 unsigned long migrate, next_scan, now = jiffies;
2326 struct task_struct *p = current;
2327 struct mm_struct *mm = p->mm;
2328 struct vm_area_struct *vma;
2329 unsigned long start, end;
2330 unsigned long nr_pte_updates = 0;
2331 long pages, virtpages;
2333 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
2335 work->next = work; /* protect against double add */
2337 * Who cares about NUMA placement when they're dying.
2339 * NOTE: make sure not to dereference p->mm before this check,
2340 * exit_task_work() happens _after_ exit_mm() so we could be called
2341 * without p->mm even though we still had it when we enqueued this
2344 if (p->flags & PF_EXITING)
2347 if (!mm->numa_next_scan) {
2348 mm->numa_next_scan = now +
2349 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2353 * Enforce maximal scan/migration frequency..
2355 migrate = mm->numa_next_scan;
2356 if (time_before(now, migrate))
2359 if (p->numa_scan_period == 0) {
2360 p->numa_scan_period_max = task_scan_max(p);
2361 p->numa_scan_period = task_scan_min(p);
2364 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2365 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2369 * Delay this task enough that another task of this mm will likely win
2370 * the next time around.
2372 p->node_stamp += 2 * TICK_NSEC;
2374 start = mm->numa_scan_offset;
2375 pages = sysctl_numa_balancing_scan_size;
2376 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2377 virtpages = pages * 8; /* Scan up to this much virtual space */
2382 if (!down_read_trylock(&mm->mmap_sem))
2384 vma = find_vma(mm, start);
2386 reset_ptenuma_scan(p);
2390 for (; vma; vma = vma->vm_next) {
2391 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
2392 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
2397 * Shared library pages mapped by multiple processes are not
2398 * migrated as it is expected they are cache replicated. Avoid
2399 * hinting faults in read-only file-backed mappings or the vdso
2400 * as migrating the pages will be of marginal benefit.
2403 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2407 * Skip inaccessible VMAs to avoid any confusion between
2408 * PROT_NONE and NUMA hinting ptes
2410 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2414 start = max(start, vma->vm_start);
2415 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2416 end = min(end, vma->vm_end);
2417 nr_pte_updates = change_prot_numa(vma, start, end);
2420 * Try to scan sysctl_numa_balancing_size worth of
2421 * hpages that have at least one present PTE that
2422 * is not already pte-numa. If the VMA contains
2423 * areas that are unused or already full of prot_numa
2424 * PTEs, scan up to virtpages, to skip through those
2428 pages -= (end - start) >> PAGE_SHIFT;
2429 virtpages -= (end - start) >> PAGE_SHIFT;
2432 if (pages <= 0 || virtpages <= 0)
2436 } while (end != vma->vm_end);
2441 * It is possible to reach the end of the VMA list but the last few
2442 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2443 * would find the !migratable VMA on the next scan but not reset the
2444 * scanner to the start so check it now.
2447 mm->numa_scan_offset = start;
2449 reset_ptenuma_scan(p);
2450 up_read(&mm->mmap_sem);
2454 * Drive the periodic memory faults..
2456 void task_tick_numa(struct rq *rq, struct task_struct *curr)
2458 struct callback_head *work = &curr->numa_work;
2462 * We don't care about NUMA placement if we don't have memory.
2464 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2468 * Using runtime rather than walltime has the dual advantage that
2469 * we (mostly) drive the selection from busy threads and that the
2470 * task needs to have done some actual work before we bother with
2473 now = curr->se.sum_exec_runtime;
2474 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2476 if (now > curr->node_stamp + period) {
2477 if (!curr->node_stamp)
2478 curr->numa_scan_period = task_scan_min(curr);
2479 curr->node_stamp += period;
2481 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2482 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2483 task_work_add(curr, work, true);
2488 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2492 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2496 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2499 #endif /* CONFIG_NUMA_BALANCING */
2502 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2504 update_load_add(&cfs_rq->load, se->load.weight);
2505 if (!parent_entity(se))
2506 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
2508 if (entity_is_task(se)) {
2509 struct rq *rq = rq_of(cfs_rq);
2511 account_numa_enqueue(rq, task_of(se));
2512 list_add(&se->group_node, &rq->cfs_tasks);
2515 cfs_rq->nr_running++;
2519 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2521 update_load_sub(&cfs_rq->load, se->load.weight);
2522 if (!parent_entity(se))
2523 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
2524 if (entity_is_task(se)) {
2525 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
2526 list_del_init(&se->group_node);
2528 cfs_rq->nr_running--;
2531 #ifdef CONFIG_FAIR_GROUP_SCHED
2533 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2535 long tg_weight, load, shares;
2538 * This really should be: cfs_rq->avg.load_avg, but instead we use
2539 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2540 * the shares for small weight interactive tasks.
2542 load = scale_load_down(cfs_rq->load.weight);
2544 tg_weight = atomic_long_read(&tg->load_avg);
2546 /* Ensure tg_weight >= load */
2547 tg_weight -= cfs_rq->tg_load_avg_contrib;
2550 shares = (tg->shares * load);
2552 shares /= tg_weight;
2554 if (shares < MIN_SHARES)
2555 shares = MIN_SHARES;
2556 if (shares > tg->shares)
2557 shares = tg->shares;
2561 # else /* CONFIG_SMP */
2562 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2566 # endif /* CONFIG_SMP */
2568 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2569 unsigned long weight)
2572 /* commit outstanding execution time */
2573 if (cfs_rq->curr == se)
2574 update_curr(cfs_rq);
2575 account_entity_dequeue(cfs_rq, se);
2578 update_load_set(&se->load, weight);
2581 account_entity_enqueue(cfs_rq, se);
2584 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2586 static void update_cfs_shares(struct sched_entity *se)
2588 struct cfs_rq *cfs_rq = group_cfs_rq(se);
2589 struct task_group *tg;
2595 if (throttled_hierarchy(cfs_rq))
2601 if (likely(se->load.weight == tg->shares))
2604 shares = calc_cfs_shares(cfs_rq, tg);
2606 reweight_entity(cfs_rq_of(se), se, shares);
2609 #else /* CONFIG_FAIR_GROUP_SCHED */
2610 static inline void update_cfs_shares(struct sched_entity *se)
2613 #endif /* CONFIG_FAIR_GROUP_SCHED */
2616 /* Precomputed fixed inverse multiplies for multiplication by y^n */
2617 static const u32 runnable_avg_yN_inv[] = {
2618 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2619 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2620 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2621 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2622 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2623 0x85aac367, 0x82cd8698,
2627 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2628 * over-estimates when re-combining.
2630 static const u32 runnable_avg_yN_sum[] = {
2631 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2632 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2633 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2638 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2640 static __always_inline u64 decay_load(u64 val, u64 n)
2642 unsigned int local_n;
2646 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2649 /* after bounds checking we can collapse to 32-bit */
2653 * As y^PERIOD = 1/2, we can combine
2654 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2655 * With a look-up table which covers y^n (n<PERIOD)
2657 * To achieve constant time decay_load.
2659 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2660 val >>= local_n / LOAD_AVG_PERIOD;
2661 local_n %= LOAD_AVG_PERIOD;
2664 val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
2669 * For updates fully spanning n periods, the contribution to runnable
2670 * average will be: \Sum 1024*y^n
2672 * We can compute this reasonably efficiently by combining:
2673 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2675 static u32 __compute_runnable_contrib(u64 n)
2679 if (likely(n <= LOAD_AVG_PERIOD))
2680 return runnable_avg_yN_sum[n];
2681 else if (unlikely(n >= LOAD_AVG_MAX_N))
2682 return LOAD_AVG_MAX;
2684 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
2686 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
2687 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
2689 n -= LOAD_AVG_PERIOD;
2690 } while (n > LOAD_AVG_PERIOD);
2692 contrib = decay_load(contrib, n);
2693 return contrib + runnable_avg_yN_sum[n];
2696 #if (SCHED_LOAD_SHIFT - SCHED_LOAD_RESOLUTION) != 10 || SCHED_CAPACITY_SHIFT != 10
2697 #error "load tracking assumes 2^10 as unit"
2700 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
2703 * We can represent the historical contribution to runnable average as the
2704 * coefficients of a geometric series. To do this we sub-divide our runnable
2705 * history into segments of approximately 1ms (1024us); label the segment that
2706 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2708 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2710 * (now) (~1ms ago) (~2ms ago)
2712 * Let u_i denote the fraction of p_i that the entity was runnable.
2714 * We then designate the fractions u_i as our co-efficients, yielding the
2715 * following representation of historical load:
2716 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2718 * We choose y based on the with of a reasonably scheduling period, fixing:
2721 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2722 * approximately half as much as the contribution to load within the last ms
2725 * When a period "rolls over" and we have new u_0`, multiplying the previous
2726 * sum again by y is sufficient to update:
2727 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2728 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2730 static __always_inline int
2731 __update_load_avg(u64 now, int cpu, struct sched_avg *sa,
2732 unsigned long weight, int running, struct cfs_rq *cfs_rq)
2734 u64 delta, scaled_delta, periods;
2736 unsigned int delta_w, scaled_delta_w, decayed = 0;
2737 unsigned long scale_freq, scale_cpu;
2739 delta = now - sa->last_update_time;
2741 * This should only happen when time goes backwards, which it
2742 * unfortunately does during sched clock init when we swap over to TSC.
2744 if ((s64)delta < 0) {
2745 sa->last_update_time = now;
2750 * Use 1024ns as the unit of measurement since it's a reasonable
2751 * approximation of 1us and fast to compute.
2756 sa->last_update_time = now;
2758 scale_freq = arch_scale_freq_capacity(NULL, cpu);
2759 scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
2760 trace_sched_contrib_scale_f(cpu, scale_freq, scale_cpu);
2762 /* delta_w is the amount already accumulated against our next period */
2763 delta_w = sa->period_contrib;
2764 if (delta + delta_w >= 1024) {
2767 /* how much left for next period will start over, we don't know yet */
2768 sa->period_contrib = 0;
2771 * Now that we know we're crossing a period boundary, figure
2772 * out how much from delta we need to complete the current
2773 * period and accrue it.
2775 delta_w = 1024 - delta_w;
2776 scaled_delta_w = cap_scale(delta_w, scale_freq);
2778 sa->load_sum += weight * scaled_delta_w;
2780 cfs_rq->runnable_load_sum +=
2781 weight * scaled_delta_w;
2785 sa->util_sum += scaled_delta_w * scale_cpu;
2789 /* Figure out how many additional periods this update spans */
2790 periods = delta / 1024;
2793 sa->load_sum = decay_load(sa->load_sum, periods + 1);
2795 cfs_rq->runnable_load_sum =
2796 decay_load(cfs_rq->runnable_load_sum, periods + 1);
2798 sa->util_sum = decay_load((u64)(sa->util_sum), periods + 1);
2800 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
2801 contrib = __compute_runnable_contrib(periods);
2802 contrib = cap_scale(contrib, scale_freq);
2804 sa->load_sum += weight * contrib;
2806 cfs_rq->runnable_load_sum += weight * contrib;
2809 sa->util_sum += contrib * scale_cpu;
2812 /* Remainder of delta accrued against u_0` */
2813 scaled_delta = cap_scale(delta, scale_freq);
2815 sa->load_sum += weight * scaled_delta;
2817 cfs_rq->runnable_load_sum += weight * scaled_delta;
2820 sa->util_sum += scaled_delta * scale_cpu;
2822 sa->period_contrib += delta;
2825 sa->load_avg = div_u64(sa->load_sum, LOAD_AVG_MAX);
2827 cfs_rq->runnable_load_avg =
2828 div_u64(cfs_rq->runnable_load_sum, LOAD_AVG_MAX);
2830 sa->util_avg = sa->util_sum / LOAD_AVG_MAX;
2837 * Signed add and clamp on underflow.
2839 * Explicitly do a load-store to ensure the intermediate value never hits
2840 * memory. This allows lockless observations without ever seeing the negative
2843 #define add_positive(_ptr, _val) do { \
2844 typeof(_ptr) ptr = (_ptr); \
2845 typeof(_val) val = (_val); \
2846 typeof(*ptr) res, var = READ_ONCE(*ptr); \
2850 if (val < 0 && res > var) \
2853 WRITE_ONCE(*ptr, res); \
2856 #ifdef CONFIG_FAIR_GROUP_SCHED
2858 * update_tg_load_avg - update the tg's load avg
2859 * @cfs_rq: the cfs_rq whose avg changed
2860 * @force: update regardless of how small the difference
2862 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
2863 * However, because tg->load_avg is a global value there are performance
2866 * In order to avoid having to look at the other cfs_rq's, we use a
2867 * differential update where we store the last value we propagated. This in
2868 * turn allows skipping updates if the differential is 'small'.
2870 * Updating tg's load_avg is necessary before update_cfs_share() (which is
2871 * done) and effective_load() (which is not done because it is too costly).
2873 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
2875 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
2878 * No need to update load_avg for root_task_group as it is not used.
2880 if (cfs_rq->tg == &root_task_group)
2883 if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
2884 atomic_long_add(delta, &cfs_rq->tg->load_avg);
2885 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
2890 * Called within set_task_rq() right before setting a task's cpu. The
2891 * caller only guarantees p->pi_lock is held; no other assumptions,
2892 * including the state of rq->lock, should be made.
2894 void set_task_rq_fair(struct sched_entity *se,
2895 struct cfs_rq *prev, struct cfs_rq *next)
2897 if (!sched_feat(ATTACH_AGE_LOAD))
2901 * We are supposed to update the task to "current" time, then its up to
2902 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
2903 * getting what current time is, so simply throw away the out-of-date
2904 * time. This will result in the wakee task is less decayed, but giving
2905 * the wakee more load sounds not bad.
2907 if (se->avg.last_update_time && prev) {
2908 u64 p_last_update_time;
2909 u64 n_last_update_time;
2911 #ifndef CONFIG_64BIT
2912 u64 p_last_update_time_copy;
2913 u64 n_last_update_time_copy;
2916 p_last_update_time_copy = prev->load_last_update_time_copy;
2917 n_last_update_time_copy = next->load_last_update_time_copy;
2921 p_last_update_time = prev->avg.last_update_time;
2922 n_last_update_time = next->avg.last_update_time;
2924 } while (p_last_update_time != p_last_update_time_copy ||
2925 n_last_update_time != n_last_update_time_copy);
2927 p_last_update_time = prev->avg.last_update_time;
2928 n_last_update_time = next->avg.last_update_time;
2930 __update_load_avg(p_last_update_time, cpu_of(rq_of(prev)),
2931 &se->avg, 0, 0, NULL);
2932 se->avg.last_update_time = n_last_update_time;
2936 /* Take into account change of utilization of a child task group */
2938 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se)
2940 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
2941 long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
2943 /* Nothing to update */
2947 /* Set new sched_entity's utilization */
2948 se->avg.util_avg = gcfs_rq->avg.util_avg;
2949 se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
2951 /* Update parent cfs_rq utilization */
2952 add_positive(&cfs_rq->avg.util_avg, delta);
2953 cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
2956 /* Take into account change of load of a child task group */
2958 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se)
2960 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
2961 long delta, load = gcfs_rq->avg.load_avg;
2964 * If the load of group cfs_rq is null, the load of the
2965 * sched_entity will also be null so we can skip the formula
2970 /* Get tg's load and ensure tg_load > 0 */
2971 tg_load = atomic_long_read(&gcfs_rq->tg->load_avg) + 1;
2973 /* Ensure tg_load >= load and updated with current load*/
2974 tg_load -= gcfs_rq->tg_load_avg_contrib;
2978 * We need to compute a correction term in the case that the
2979 * task group is consuming more CPU than a task of equal
2980 * weight. A task with a weight equals to tg->shares will have
2981 * a load less or equal to scale_load_down(tg->shares).
2982 * Similarly, the sched_entities that represent the task group
2983 * at parent level, can't have a load higher than
2984 * scale_load_down(tg->shares). And the Sum of sched_entities'
2985 * load must be <= scale_load_down(tg->shares).
2987 if (tg_load > scale_load_down(gcfs_rq->tg->shares)) {
2988 /* scale gcfs_rq's load into tg's shares*/
2989 load *= scale_load_down(gcfs_rq->tg->shares);
2994 delta = load - se->avg.load_avg;
2996 /* Nothing to update */
3000 /* Set new sched_entity's load */
3001 se->avg.load_avg = load;
3002 se->avg.load_sum = se->avg.load_avg * LOAD_AVG_MAX;
3004 /* Update parent cfs_rq load */
3005 add_positive(&cfs_rq->avg.load_avg, delta);
3006 cfs_rq->avg.load_sum = cfs_rq->avg.load_avg * LOAD_AVG_MAX;
3009 * If the sched_entity is already enqueued, we also have to update the
3010 * runnable load avg.
3013 /* Update parent cfs_rq runnable_load_avg */
3014 add_positive(&cfs_rq->runnable_load_avg, delta);
3015 cfs_rq->runnable_load_sum = cfs_rq->runnable_load_avg * LOAD_AVG_MAX;
3019 static inline void set_tg_cfs_propagate(struct cfs_rq *cfs_rq)
3021 cfs_rq->propagate_avg = 1;
3024 static inline int test_and_clear_tg_cfs_propagate(struct sched_entity *se)
3026 struct cfs_rq *cfs_rq = group_cfs_rq(se);
3028 if (!cfs_rq->propagate_avg)
3031 cfs_rq->propagate_avg = 0;
3035 /* Update task and its cfs_rq load average */
3036 static inline int propagate_entity_load_avg(struct sched_entity *se)
3038 struct cfs_rq *cfs_rq;
3040 if (entity_is_task(se))
3043 if (!test_and_clear_tg_cfs_propagate(se))
3046 cfs_rq = cfs_rq_of(se);
3048 set_tg_cfs_propagate(cfs_rq);
3050 update_tg_cfs_util(cfs_rq, se);
3051 update_tg_cfs_load(cfs_rq, se);
3056 #else /* CONFIG_FAIR_GROUP_SCHED */
3058 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
3060 static inline int propagate_entity_load_avg(struct sched_entity *se)
3065 static inline void set_tg_cfs_propagate(struct cfs_rq *cfs_rq) {}
3067 #endif /* CONFIG_FAIR_GROUP_SCHED */
3069 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq)
3071 if (&this_rq()->cfs == cfs_rq) {
3073 * There are a few boundary cases this might miss but it should
3074 * get called often enough that that should (hopefully) not be
3075 * a real problem -- added to that it only calls on the local
3076 * CPU, so if we enqueue remotely we'll miss an update, but
3077 * the next tick/schedule should update.
3079 * It will not get called when we go idle, because the idle
3080 * thread is a different class (!fair), nor will the utilization
3081 * number include things like RT tasks.
3083 * As is, the util number is not freq-invariant (we'd have to
3084 * implement arch_scale_freq_capacity() for that).
3088 cpufreq_update_util(rq_of(cfs_rq), 0);
3092 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
3095 * Unsigned subtract and clamp on underflow.
3097 * Explicitly do a load-store to ensure the intermediate value never hits
3098 * memory. This allows lockless observations without ever seeing the negative
3101 #define sub_positive(_ptr, _val) do { \
3102 typeof(_ptr) ptr = (_ptr); \
3103 typeof(*ptr) val = (_val); \
3104 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3108 WRITE_ONCE(*ptr, res); \
3112 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3113 * @now: current time, as per cfs_rq_clock_task()
3114 * @cfs_rq: cfs_rq to update
3115 * @update_freq: should we call cfs_rq_util_change() or will the call do so
3117 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3118 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3119 * post_init_entity_util_avg().
3121 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3123 * Returns true if the load decayed or we removed load.
3125 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3126 * call update_tg_load_avg() when this function returns true.
3129 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3131 struct sched_avg *sa = &cfs_rq->avg;
3132 int decayed, removed = 0, removed_util = 0;
3134 if (atomic_long_read(&cfs_rq->removed_load_avg)) {
3135 s64 r = atomic_long_xchg(&cfs_rq->removed_load_avg, 0);
3136 sub_positive(&sa->load_avg, r);
3137 sub_positive(&sa->load_sum, r * LOAD_AVG_MAX);
3139 set_tg_cfs_propagate(cfs_rq);
3142 if (atomic_long_read(&cfs_rq->removed_util_avg)) {
3143 long r = atomic_long_xchg(&cfs_rq->removed_util_avg, 0);
3144 sub_positive(&sa->util_avg, r);
3145 sub_positive(&sa->util_sum, r * LOAD_AVG_MAX);
3147 set_tg_cfs_propagate(cfs_rq);
3150 decayed = __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
3151 scale_load_down(cfs_rq->load.weight), cfs_rq->curr != NULL, cfs_rq);
3153 #ifndef CONFIG_64BIT
3155 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3158 /* Trace CPU load, unless cfs_rq belongs to a non-root task_group */
3159 if (cfs_rq == &rq_of(cfs_rq)->cfs)
3160 trace_sched_load_avg_cpu(cpu_of(rq_of(cfs_rq)), cfs_rq);
3162 if (update_freq && (decayed || removed_util))
3163 cfs_rq_util_change(cfs_rq);
3165 return decayed || removed;
3169 * Optional action to be done while updating the load average
3171 #define UPDATE_TG 0x1
3172 #define SKIP_AGE_LOAD 0x2
3174 /* Update task and its cfs_rq load average */
3175 static inline void update_load_avg(struct sched_entity *se, int flags)
3177 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3178 u64 now = cfs_rq_clock_task(cfs_rq);
3179 int cpu = cpu_of(rq_of(cfs_rq));
3184 * Track task load average for carrying it to new CPU after migrated, and
3185 * track group sched_entity load average for task_h_load calc in migration
3187 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) {
3188 __update_load_avg(now, cpu, &se->avg,
3189 se->on_rq * scale_load_down(se->load.weight),
3190 cfs_rq->curr == se, NULL);
3193 decayed = update_cfs_rq_load_avg(now, cfs_rq, true);
3194 decayed |= propagate_entity_load_avg(se);
3196 if (decayed && (flags & UPDATE_TG))
3197 update_tg_load_avg(cfs_rq, 0);
3199 if (entity_is_task(se)) {
3200 #ifdef CONFIG_SCHED_WALT
3201 ptr = (void *)&(task_of(se)->ravg);
3203 trace_sched_load_avg_task(task_of(se), &se->avg, ptr);
3208 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3209 * @cfs_rq: cfs_rq to attach to
3210 * @se: sched_entity to attach
3212 * Must call update_cfs_rq_load_avg() before this, since we rely on
3213 * cfs_rq->avg.last_update_time being current.
3215 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3217 se->avg.last_update_time = cfs_rq->avg.last_update_time;
3218 cfs_rq->avg.load_avg += se->avg.load_avg;
3219 cfs_rq->avg.load_sum += se->avg.load_sum;
3220 cfs_rq->avg.util_avg += se->avg.util_avg;
3221 cfs_rq->avg.util_sum += se->avg.util_sum;
3222 set_tg_cfs_propagate(cfs_rq);
3224 cfs_rq_util_change(cfs_rq);
3228 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3229 * @cfs_rq: cfs_rq to detach from
3230 * @se: sched_entity to detach
3232 * Must call update_cfs_rq_load_avg() before this, since we rely on
3233 * cfs_rq->avg.last_update_time being current.
3235 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3238 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3239 sub_positive(&cfs_rq->avg.load_sum, se->avg.load_sum);
3240 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3241 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
3242 set_tg_cfs_propagate(cfs_rq);
3244 cfs_rq_util_change(cfs_rq);
3247 /* Add the load generated by se into cfs_rq's load average */
3249 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3251 struct sched_avg *sa = &se->avg;
3253 cfs_rq->runnable_load_avg += sa->load_avg;
3254 cfs_rq->runnable_load_sum += sa->load_sum;
3256 if (!sa->last_update_time) {
3257 attach_entity_load_avg(cfs_rq, se);
3258 update_tg_load_avg(cfs_rq, 0);
3262 /* Remove the runnable load generated by se from cfs_rq's runnable load average */
3264 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3266 cfs_rq->runnable_load_avg =
3267 max_t(long, cfs_rq->runnable_load_avg - se->avg.load_avg, 0);
3268 cfs_rq->runnable_load_sum =
3269 max_t(s64, cfs_rq->runnable_load_sum - se->avg.load_sum, 0);
3272 #ifndef CONFIG_64BIT
3273 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3275 u64 last_update_time_copy;
3276 u64 last_update_time;
3279 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3281 last_update_time = cfs_rq->avg.last_update_time;
3282 } while (last_update_time != last_update_time_copy);
3284 return last_update_time;
3287 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3289 return cfs_rq->avg.last_update_time;
3294 * Synchronize entity load avg of dequeued entity without locking
3297 void sync_entity_load_avg(struct sched_entity *se)
3299 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3300 u64 last_update_time;
3302 last_update_time = cfs_rq_last_update_time(cfs_rq);
3303 __update_load_avg(last_update_time, cpu_of(rq_of(cfs_rq)), &se->avg, 0, 0, NULL);
3307 * Task first catches up with cfs_rq, and then subtract
3308 * itself from the cfs_rq (task must be off the queue now).
3310 void remove_entity_load_avg(struct sched_entity *se)
3312 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3315 * tasks cannot exit without having gone through wake_up_new_task() ->
3316 * post_init_entity_util_avg() which will have added things to the
3317 * cfs_rq, so we can remove unconditionally.
3319 * Similarly for groups, they will have passed through
3320 * post_init_entity_util_avg() before unregister_sched_fair_group()
3324 sync_entity_load_avg(se);
3325 atomic_long_add(se->avg.load_avg, &cfs_rq->removed_load_avg);
3326 atomic_long_add(se->avg.util_avg, &cfs_rq->removed_util_avg);
3330 * Update the rq's load with the elapsed running time before entering
3331 * idle. if the last scheduled task is not a CFS task, idle_enter will
3332 * be the only way to update the runnable statistic.
3334 void idle_enter_fair(struct rq *this_rq)
3339 * Update the rq's load with the elapsed idle time before a task is
3340 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
3341 * be the only way to update the runnable statistic.
3343 void idle_exit_fair(struct rq *this_rq)
3347 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
3349 return cfs_rq->runnable_load_avg;
3352 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3354 return cfs_rq->avg.load_avg;
3357 static int idle_balance(struct rq *this_rq);
3359 #else /* CONFIG_SMP */
3362 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3367 #define UPDATE_TG 0x0
3368 #define SKIP_AGE_LOAD 0x0
3370 static inline void update_load_avg(struct sched_entity *se, int not_used1){}
3372 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3374 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3375 static inline void remove_entity_load_avg(struct sched_entity *se) {}
3378 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3380 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3382 static inline int idle_balance(struct rq *rq)
3387 #endif /* CONFIG_SMP */
3389 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
3391 #ifdef CONFIG_SCHEDSTATS
3392 struct task_struct *tsk = NULL;
3394 if (entity_is_task(se))
3397 if (se->statistics.sleep_start) {
3398 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
3403 if (unlikely(delta > se->statistics.sleep_max))
3404 se->statistics.sleep_max = delta;
3406 se->statistics.sleep_start = 0;
3407 se->statistics.sum_sleep_runtime += delta;
3410 account_scheduler_latency(tsk, delta >> 10, 1);
3411 trace_sched_stat_sleep(tsk, delta);
3414 if (se->statistics.block_start) {
3415 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
3420 if (unlikely(delta > se->statistics.block_max))
3421 se->statistics.block_max = delta;
3423 se->statistics.block_start = 0;
3424 se->statistics.sum_sleep_runtime += delta;
3427 if (tsk->in_iowait) {
3428 se->statistics.iowait_sum += delta;
3429 se->statistics.iowait_count++;
3430 trace_sched_stat_iowait(tsk, delta);
3433 trace_sched_stat_blocked(tsk, delta);
3434 trace_sched_blocked_reason(tsk);
3437 * Blocking time is in units of nanosecs, so shift by
3438 * 20 to get a milliseconds-range estimation of the
3439 * amount of time that the task spent sleeping:
3441 if (unlikely(prof_on == SLEEP_PROFILING)) {
3442 profile_hits(SLEEP_PROFILING,
3443 (void *)get_wchan(tsk),
3446 account_scheduler_latency(tsk, delta >> 10, 0);
3452 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
3454 #ifdef CONFIG_SCHED_DEBUG
3455 s64 d = se->vruntime - cfs_rq->min_vruntime;
3460 if (d > 3*sysctl_sched_latency)
3461 schedstat_inc(cfs_rq, nr_spread_over);
3466 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
3468 u64 vruntime = cfs_rq->min_vruntime;
3471 * The 'current' period is already promised to the current tasks,
3472 * however the extra weight of the new task will slow them down a
3473 * little, place the new task so that it fits in the slot that
3474 * stays open at the end.
3476 if (initial && sched_feat(START_DEBIT))
3477 vruntime += sched_vslice(cfs_rq, se);
3479 /* sleeps up to a single latency don't count. */
3481 unsigned long thresh = sysctl_sched_latency;
3484 * Halve their sleep time's effect, to allow
3485 * for a gentler effect of sleepers:
3487 if (sched_feat(GENTLE_FAIR_SLEEPERS))
3493 /* ensure we never gain time by being placed backwards. */
3494 se->vruntime = max_vruntime(se->vruntime, vruntime);
3497 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
3500 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3503 * Update the normalized vruntime before updating min_vruntime
3504 * through calling update_curr().
3506 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
3507 se->vruntime += cfs_rq->min_vruntime;
3510 * Update run-time statistics of the 'current'.
3512 update_curr(cfs_rq);
3513 update_load_avg(se, UPDATE_TG);
3514 enqueue_entity_load_avg(cfs_rq, se);
3515 update_cfs_shares(se);
3516 account_entity_enqueue(cfs_rq, se);
3518 if (flags & ENQUEUE_WAKEUP) {
3519 place_entity(cfs_rq, se, 0);
3520 enqueue_sleeper(cfs_rq, se);
3523 update_stats_enqueue(cfs_rq, se);
3524 check_spread(cfs_rq, se);
3525 if (se != cfs_rq->curr)
3526 __enqueue_entity(cfs_rq, se);
3529 if (cfs_rq->nr_running == 1) {
3530 list_add_leaf_cfs_rq(cfs_rq);
3531 check_enqueue_throttle(cfs_rq);
3535 static void __clear_buddies_last(struct sched_entity *se)
3537 for_each_sched_entity(se) {
3538 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3539 if (cfs_rq->last != se)
3542 cfs_rq->last = NULL;
3546 static void __clear_buddies_next(struct sched_entity *se)
3548 for_each_sched_entity(se) {
3549 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3550 if (cfs_rq->next != se)
3553 cfs_rq->next = NULL;
3557 static void __clear_buddies_skip(struct sched_entity *se)
3559 for_each_sched_entity(se) {
3560 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3561 if (cfs_rq->skip != se)
3564 cfs_rq->skip = NULL;
3568 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3570 if (cfs_rq->last == se)
3571 __clear_buddies_last(se);
3573 if (cfs_rq->next == se)
3574 __clear_buddies_next(se);
3576 if (cfs_rq->skip == se)
3577 __clear_buddies_skip(se);
3580 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3583 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3586 * Update run-time statistics of the 'current'.
3588 update_curr(cfs_rq);
3591 * When dequeuing a sched_entity, we must:
3592 * - Update loads to have both entity and cfs_rq synced with now.
3593 * - Substract its load from the cfs_rq->runnable_avg.
3594 * - Substract its previous weight from cfs_rq->load.weight.
3595 * - For group entity, update its weight to reflect the new share
3596 * of its group cfs_rq.
3598 update_load_avg(se, UPDATE_TG);
3599 dequeue_entity_load_avg(cfs_rq, se);
3601 update_stats_dequeue(cfs_rq, se);
3602 if (flags & DEQUEUE_SLEEP) {
3603 #ifdef CONFIG_SCHEDSTATS
3604 if (entity_is_task(se)) {
3605 struct task_struct *tsk = task_of(se);
3607 if (tsk->state & TASK_INTERRUPTIBLE)
3608 se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
3609 if (tsk->state & TASK_UNINTERRUPTIBLE)
3610 se->statistics.block_start = rq_clock(rq_of(cfs_rq));
3615 clear_buddies(cfs_rq, se);
3617 if (se != cfs_rq->curr)
3618 __dequeue_entity(cfs_rq, se);
3620 account_entity_dequeue(cfs_rq, se);
3623 * Normalize the entity after updating the min_vruntime because the
3624 * update can refer to the ->curr item and we need to reflect this
3625 * movement in our normalized position.
3627 if (!(flags & DEQUEUE_SLEEP))
3628 se->vruntime -= cfs_rq->min_vruntime;
3630 /* return excess runtime on last dequeue */
3631 return_cfs_rq_runtime(cfs_rq);
3633 update_min_vruntime(cfs_rq);
3634 update_cfs_shares(se);
3638 * Preempt the current task with a newly woken task if needed:
3641 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3643 unsigned long ideal_runtime, delta_exec;
3644 struct sched_entity *se;
3647 ideal_runtime = sched_slice(cfs_rq, curr);
3648 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
3649 if (delta_exec > ideal_runtime) {
3650 resched_curr(rq_of(cfs_rq));
3652 * The current task ran long enough, ensure it doesn't get
3653 * re-elected due to buddy favours.
3655 clear_buddies(cfs_rq, curr);
3660 * Ensure that a task that missed wakeup preemption by a
3661 * narrow margin doesn't have to wait for a full slice.
3662 * This also mitigates buddy induced latencies under load.
3664 if (delta_exec < sysctl_sched_min_granularity)
3667 se = __pick_first_entity(cfs_rq);
3668 delta = curr->vruntime - se->vruntime;
3673 if (delta > ideal_runtime)
3674 resched_curr(rq_of(cfs_rq));
3678 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
3680 /* 'current' is not kept within the tree. */
3683 * Any task has to be enqueued before it get to execute on
3684 * a CPU. So account for the time it spent waiting on the
3687 update_stats_wait_end(cfs_rq, se);
3688 __dequeue_entity(cfs_rq, se);
3689 update_load_avg(se, UPDATE_TG);
3692 update_stats_curr_start(cfs_rq, se);
3694 #ifdef CONFIG_SCHEDSTATS
3696 * Track our maximum slice length, if the CPU's load is at
3697 * least twice that of our own weight (i.e. dont track it
3698 * when there are only lesser-weight tasks around):
3700 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
3701 se->statistics.slice_max = max(se->statistics.slice_max,
3702 se->sum_exec_runtime - se->prev_sum_exec_runtime);
3705 se->prev_sum_exec_runtime = se->sum_exec_runtime;
3709 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
3712 * Pick the next process, keeping these things in mind, in this order:
3713 * 1) keep things fair between processes/task groups
3714 * 2) pick the "next" process, since someone really wants that to run
3715 * 3) pick the "last" process, for cache locality
3716 * 4) do not run the "skip" process, if something else is available
3718 static struct sched_entity *
3719 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3721 struct sched_entity *left = __pick_first_entity(cfs_rq);
3722 struct sched_entity *se;
3725 * If curr is set we have to see if its left of the leftmost entity
3726 * still in the tree, provided there was anything in the tree at all.
3728 if (!left || (curr && entity_before(curr, left)))
3731 se = left; /* ideally we run the leftmost entity */
3734 * Avoid running the skip buddy, if running something else can
3735 * be done without getting too unfair.
3737 if (cfs_rq->skip == se) {
3738 struct sched_entity *second;
3741 second = __pick_first_entity(cfs_rq);
3743 second = __pick_next_entity(se);
3744 if (!second || (curr && entity_before(curr, second)))
3748 if (second && wakeup_preempt_entity(second, left) < 1)
3753 * Prefer last buddy, try to return the CPU to a preempted task.
3755 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
3759 * Someone really wants this to run. If it's not unfair, run it.
3761 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
3764 clear_buddies(cfs_rq, se);
3769 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3771 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
3774 * If still on the runqueue then deactivate_task()
3775 * was not called and update_curr() has to be done:
3778 update_curr(cfs_rq);
3780 /* throttle cfs_rqs exceeding runtime */
3781 check_cfs_rq_runtime(cfs_rq);
3783 check_spread(cfs_rq, prev);
3785 update_stats_wait_start(cfs_rq, prev);
3786 /* Put 'current' back into the tree. */
3787 __enqueue_entity(cfs_rq, prev);
3788 /* in !on_rq case, update occurred at dequeue */
3789 update_load_avg(prev, 0);
3791 cfs_rq->curr = NULL;
3795 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
3798 * Update run-time statistics of the 'current'.
3800 update_curr(cfs_rq);
3803 * Ensure that runnable average is periodically updated.
3805 update_load_avg(curr, UPDATE_TG);
3806 update_cfs_shares(curr);
3808 #ifdef CONFIG_SCHED_HRTICK
3810 * queued ticks are scheduled to match the slice, so don't bother
3811 * validating it and just reschedule.
3814 resched_curr(rq_of(cfs_rq));
3818 * don't let the period tick interfere with the hrtick preemption
3820 if (!sched_feat(DOUBLE_TICK) &&
3821 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3825 if (cfs_rq->nr_running > 1)
3826 check_preempt_tick(cfs_rq, curr);
3830 /**************************************************
3831 * CFS bandwidth control machinery
3834 #ifdef CONFIG_CFS_BANDWIDTH
3836 #ifdef HAVE_JUMP_LABEL
3837 static struct static_key __cfs_bandwidth_used;
3839 static inline bool cfs_bandwidth_used(void)
3841 return static_key_false(&__cfs_bandwidth_used);
3844 void cfs_bandwidth_usage_inc(void)
3846 static_key_slow_inc(&__cfs_bandwidth_used);
3849 void cfs_bandwidth_usage_dec(void)
3851 static_key_slow_dec(&__cfs_bandwidth_used);
3853 #else /* HAVE_JUMP_LABEL */
3854 static bool cfs_bandwidth_used(void)
3859 void cfs_bandwidth_usage_inc(void) {}
3860 void cfs_bandwidth_usage_dec(void) {}
3861 #endif /* HAVE_JUMP_LABEL */
3864 * default period for cfs group bandwidth.
3865 * default: 0.1s, units: nanoseconds
3867 static inline u64 default_cfs_period(void)
3869 return 100000000ULL;
3872 static inline u64 sched_cfs_bandwidth_slice(void)
3874 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3878 * Replenish runtime according to assigned quota and update expiration time.
3879 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3880 * additional synchronization around rq->lock.
3882 * requires cfs_b->lock
3884 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
3888 if (cfs_b->quota == RUNTIME_INF)
3891 now = sched_clock_cpu(smp_processor_id());
3892 cfs_b->runtime = cfs_b->quota;
3893 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3896 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3898 return &tg->cfs_bandwidth;
3901 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3902 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3904 if (unlikely(cfs_rq->throttle_count))
3905 return cfs_rq->throttled_clock_task;
3907 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
3910 /* returns 0 on failure to allocate runtime */
3911 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3913 struct task_group *tg = cfs_rq->tg;
3914 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
3915 u64 amount = 0, min_amount, expires;
3917 /* note: this is a positive sum as runtime_remaining <= 0 */
3918 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3920 raw_spin_lock(&cfs_b->lock);
3921 if (cfs_b->quota == RUNTIME_INF)
3922 amount = min_amount;
3924 start_cfs_bandwidth(cfs_b);
3926 if (cfs_b->runtime > 0) {
3927 amount = min(cfs_b->runtime, min_amount);
3928 cfs_b->runtime -= amount;
3932 expires = cfs_b->runtime_expires;
3933 raw_spin_unlock(&cfs_b->lock);
3935 cfs_rq->runtime_remaining += amount;
3937 * we may have advanced our local expiration to account for allowed
3938 * spread between our sched_clock and the one on which runtime was
3941 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3942 cfs_rq->runtime_expires = expires;
3944 return cfs_rq->runtime_remaining > 0;
3948 * Note: This depends on the synchronization provided by sched_clock and the
3949 * fact that rq->clock snapshots this value.
3951 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3953 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3955 /* if the deadline is ahead of our clock, nothing to do */
3956 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
3959 if (cfs_rq->runtime_remaining < 0)
3963 * If the local deadline has passed we have to consider the
3964 * possibility that our sched_clock is 'fast' and the global deadline
3965 * has not truly expired.
3967 * Fortunately we can check determine whether this the case by checking
3968 * whether the global deadline has advanced. It is valid to compare
3969 * cfs_b->runtime_expires without any locks since we only care about
3970 * exact equality, so a partial write will still work.
3973 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
3974 /* extend local deadline, drift is bounded above by 2 ticks */
3975 cfs_rq->runtime_expires += TICK_NSEC;
3977 /* global deadline is ahead, expiration has passed */
3978 cfs_rq->runtime_remaining = 0;
3982 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3984 /* dock delta_exec before expiring quota (as it could span periods) */
3985 cfs_rq->runtime_remaining -= delta_exec;
3986 expire_cfs_rq_runtime(cfs_rq);
3988 if (likely(cfs_rq->runtime_remaining > 0))
3992 * if we're unable to extend our runtime we resched so that the active
3993 * hierarchy can be throttled
3995 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
3996 resched_curr(rq_of(cfs_rq));
3999 static __always_inline
4000 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4002 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4005 __account_cfs_rq_runtime(cfs_rq, delta_exec);
4008 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4010 return cfs_bandwidth_used() && cfs_rq->throttled;
4013 /* check whether cfs_rq, or any parent, is throttled */
4014 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4016 return cfs_bandwidth_used() && cfs_rq->throttle_count;
4020 * Ensure that neither of the group entities corresponding to src_cpu or
4021 * dest_cpu are members of a throttled hierarchy when performing group
4022 * load-balance operations.
4024 static inline int throttled_lb_pair(struct task_group *tg,
4025 int src_cpu, int dest_cpu)
4027 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4029 src_cfs_rq = tg->cfs_rq[src_cpu];
4030 dest_cfs_rq = tg->cfs_rq[dest_cpu];
4032 return throttled_hierarchy(src_cfs_rq) ||
4033 throttled_hierarchy(dest_cfs_rq);
4036 /* updated child weight may affect parent so we have to do this bottom up */
4037 static int tg_unthrottle_up(struct task_group *tg, void *data)
4039 struct rq *rq = data;
4040 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4042 cfs_rq->throttle_count--;
4044 if (!cfs_rq->throttle_count) {
4045 /* adjust cfs_rq_clock_task() */
4046 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
4047 cfs_rq->throttled_clock_task;
4054 static int tg_throttle_down(struct task_group *tg, void *data)
4056 struct rq *rq = data;
4057 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4059 /* group is entering throttled state, stop time */
4060 if (!cfs_rq->throttle_count)
4061 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4062 cfs_rq->throttle_count++;
4067 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
4069 struct rq *rq = rq_of(cfs_rq);
4070 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4071 struct sched_entity *se;
4072 long task_delta, dequeue = 1;
4075 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4077 /* freeze hierarchy runnable averages while throttled */
4079 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4082 task_delta = cfs_rq->h_nr_running;
4083 for_each_sched_entity(se) {
4084 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4085 /* throttled entity or throttle-on-deactivate */
4090 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
4091 qcfs_rq->h_nr_running -= task_delta;
4093 if (qcfs_rq->load.weight)
4098 sub_nr_running(rq, task_delta);
4100 cfs_rq->throttled = 1;
4101 cfs_rq->throttled_clock = rq_clock(rq);
4102 raw_spin_lock(&cfs_b->lock);
4103 empty = list_empty(&cfs_b->throttled_cfs_rq);
4106 * Add to the _head_ of the list, so that an already-started
4107 * distribute_cfs_runtime will not see us. If disribute_cfs_runtime is
4108 * not running add to the tail so that later runqueues don't get starved.
4110 if (cfs_b->distribute_running)
4111 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4113 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4116 * If we're the first throttled task, make sure the bandwidth
4120 start_cfs_bandwidth(cfs_b);
4122 raw_spin_unlock(&cfs_b->lock);
4125 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
4127 struct rq *rq = rq_of(cfs_rq);
4128 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4129 struct sched_entity *se;
4133 se = cfs_rq->tg->se[cpu_of(rq)];
4135 cfs_rq->throttled = 0;
4137 update_rq_clock(rq);
4139 raw_spin_lock(&cfs_b->lock);
4140 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4141 list_del_rcu(&cfs_rq->throttled_list);
4142 raw_spin_unlock(&cfs_b->lock);
4144 /* update hierarchical throttle state */
4145 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4147 if (!cfs_rq->load.weight)
4150 task_delta = cfs_rq->h_nr_running;
4151 for_each_sched_entity(se) {
4155 cfs_rq = cfs_rq_of(se);
4157 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4158 cfs_rq->h_nr_running += task_delta;
4160 if (cfs_rq_throttled(cfs_rq))
4165 add_nr_running(rq, task_delta);
4167 /* determine whether we need to wake up potentially idle cpu */
4168 if (rq->curr == rq->idle && rq->cfs.nr_running)
4172 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
4173 u64 remaining, u64 expires)
4175 struct cfs_rq *cfs_rq;
4177 u64 starting_runtime = remaining;
4180 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4182 struct rq *rq = rq_of(cfs_rq);
4184 raw_spin_lock(&rq->lock);
4185 if (!cfs_rq_throttled(cfs_rq))
4188 runtime = -cfs_rq->runtime_remaining + 1;
4189 if (runtime > remaining)
4190 runtime = remaining;
4191 remaining -= runtime;
4193 cfs_rq->runtime_remaining += runtime;
4194 cfs_rq->runtime_expires = expires;
4196 /* we check whether we're throttled above */
4197 if (cfs_rq->runtime_remaining > 0)
4198 unthrottle_cfs_rq(cfs_rq);
4201 raw_spin_unlock(&rq->lock);
4208 return starting_runtime - remaining;
4212 * Responsible for refilling a task_group's bandwidth and unthrottling its
4213 * cfs_rqs as appropriate. If there has been no activity within the last
4214 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4215 * used to track this state.
4217 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
4219 u64 runtime, runtime_expires;
4222 /* no need to continue the timer with no bandwidth constraint */
4223 if (cfs_b->quota == RUNTIME_INF)
4224 goto out_deactivate;
4226 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4227 cfs_b->nr_periods += overrun;
4230 * idle depends on !throttled (for the case of a large deficit), and if
4231 * we're going inactive then everything else can be deferred
4233 if (cfs_b->idle && !throttled)
4234 goto out_deactivate;
4236 __refill_cfs_bandwidth_runtime(cfs_b);
4239 /* mark as potentially idle for the upcoming period */
4244 /* account preceding periods in which throttling occurred */
4245 cfs_b->nr_throttled += overrun;
4247 runtime_expires = cfs_b->runtime_expires;
4250 * This check is repeated as we are holding onto the new bandwidth while
4251 * we unthrottle. This can potentially race with an unthrottled group
4252 * trying to acquire new bandwidth from the global pool. This can result
4253 * in us over-using our runtime if it is all used during this loop, but
4254 * only by limited amounts in that extreme case.
4256 while (throttled && cfs_b->runtime > 0 && !cfs_b->distribute_running) {
4257 runtime = cfs_b->runtime;
4258 cfs_b->distribute_running = 1;
4259 raw_spin_unlock(&cfs_b->lock);
4260 /* we can't nest cfs_b->lock while distributing bandwidth */
4261 runtime = distribute_cfs_runtime(cfs_b, runtime,
4263 raw_spin_lock(&cfs_b->lock);
4265 cfs_b->distribute_running = 0;
4266 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4268 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4272 * While we are ensured activity in the period following an
4273 * unthrottle, this also covers the case in which the new bandwidth is
4274 * insufficient to cover the existing bandwidth deficit. (Forcing the
4275 * timer to remain active while there are any throttled entities.)
4285 /* a cfs_rq won't donate quota below this amount */
4286 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
4287 /* minimum remaining period time to redistribute slack quota */
4288 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
4289 /* how long we wait to gather additional slack before distributing */
4290 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
4293 * Are we near the end of the current quota period?
4295 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4296 * hrtimer base being cleared by hrtimer_start. In the case of
4297 * migrate_hrtimers, base is never cleared, so we are fine.
4299 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
4301 struct hrtimer *refresh_timer = &cfs_b->period_timer;
4304 /* if the call-back is running a quota refresh is already occurring */
4305 if (hrtimer_callback_running(refresh_timer))
4308 /* is a quota refresh about to occur? */
4309 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
4310 if (remaining < min_expire)
4316 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
4318 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
4320 /* if there's a quota refresh soon don't bother with slack */
4321 if (runtime_refresh_within(cfs_b, min_left))
4324 hrtimer_start(&cfs_b->slack_timer,
4325 ns_to_ktime(cfs_bandwidth_slack_period),
4329 /* we know any runtime found here is valid as update_curr() precedes return */
4330 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4332 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4333 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
4335 if (slack_runtime <= 0)
4338 raw_spin_lock(&cfs_b->lock);
4339 if (cfs_b->quota != RUNTIME_INF &&
4340 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
4341 cfs_b->runtime += slack_runtime;
4343 /* we are under rq->lock, defer unthrottling using a timer */
4344 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
4345 !list_empty(&cfs_b->throttled_cfs_rq))
4346 start_cfs_slack_bandwidth(cfs_b);
4348 raw_spin_unlock(&cfs_b->lock);
4350 /* even if it's not valid for return we don't want to try again */
4351 cfs_rq->runtime_remaining -= slack_runtime;
4354 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4356 if (!cfs_bandwidth_used())
4359 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
4362 __return_cfs_rq_runtime(cfs_rq);
4366 * This is done with a timer (instead of inline with bandwidth return) since
4367 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4369 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
4371 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
4374 /* confirm we're still not at a refresh boundary */
4375 raw_spin_lock(&cfs_b->lock);
4376 if (cfs_b->distribute_running) {
4377 raw_spin_unlock(&cfs_b->lock);
4381 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
4382 raw_spin_unlock(&cfs_b->lock);
4386 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
4387 runtime = cfs_b->runtime;
4389 expires = cfs_b->runtime_expires;
4391 cfs_b->distribute_running = 1;
4393 raw_spin_unlock(&cfs_b->lock);
4398 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
4400 raw_spin_lock(&cfs_b->lock);
4401 if (expires == cfs_b->runtime_expires)
4402 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4403 cfs_b->distribute_running = 0;
4404 raw_spin_unlock(&cfs_b->lock);
4408 * When a group wakes up we want to make sure that its quota is not already
4409 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4410 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4412 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
4414 if (!cfs_bandwidth_used())
4417 /* Synchronize hierarchical throttle counter: */
4418 if (unlikely(!cfs_rq->throttle_uptodate)) {
4419 struct rq *rq = rq_of(cfs_rq);
4420 struct cfs_rq *pcfs_rq;
4421 struct task_group *tg;
4423 cfs_rq->throttle_uptodate = 1;
4425 /* Get closest up-to-date node, because leaves go first: */
4426 for (tg = cfs_rq->tg->parent; tg; tg = tg->parent) {
4427 pcfs_rq = tg->cfs_rq[cpu_of(rq)];
4428 if (pcfs_rq->throttle_uptodate)
4432 cfs_rq->throttle_count = pcfs_rq->throttle_count;
4433 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4437 /* an active group must be handled by the update_curr()->put() path */
4438 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
4441 /* ensure the group is not already throttled */
4442 if (cfs_rq_throttled(cfs_rq))
4445 /* update runtime allocation */
4446 account_cfs_rq_runtime(cfs_rq, 0);
4447 if (cfs_rq->runtime_remaining <= 0)
4448 throttle_cfs_rq(cfs_rq);
4451 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4452 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4454 if (!cfs_bandwidth_used())
4457 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
4461 * it's possible for a throttled entity to be forced into a running
4462 * state (e.g. set_curr_task), in this case we're finished.
4464 if (cfs_rq_throttled(cfs_rq))
4467 throttle_cfs_rq(cfs_rq);
4471 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
4473 struct cfs_bandwidth *cfs_b =
4474 container_of(timer, struct cfs_bandwidth, slack_timer);
4476 do_sched_cfs_slack_timer(cfs_b);
4478 return HRTIMER_NORESTART;
4481 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
4483 struct cfs_bandwidth *cfs_b =
4484 container_of(timer, struct cfs_bandwidth, period_timer);
4488 raw_spin_lock(&cfs_b->lock);
4490 overrun = hrtimer_forward_now(timer, cfs_b->period);
4494 idle = do_sched_cfs_period_timer(cfs_b, overrun);
4497 cfs_b->period_active = 0;
4498 raw_spin_unlock(&cfs_b->lock);
4500 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
4503 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4505 raw_spin_lock_init(&cfs_b->lock);
4507 cfs_b->quota = RUNTIME_INF;
4508 cfs_b->period = ns_to_ktime(default_cfs_period());
4510 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4511 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
4512 cfs_b->period_timer.function = sched_cfs_period_timer;
4513 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4514 cfs_b->slack_timer.function = sched_cfs_slack_timer;
4515 cfs_b->distribute_running = 0;
4518 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4520 cfs_rq->runtime_enabled = 0;
4521 INIT_LIST_HEAD(&cfs_rq->throttled_list);
4524 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4526 lockdep_assert_held(&cfs_b->lock);
4528 if (!cfs_b->period_active) {
4529 cfs_b->period_active = 1;
4530 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
4531 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
4535 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4537 /* init_cfs_bandwidth() was not called */
4538 if (!cfs_b->throttled_cfs_rq.next)
4541 hrtimer_cancel(&cfs_b->period_timer);
4542 hrtimer_cancel(&cfs_b->slack_timer);
4545 static void __maybe_unused update_runtime_enabled(struct rq *rq)
4547 struct cfs_rq *cfs_rq;
4549 for_each_leaf_cfs_rq(rq, cfs_rq) {
4550 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
4552 raw_spin_lock(&cfs_b->lock);
4553 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4554 raw_spin_unlock(&cfs_b->lock);
4558 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
4560 struct cfs_rq *cfs_rq;
4562 for_each_leaf_cfs_rq(rq, cfs_rq) {
4563 if (!cfs_rq->runtime_enabled)
4567 * clock_task is not advancing so we just need to make sure
4568 * there's some valid quota amount
4570 cfs_rq->runtime_remaining = 1;
4572 * Offline rq is schedulable till cpu is completely disabled
4573 * in take_cpu_down(), so we prevent new cfs throttling here.
4575 cfs_rq->runtime_enabled = 0;
4577 if (cfs_rq_throttled(cfs_rq))
4578 unthrottle_cfs_rq(cfs_rq);
4582 #else /* CONFIG_CFS_BANDWIDTH */
4583 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4585 return rq_clock_task(rq_of(cfs_rq));
4588 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
4589 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
4590 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
4591 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4593 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4598 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4603 static inline int throttled_lb_pair(struct task_group *tg,
4604 int src_cpu, int dest_cpu)
4609 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4611 #ifdef CONFIG_FAIR_GROUP_SCHED
4612 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4615 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4619 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4620 static inline void update_runtime_enabled(struct rq *rq) {}
4621 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
4623 #endif /* CONFIG_CFS_BANDWIDTH */
4625 /**************************************************
4626 * CFS operations on tasks:
4629 #ifdef CONFIG_SCHED_HRTICK
4630 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
4632 struct sched_entity *se = &p->se;
4633 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4635 WARN_ON(task_rq(p) != rq);
4637 if (cfs_rq->nr_running > 1) {
4638 u64 slice = sched_slice(cfs_rq, se);
4639 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
4640 s64 delta = slice - ran;
4647 hrtick_start(rq, delta);
4652 * called from enqueue/dequeue and updates the hrtick when the
4653 * current task is from our class and nr_running is low enough
4656 static void hrtick_update(struct rq *rq)
4658 struct task_struct *curr = rq->curr;
4660 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
4663 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
4664 hrtick_start_fair(rq, curr);
4666 #else /* !CONFIG_SCHED_HRTICK */
4668 hrtick_start_fair(struct rq *rq, struct task_struct *p)
4672 static inline void hrtick_update(struct rq *rq)
4678 static bool __cpu_overutilized(int cpu, int delta);
4679 static bool cpu_overutilized(int cpu);
4680 unsigned long boosted_cpu_util(int cpu);
4682 #define boosted_cpu_util(cpu) cpu_util_freq(cpu)
4686 * The enqueue_task method is called before nr_running is
4687 * increased. Here we update the fair scheduling stats and
4688 * then put the task into the rbtree:
4691 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4693 struct cfs_rq *cfs_rq;
4694 struct sched_entity *se = &p->se;
4696 int task_new = flags & ENQUEUE_WAKEUP_NEW;
4700 * If in_iowait is set, the code below may not trigger any cpufreq
4701 * utilization updates, so do it here explicitly with the IOWAIT flag
4705 cpufreq_update_this_cpu(rq, SCHED_CPUFREQ_IOWAIT);
4707 for_each_sched_entity(se) {
4710 cfs_rq = cfs_rq_of(se);
4711 enqueue_entity(cfs_rq, se, flags);
4714 * end evaluation on encountering a throttled cfs_rq
4716 * note: in the case of encountering a throttled cfs_rq we will
4717 * post the final h_nr_running increment below.
4719 if (cfs_rq_throttled(cfs_rq))
4721 cfs_rq->h_nr_running++;
4722 walt_inc_cfs_cumulative_runnable_avg(cfs_rq, p);
4724 flags = ENQUEUE_WAKEUP;
4727 for_each_sched_entity(se) {
4728 cfs_rq = cfs_rq_of(se);
4729 cfs_rq->h_nr_running++;
4730 walt_inc_cfs_cumulative_runnable_avg(cfs_rq, p);
4732 if (cfs_rq_throttled(cfs_rq))
4735 update_load_avg(se, UPDATE_TG);
4736 update_cfs_shares(se);
4740 add_nr_running(rq, 1);
4745 * Update SchedTune accounting.
4747 * We do it before updating the CPU capacity to ensure the
4748 * boost value of the current task is accounted for in the
4749 * selection of the OPP.
4751 * We do it also in the case where we enqueue a throttled task;
4752 * we could argue that a throttled task should not boost a CPU,
4754 * a) properly implementing CPU boosting considering throttled
4755 * tasks will increase a lot the complexity of the solution
4756 * b) it's not easy to quantify the benefits introduced by
4757 * such a more complex solution.
4758 * Thus, for the time being we go for the simple solution and boost
4759 * also for throttled RQs.
4761 schedtune_enqueue_task(p, cpu_of(rq));
4764 walt_inc_cumulative_runnable_avg(rq, p);
4765 if (!task_new && !rq->rd->overutilized &&
4766 cpu_overutilized(rq->cpu)) {
4767 rq->rd->overutilized = true;
4768 trace_sched_overutilized(true);
4772 #endif /* CONFIG_SMP */
4776 static void set_next_buddy(struct sched_entity *se);
4779 * The dequeue_task method is called before nr_running is
4780 * decreased. We remove the task from the rbtree and
4781 * update the fair scheduling stats:
4783 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4785 struct cfs_rq *cfs_rq;
4786 struct sched_entity *se = &p->se;
4787 int task_sleep = flags & DEQUEUE_SLEEP;
4789 for_each_sched_entity(se) {
4790 cfs_rq = cfs_rq_of(se);
4791 dequeue_entity(cfs_rq, se, flags);
4794 * end evaluation on encountering a throttled cfs_rq
4796 * note: in the case of encountering a throttled cfs_rq we will
4797 * post the final h_nr_running decrement below.
4799 if (cfs_rq_throttled(cfs_rq))
4801 cfs_rq->h_nr_running--;
4802 walt_dec_cfs_cumulative_runnable_avg(cfs_rq, p);
4804 /* Don't dequeue parent if it has other entities besides us */
4805 if (cfs_rq->load.weight) {
4806 /* Avoid re-evaluating load for this entity: */
4807 se = parent_entity(se);
4809 * Bias pick_next to pick a task from this cfs_rq, as
4810 * p is sleeping when it is within its sched_slice.
4812 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
4816 flags |= DEQUEUE_SLEEP;
4819 for_each_sched_entity(se) {
4820 cfs_rq = cfs_rq_of(se);
4821 cfs_rq->h_nr_running--;
4822 walt_dec_cfs_cumulative_runnable_avg(cfs_rq, p);
4824 if (cfs_rq_throttled(cfs_rq))
4827 update_load_avg(se, UPDATE_TG);
4828 update_cfs_shares(se);
4832 sub_nr_running(rq, 1);
4837 * Update SchedTune accounting
4839 * We do it before updating the CPU capacity to ensure the
4840 * boost value of the current task is accounted for in the
4841 * selection of the OPP.
4843 schedtune_dequeue_task(p, cpu_of(rq));
4846 walt_dec_cumulative_runnable_avg(rq, p);
4847 #endif /* CONFIG_SMP */
4855 * per rq 'load' arrray crap; XXX kill this.
4859 * The exact cpuload at various idx values, calculated at every tick would be
4860 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
4862 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
4863 * on nth tick when cpu may be busy, then we have:
4864 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
4865 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
4867 * decay_load_missed() below does efficient calculation of
4868 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
4869 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
4871 * The calculation is approximated on a 128 point scale.
4872 * degrade_zero_ticks is the number of ticks after which load at any
4873 * particular idx is approximated to be zero.
4874 * degrade_factor is a precomputed table, a row for each load idx.
4875 * Each column corresponds to degradation factor for a power of two ticks,
4876 * based on 128 point scale.
4878 * row 2, col 3 (=12) says that the degradation at load idx 2 after
4879 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
4881 * With this power of 2 load factors, we can degrade the load n times
4882 * by looking at 1 bits in n and doing as many mult/shift instead of
4883 * n mult/shifts needed by the exact degradation.
4885 #define DEGRADE_SHIFT 7
4886 static const unsigned char
4887 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
4888 static const unsigned char
4889 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
4890 {0, 0, 0, 0, 0, 0, 0, 0},
4891 {64, 32, 8, 0, 0, 0, 0, 0},
4892 {96, 72, 40, 12, 1, 0, 0},
4893 {112, 98, 75, 43, 15, 1, 0},
4894 {120, 112, 98, 76, 45, 16, 2} };
4897 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
4898 * would be when CPU is idle and so we just decay the old load without
4899 * adding any new load.
4901 static unsigned long
4902 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
4906 if (!missed_updates)
4909 if (missed_updates >= degrade_zero_ticks[idx])
4913 return load >> missed_updates;
4915 while (missed_updates) {
4916 if (missed_updates % 2)
4917 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
4919 missed_updates >>= 1;
4926 * Update rq->cpu_load[] statistics. This function is usually called every
4927 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
4928 * every tick. We fix it up based on jiffies.
4930 static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
4931 unsigned long pending_updates)
4935 this_rq->nr_load_updates++;
4937 /* Update our load: */
4938 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
4939 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
4940 unsigned long old_load, new_load;
4942 /* scale is effectively 1 << i now, and >> i divides by scale */
4944 old_load = this_rq->cpu_load[i];
4945 old_load = decay_load_missed(old_load, pending_updates - 1, i);
4946 new_load = this_load;
4948 * Round up the averaging division if load is increasing. This
4949 * prevents us from getting stuck on 9 if the load is 10, for
4952 if (new_load > old_load)
4953 new_load += scale - 1;
4955 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
4958 sched_avg_update(this_rq);
4961 /* Used instead of source_load when we know the type == 0 */
4962 static unsigned long weighted_cpuload(const int cpu)
4964 return cfs_rq_runnable_load_avg(&cpu_rq(cpu)->cfs);
4967 #ifdef CONFIG_NO_HZ_COMMON
4969 * There is no sane way to deal with nohz on smp when using jiffies because the
4970 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
4971 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
4973 * Therefore we cannot use the delta approach from the regular tick since that
4974 * would seriously skew the load calculation. However we'll make do for those
4975 * updates happening while idle (nohz_idle_balance) or coming out of idle
4976 * (tick_nohz_idle_exit).
4978 * This means we might still be one tick off for nohz periods.
4982 * Called from nohz_idle_balance() to update the load ratings before doing the
4985 static void update_idle_cpu_load(struct rq *this_rq)
4987 unsigned long curr_jiffies = READ_ONCE(jiffies);
4988 unsigned long load = weighted_cpuload(cpu_of(this_rq));
4989 unsigned long pending_updates;
4992 * bail if there's load or we're actually up-to-date.
4994 if (load || curr_jiffies == this_rq->last_load_update_tick)
4997 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
4998 this_rq->last_load_update_tick = curr_jiffies;
5000 __update_cpu_load(this_rq, load, pending_updates);
5004 * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
5006 void update_cpu_load_nohz(void)
5008 struct rq *this_rq = this_rq();
5009 unsigned long curr_jiffies = READ_ONCE(jiffies);
5010 unsigned long pending_updates;
5012 if (curr_jiffies == this_rq->last_load_update_tick)
5015 raw_spin_lock(&this_rq->lock);
5016 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
5017 if (pending_updates) {
5018 this_rq->last_load_update_tick = curr_jiffies;
5020 * We were idle, this means load 0, the current load might be
5021 * !0 due to remote wakeups and the sort.
5023 __update_cpu_load(this_rq, 0, pending_updates);
5025 raw_spin_unlock(&this_rq->lock);
5027 #endif /* CONFIG_NO_HZ */
5030 * Called from scheduler_tick()
5032 void update_cpu_load_active(struct rq *this_rq)
5034 unsigned long load = weighted_cpuload(cpu_of(this_rq));
5036 * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
5038 this_rq->last_load_update_tick = jiffies;
5039 __update_cpu_load(this_rq, load, 1);
5043 * Return a low guess at the load of a migration-source cpu weighted
5044 * according to the scheduling class and "nice" value.
5046 * We want to under-estimate the load of migration sources, to
5047 * balance conservatively.
5049 static unsigned long source_load(int cpu, int type)
5051 struct rq *rq = cpu_rq(cpu);
5052 unsigned long total = weighted_cpuload(cpu);
5054 if (type == 0 || !sched_feat(LB_BIAS))
5057 return min(rq->cpu_load[type-1], total);
5061 * Return a high guess at the load of a migration-target cpu weighted
5062 * according to the scheduling class and "nice" value.
5064 static unsigned long target_load(int cpu, int type)
5066 struct rq *rq = cpu_rq(cpu);
5067 unsigned long total = weighted_cpuload(cpu);
5069 if (type == 0 || !sched_feat(LB_BIAS))
5072 return max(rq->cpu_load[type-1], total);
5076 static unsigned long cpu_avg_load_per_task(int cpu)
5078 struct rq *rq = cpu_rq(cpu);
5079 unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
5080 unsigned long load_avg = weighted_cpuload(cpu);
5083 return load_avg / nr_running;
5088 static void record_wakee(struct task_struct *p)
5091 * Rough decay (wiping) for cost saving, don't worry
5092 * about the boundary, really active task won't care
5095 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5096 current->wakee_flips >>= 1;
5097 current->wakee_flip_decay_ts = jiffies;
5100 if (current->last_wakee != p) {
5101 current->last_wakee = p;
5102 current->wakee_flips++;
5106 static void task_waking_fair(struct task_struct *p)
5108 struct sched_entity *se = &p->se;
5109 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5112 #ifndef CONFIG_64BIT
5113 u64 min_vruntime_copy;
5116 min_vruntime_copy = cfs_rq->min_vruntime_copy;
5118 min_vruntime = cfs_rq->min_vruntime;
5119 } while (min_vruntime != min_vruntime_copy);
5121 min_vruntime = cfs_rq->min_vruntime;
5124 se->vruntime -= min_vruntime;
5128 #ifdef CONFIG_FAIR_GROUP_SCHED
5130 * effective_load() calculates the load change as seen from the root_task_group
5132 * Adding load to a group doesn't make a group heavier, but can cause movement
5133 * of group shares between cpus. Assuming the shares were perfectly aligned one
5134 * can calculate the shift in shares.
5136 * Calculate the effective load difference if @wl is added (subtracted) to @tg
5137 * on this @cpu and results in a total addition (subtraction) of @wg to the
5138 * total group weight.
5140 * Given a runqueue weight distribution (rw_i) we can compute a shares
5141 * distribution (s_i) using:
5143 * s_i = rw_i / \Sum rw_j (1)
5145 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
5146 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
5147 * shares distribution (s_i):
5149 * rw_i = { 2, 4, 1, 0 }
5150 * s_i = { 2/7, 4/7, 1/7, 0 }
5152 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
5153 * task used to run on and the CPU the waker is running on), we need to
5154 * compute the effect of waking a task on either CPU and, in case of a sync
5155 * wakeup, compute the effect of the current task going to sleep.
5157 * So for a change of @wl to the local @cpu with an overall group weight change
5158 * of @wl we can compute the new shares distribution (s'_i) using:
5160 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
5162 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
5163 * differences in waking a task to CPU 0. The additional task changes the
5164 * weight and shares distributions like:
5166 * rw'_i = { 3, 4, 1, 0 }
5167 * s'_i = { 3/8, 4/8, 1/8, 0 }
5169 * We can then compute the difference in effective weight by using:
5171 * dw_i = S * (s'_i - s_i) (3)
5173 * Where 'S' is the group weight as seen by its parent.
5175 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
5176 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
5177 * 4/7) times the weight of the group.
5179 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5181 struct sched_entity *se = tg->se[cpu];
5183 if (!tg->parent) /* the trivial, non-cgroup case */
5186 for_each_sched_entity(se) {
5187 struct cfs_rq *cfs_rq = se->my_q;
5188 long W, w = cfs_rq_load_avg(cfs_rq);
5193 * W = @wg + \Sum rw_j
5195 W = wg + atomic_long_read(&tg->load_avg);
5197 /* Ensure \Sum rw_j >= rw_i */
5198 W -= cfs_rq->tg_load_avg_contrib;
5207 * wl = S * s'_i; see (2)
5210 wl = (w * (long)tg->shares) / W;
5215 * Per the above, wl is the new se->load.weight value; since
5216 * those are clipped to [MIN_SHARES, ...) do so now. See
5217 * calc_cfs_shares().
5219 if (wl < MIN_SHARES)
5223 * wl = dw_i = S * (s'_i - s_i); see (3)
5225 wl -= se->avg.load_avg;
5228 * Recursively apply this logic to all parent groups to compute
5229 * the final effective load change on the root group. Since
5230 * only the @tg group gets extra weight, all parent groups can
5231 * only redistribute existing shares. @wl is the shift in shares
5232 * resulting from this level per the above.
5241 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5249 * Returns the current capacity of cpu after applying both
5250 * cpu and freq scaling.
5252 unsigned long capacity_curr_of(int cpu)
5254 return cpu_rq(cpu)->cpu_capacity_orig *
5255 arch_scale_freq_capacity(NULL, cpu)
5256 >> SCHED_CAPACITY_SHIFT;
5259 static inline bool energy_aware(void)
5261 return sched_feat(ENERGY_AWARE);
5265 struct sched_group *sg_top;
5266 struct sched_group *sg_cap;
5274 struct task_struct *task;
5288 static int cpu_util_wake(int cpu, struct task_struct *p);
5291 * __cpu_norm_util() returns the cpu util relative to a specific capacity,
5292 * i.e. it's busy ratio, in the range [0..SCHED_LOAD_SCALE], which is useful for
5293 * energy calculations.
5295 * Since util is a scale-invariant utilization defined as:
5297 * util ~ (curr_freq/max_freq)*1024 * capacity_orig/1024 * running_time/time
5299 * the normalized util can be found using the specific capacity.
5301 * capacity = capacity_orig * curr_freq/max_freq
5303 * norm_util = running_time/time ~ util/capacity
5305 static unsigned long __cpu_norm_util(unsigned long util, unsigned long capacity)
5307 if (util >= capacity)
5308 return SCHED_CAPACITY_SCALE;
5310 return (util << SCHED_CAPACITY_SHIFT)/capacity;
5313 static unsigned long group_max_util(struct energy_env *eenv)
5315 unsigned long max_util = 0;
5319 for_each_cpu(cpu, sched_group_cpus(eenv->sg_cap)) {
5320 util = cpu_util_wake(cpu, eenv->task);
5323 * If we are looking at the target CPU specified by the eenv,
5324 * then we should add the (estimated) utilization of the task
5325 * assuming we will wake it up on that CPU.
5327 if (unlikely(cpu == eenv->trg_cpu))
5328 util += eenv->util_delta;
5330 max_util = max(max_util, util);
5337 * group_norm_util() returns the approximated group util relative to it's
5338 * current capacity (busy ratio), in the range [0..SCHED_LOAD_SCALE], for use
5339 * in energy calculations.
5341 * Since task executions may or may not overlap in time in the group the true
5342 * normalized util is between MAX(cpu_norm_util(i)) and SUM(cpu_norm_util(i))
5343 * when iterating over all CPUs in the group.
5344 * The latter estimate is used as it leads to a more pessimistic energy
5345 * estimate (more busy).
5348 long group_norm_util(struct energy_env *eenv, struct sched_group *sg)
5350 unsigned long capacity = sg->sge->cap_states[eenv->cap_idx].cap;
5351 unsigned long util, util_sum = 0;
5354 for_each_cpu(cpu, sched_group_cpus(sg)) {
5355 util = cpu_util_wake(cpu, eenv->task);
5358 * If we are looking at the target CPU specified by the eenv,
5359 * then we should add the (estimated) utilization of the task
5360 * assuming we will wake it up on that CPU.
5362 if (unlikely(cpu == eenv->trg_cpu))
5363 util += eenv->util_delta;
5365 util_sum += __cpu_norm_util(util, capacity);
5368 return min_t(unsigned long, util_sum, SCHED_CAPACITY_SCALE);
5371 static int find_new_capacity(struct energy_env *eenv,
5372 const struct sched_group_energy * const sge)
5374 int idx, max_idx = sge->nr_cap_states - 1;
5375 unsigned long util = group_max_util(eenv);
5377 /* default is max_cap if we don't find a match */
5378 eenv->cap_idx = max_idx;
5380 for (idx = 0; idx < sge->nr_cap_states; idx++) {
5381 if (sge->cap_states[idx].cap >= util) {
5382 eenv->cap_idx = idx;
5387 return eenv->cap_idx;
5390 static int group_idle_state(struct energy_env *eenv, struct sched_group *sg)
5392 int i, state = INT_MAX;
5393 int src_in_grp, dst_in_grp;
5396 /* Find the shallowest idle state in the sched group. */
5397 for_each_cpu(i, sched_group_cpus(sg))
5398 state = min(state, idle_get_state_idx(cpu_rq(i)));
5400 /* Take non-cpuidle idling into account (active idle/arch_cpu_idle()) */
5403 src_in_grp = cpumask_test_cpu(eenv->src_cpu, sched_group_cpus(sg));
5404 dst_in_grp = cpumask_test_cpu(eenv->dst_cpu, sched_group_cpus(sg));
5405 if (src_in_grp == dst_in_grp) {
5406 /* both CPUs under consideration are in the same group or not in
5407 * either group, migration should leave idle state the same.
5413 * Try to estimate if a deeper idle state is
5414 * achievable when we move the task.
5416 for_each_cpu(i, sched_group_cpus(sg)) {
5417 grp_util += cpu_util_wake(i, eenv->task);
5418 if (unlikely(i == eenv->trg_cpu))
5419 grp_util += eenv->util_delta;
5423 ((long)sg->sgc->max_capacity * (int)sg->group_weight)) {
5424 /* after moving, this group is at most partly
5425 * occupied, so it should have some idle time.
5427 int max_idle_state_idx = sg->sge->nr_idle_states - 2;
5428 int new_state = grp_util * max_idle_state_idx;
5430 /* group will have no util, use lowest state */
5431 new_state = max_idle_state_idx + 1;
5433 /* for partially idle, linearly map util to idle
5434 * states, excluding the lowest one. This does not
5435 * correspond to the state we expect to enter in
5436 * reality, but an indication of what might happen.
5438 new_state = min(max_idle_state_idx, (int)
5439 (new_state / sg->sgc->max_capacity));
5440 new_state = max_idle_state_idx - new_state;
5444 /* After moving, the group will be fully occupied
5445 * so assume it will not be idle at all.
5454 * sched_group_energy(): Computes the absolute energy consumption of cpus
5455 * belonging to the sched_group including shared resources shared only by
5456 * members of the group. Iterates over all cpus in the hierarchy below the
5457 * sched_group starting from the bottom working it's way up before going to
5458 * the next cpu until all cpus are covered at all levels. The current
5459 * implementation is likely to gather the same util statistics multiple times.
5460 * This can probably be done in a faster but more complex way.
5461 * Note: sched_group_energy() may fail when racing with sched_domain updates.
5463 static int sched_group_energy(struct energy_env *eenv)
5465 struct cpumask visit_cpus;
5466 u64 total_energy = 0;
5469 WARN_ON(!eenv->sg_top->sge);
5471 cpumask_copy(&visit_cpus, sched_group_cpus(eenv->sg_top));
5472 /* If a cpu is hotplugged in while we are in this function,
5473 * it does not appear in the existing visit_cpus mask
5474 * which came from the sched_group pointer of the
5475 * sched_domain pointed at by sd_ea for either the prev
5476 * or next cpu and was dereferenced in __energy_diff.
5477 * Since we will dereference sd_scs later as we iterate
5478 * through the CPUs we expect to visit, new CPUs can
5479 * be present which are not in the visit_cpus mask.
5480 * Guard this with cpu_count.
5482 cpu_count = cpumask_weight(&visit_cpus);
5484 while (!cpumask_empty(&visit_cpus)) {
5485 struct sched_group *sg_shared_cap = NULL;
5486 int cpu = cpumask_first(&visit_cpus);
5487 struct sched_domain *sd;
5490 * Is the group utilization affected by cpus outside this
5492 * This sd may have groups with cpus which were not present
5493 * when we took visit_cpus.
5495 sd = rcu_dereference(per_cpu(sd_scs, cpu));
5497 if (sd && sd->parent)
5498 sg_shared_cap = sd->parent->groups;
5500 for_each_domain(cpu, sd) {
5501 struct sched_group *sg = sd->groups;
5503 /* Has this sched_domain already been visited? */
5504 if (sd->child && group_first_cpu(sg) != cpu)
5508 unsigned long group_util;
5509 int sg_busy_energy, sg_idle_energy;
5510 int cap_idx, idle_idx;
5512 if (sg_shared_cap && sg_shared_cap->group_weight >= sg->group_weight)
5513 eenv->sg_cap = sg_shared_cap;
5517 cap_idx = find_new_capacity(eenv, sg->sge);
5519 if (sg->group_weight == 1) {
5520 /* Remove capacity of src CPU (before task move) */
5521 if (eenv->trg_cpu == eenv->src_cpu &&
5522 cpumask_test_cpu(eenv->src_cpu, sched_group_cpus(sg))) {
5523 eenv->cap.before = sg->sge->cap_states[cap_idx].cap;
5524 eenv->cap.delta -= eenv->cap.before;
5526 /* Add capacity of dst CPU (after task move) */
5527 if (eenv->trg_cpu == eenv->dst_cpu &&
5528 cpumask_test_cpu(eenv->dst_cpu, sched_group_cpus(sg))) {
5529 eenv->cap.after = sg->sge->cap_states[cap_idx].cap;
5530 eenv->cap.delta += eenv->cap.after;
5534 idle_idx = group_idle_state(eenv, sg);
5535 group_util = group_norm_util(eenv, sg);
5537 sg_busy_energy = (group_util * sg->sge->cap_states[cap_idx].power);
5538 sg_idle_energy = ((SCHED_LOAD_SCALE-group_util)
5539 * sg->sge->idle_states[idle_idx].power);
5541 total_energy += sg_busy_energy + sg_idle_energy;
5545 * cpu_count here is the number of
5546 * cpus we expect to visit in this
5547 * calculation. If we race against
5548 * hotplug, we can have extra cpus
5549 * added to the groups we are
5550 * iterating which do not appear in
5551 * the visit_cpus mask. In that case
5552 * we are not able to calculate energy
5553 * without restarting so we will bail
5554 * out and use prev_cpu this time.
5558 cpumask_xor(&visit_cpus, &visit_cpus, sched_group_cpus(sg));
5562 if (cpumask_equal(sched_group_cpus(sg), sched_group_cpus(eenv->sg_top)))
5565 } while (sg = sg->next, sg != sd->groups);
5569 * If we raced with hotplug and got an sd NULL-pointer;
5570 * returning a wrong energy estimation is better than
5571 * entering an infinite loop.
5572 * Specifically: If a cpu is unplugged after we took
5573 * the visit_cpus mask, it no longer has an sd_scs
5574 * pointer, so when we dereference it, we get NULL.
5576 if (cpumask_test_cpu(cpu, &visit_cpus))
5579 cpumask_clear_cpu(cpu, &visit_cpus);
5583 eenv->energy = total_energy >> SCHED_CAPACITY_SHIFT;
5587 static inline bool cpu_in_sg(struct sched_group *sg, int cpu)
5589 return cpu != -1 && cpumask_test_cpu(cpu, sched_group_cpus(sg));
5592 static inline unsigned long task_util(struct task_struct *p);
5595 * energy_diff(): Estimate the energy impact of changing the utilization
5596 * distribution. eenv specifies the change: utilisation amount, source, and
5597 * destination cpu. Source or destination cpu may be -1 in which case the
5598 * utilization is removed from or added to the system (e.g. task wake-up). If
5599 * both are specified, the utilization is migrated.
5601 static inline int __energy_diff(struct energy_env *eenv)
5603 struct sched_domain *sd;
5604 struct sched_group *sg;
5605 int sd_cpu = -1, energy_before = 0, energy_after = 0;
5608 struct energy_env eenv_before = {
5609 .util_delta = task_util(eenv->task),
5610 .src_cpu = eenv->src_cpu,
5611 .dst_cpu = eenv->dst_cpu,
5612 .trg_cpu = eenv->src_cpu,
5613 .nrg = { 0, 0, 0, 0},
5618 if (eenv->src_cpu == eenv->dst_cpu)
5621 sd_cpu = (eenv->src_cpu != -1) ? eenv->src_cpu : eenv->dst_cpu;
5622 sd = rcu_dereference(per_cpu(sd_ea, sd_cpu));
5625 return 0; /* Error */
5630 if (cpu_in_sg(sg, eenv->src_cpu) || cpu_in_sg(sg, eenv->dst_cpu)) {
5631 eenv_before.sg_top = eenv->sg_top = sg;
5633 if (sched_group_energy(&eenv_before))
5634 return 0; /* Invalid result abort */
5635 energy_before += eenv_before.energy;
5637 /* Keep track of SRC cpu (before) capacity */
5638 eenv->cap.before = eenv_before.cap.before;
5639 eenv->cap.delta = eenv_before.cap.delta;
5641 if (sched_group_energy(eenv))
5642 return 0; /* Invalid result abort */
5643 energy_after += eenv->energy;
5645 } while (sg = sg->next, sg != sd->groups);
5647 eenv->nrg.before = energy_before;
5648 eenv->nrg.after = energy_after;
5649 eenv->nrg.diff = eenv->nrg.after - eenv->nrg.before;
5651 #ifndef CONFIG_SCHED_TUNE
5652 trace_sched_energy_diff(eenv->task,
5653 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5654 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5655 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5656 eenv->nrg.delta, eenv->payoff);
5659 * Dead-zone margin preventing too many migrations.
5662 margin = eenv->nrg.before >> 6; /* ~1.56% */
5664 diff = eenv->nrg.after - eenv->nrg.before;
5666 eenv->nrg.diff = (abs(diff) < margin) ? 0 : eenv->nrg.diff;
5668 return eenv->nrg.diff;
5671 #ifdef CONFIG_SCHED_TUNE
5673 struct target_nrg schedtune_target_nrg;
5675 #ifdef CONFIG_CGROUP_SCHEDTUNE
5676 extern bool schedtune_initialized;
5677 #endif /* CONFIG_CGROUP_SCHEDTUNE */
5680 * System energy normalization
5681 * Returns the normalized value, in the range [0..SCHED_CAPACITY_SCALE],
5682 * corresponding to the specified energy variation.
5685 normalize_energy(int energy_diff)
5689 #ifdef CONFIG_CGROUP_SCHEDTUNE
5690 /* during early setup, we don't know the extents */
5691 if (unlikely(!schedtune_initialized))
5692 return energy_diff < 0 ? -1 : 1 ;
5693 #endif /* CONFIG_CGROUP_SCHEDTUNE */
5695 #ifdef CONFIG_SCHED_DEBUG
5699 /* Check for boundaries */
5700 max_delta = schedtune_target_nrg.max_power;
5701 max_delta -= schedtune_target_nrg.min_power;
5702 WARN_ON(abs(energy_diff) >= max_delta);
5706 /* Do scaling using positive numbers to increase the range */
5707 normalized_nrg = (energy_diff < 0) ? -energy_diff : energy_diff;
5709 /* Scale by energy magnitude */
5710 normalized_nrg <<= SCHED_CAPACITY_SHIFT;
5712 /* Normalize on max energy for target platform */
5713 normalized_nrg = reciprocal_divide(
5714 normalized_nrg, schedtune_target_nrg.rdiv);
5716 return (energy_diff < 0) ? -normalized_nrg : normalized_nrg;
5720 energy_diff(struct energy_env *eenv)
5722 int boost = schedtune_task_boost(eenv->task);
5725 /* Conpute "absolute" energy diff */
5726 __energy_diff(eenv);
5728 /* Return energy diff when boost margin is 0 */
5730 trace_sched_energy_diff(eenv->task,
5731 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5732 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5733 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5734 0, -eenv->nrg.diff);
5735 return eenv->nrg.diff;
5738 /* Compute normalized energy diff */
5739 nrg_delta = normalize_energy(eenv->nrg.diff);
5740 eenv->nrg.delta = nrg_delta;
5742 eenv->payoff = schedtune_accept_deltas(
5747 trace_sched_energy_diff(eenv->task,
5748 eenv->src_cpu, eenv->dst_cpu, eenv->util_delta,
5749 eenv->nrg.before, eenv->nrg.after, eenv->nrg.diff,
5750 eenv->cap.before, eenv->cap.after, eenv->cap.delta,
5751 eenv->nrg.delta, eenv->payoff);
5754 * When SchedTune is enabled, the energy_diff() function will return
5755 * the computed energy payoff value. Since the energy_diff() return
5756 * value is expected to be negative by its callers, this evaluation
5757 * function return a negative value each time the evaluation return a
5758 * positive payoff, which is the condition for the acceptance of
5759 * a scheduling decision
5761 return -eenv->payoff;
5763 #else /* CONFIG_SCHED_TUNE */
5764 #define energy_diff(eenv) __energy_diff(eenv)
5768 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5769 * A waker of many should wake a different task than the one last awakened
5770 * at a frequency roughly N times higher than one of its wakees. In order
5771 * to determine whether we should let the load spread vs consolodating to
5772 * shared cache, we look for a minimum 'flip' frequency of llc_size in one
5773 * partner, and a factor of lls_size higher frequency in the other. With
5774 * both conditions met, we can be relatively sure that the relationship is
5775 * non-monogamous, with partner count exceeding socket size. Waker/wakee
5776 * being client/server, worker/dispatcher, interrupt source or whatever is
5777 * irrelevant, spread criteria is apparent partner count exceeds socket size.
5779 static int wake_wide(struct task_struct *p, int sibling_count_hint)
5781 unsigned int master = current->wakee_flips;
5782 unsigned int slave = p->wakee_flips;
5783 int llc_size = this_cpu_read(sd_llc_size);
5785 if (sibling_count_hint >= llc_size)
5789 swap(master, slave);
5790 if (slave < llc_size || master < slave * llc_size)
5795 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5796 int prev_cpu, int sync)
5798 s64 this_load, load;
5799 s64 this_eff_load, prev_eff_load;
5801 struct task_group *tg;
5802 unsigned long weight;
5806 this_cpu = smp_processor_id();
5807 load = source_load(prev_cpu, idx);
5808 this_load = target_load(this_cpu, idx);
5811 * If sync wakeup then subtract the (maximum possible)
5812 * effect of the currently running task from the load
5813 * of the current CPU:
5816 tg = task_group(current);
5817 weight = current->se.avg.load_avg;
5819 this_load += effective_load(tg, this_cpu, -weight, -weight);
5820 load += effective_load(tg, prev_cpu, 0, -weight);
5824 weight = p->se.avg.load_avg;
5827 * In low-load situations, where prev_cpu is idle and this_cpu is idle
5828 * due to the sync cause above having dropped this_load to 0, we'll
5829 * always have an imbalance, but there's really nothing you can do
5830 * about that, so that's good too.
5832 * Otherwise check if either cpus are near enough in load to allow this
5833 * task to be woken on this_cpu.
5835 this_eff_load = 100;
5836 this_eff_load *= capacity_of(prev_cpu);
5838 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
5839 prev_eff_load *= capacity_of(this_cpu);
5841 if (this_load > 0) {
5842 this_eff_load *= this_load +
5843 effective_load(tg, this_cpu, weight, weight);
5845 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
5848 balanced = this_eff_load <= prev_eff_load;
5850 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
5855 schedstat_inc(sd, ttwu_move_affine);
5856 schedstat_inc(p, se.statistics.nr_wakeups_affine);
5861 static inline unsigned long task_util(struct task_struct *p)
5863 #ifdef CONFIG_SCHED_WALT
5864 if (!walt_disabled && sysctl_sched_use_walt_task_util) {
5865 unsigned long demand = p->ravg.demand;
5866 return (demand << 10) / walt_ravg_window;
5869 return p->se.avg.util_avg;
5872 static inline unsigned long boosted_task_util(struct task_struct *task);
5874 static inline bool __task_fits(struct task_struct *p, int cpu, int util)
5876 unsigned long capacity = capacity_of(cpu);
5878 util += boosted_task_util(p);
5880 return (capacity * 1024) > (util * capacity_margin);
5883 static inline bool task_fits_max(struct task_struct *p, int cpu)
5885 unsigned long capacity = capacity_of(cpu);
5886 unsigned long max_capacity = cpu_rq(cpu)->rd->max_cpu_capacity.val;
5888 if (capacity == max_capacity)
5891 if (capacity * capacity_margin > max_capacity * 1024)
5894 return __task_fits(p, cpu, 0);
5897 static bool __cpu_overutilized(int cpu, int delta)
5899 return (capacity_of(cpu) * 1024) < ((cpu_util(cpu) + delta) * capacity_margin);
5902 static bool cpu_overutilized(int cpu)
5904 return __cpu_overutilized(cpu, 0);
5907 #ifdef CONFIG_SCHED_TUNE
5909 struct reciprocal_value schedtune_spc_rdiv;
5912 schedtune_margin(unsigned long signal, long boost)
5914 long long margin = 0;
5917 * Signal proportional compensation (SPC)
5919 * The Boost (B) value is used to compute a Margin (M) which is
5920 * proportional to the complement of the original Signal (S):
5921 * M = B * (SCHED_CAPACITY_SCALE - S)
5922 * The obtained M could be used by the caller to "boost" S.
5925 margin = SCHED_CAPACITY_SCALE - signal;
5928 margin = -signal * boost;
5930 margin = reciprocal_divide(margin, schedtune_spc_rdiv);
5938 schedtune_cpu_margin(unsigned long util, int cpu)
5940 int boost = schedtune_cpu_boost(cpu);
5945 return schedtune_margin(util, boost);
5949 schedtune_task_margin(struct task_struct *task)
5951 int boost = schedtune_task_boost(task);
5958 util = task_util(task);
5959 margin = schedtune_margin(util, boost);
5964 #else /* CONFIG_SCHED_TUNE */
5967 schedtune_cpu_margin(unsigned long util, int cpu)
5973 schedtune_task_margin(struct task_struct *task)
5978 #endif /* CONFIG_SCHED_TUNE */
5981 boosted_cpu_util(int cpu)
5983 unsigned long util = cpu_util_freq(cpu);
5984 long margin = schedtune_cpu_margin(util, cpu);
5986 trace_sched_boost_cpu(cpu, util, margin);
5988 return util + margin;
5991 static inline unsigned long
5992 boosted_task_util(struct task_struct *task)
5994 unsigned long util = task_util(task);
5995 long margin = schedtune_task_margin(task);
5997 trace_sched_boost_task(task, util, margin);
5999 return util + margin;
6002 static unsigned long capacity_spare_wake(int cpu, struct task_struct *p)
6004 return max_t(long, capacity_of(cpu) - cpu_util_wake(cpu, p), 0);
6008 * find_idlest_group finds and returns the least busy CPU group within the
6011 * Assumes p is allowed on at least one CPU in sd.
6013 static struct sched_group *
6014 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
6015 int this_cpu, int sd_flag)
6017 struct sched_group *idlest = NULL, *group = sd->groups;
6018 struct sched_group *most_spare_sg = NULL;
6019 unsigned long min_load = ULONG_MAX, this_load = ULONG_MAX;
6020 unsigned long most_spare = 0, this_spare = 0;
6021 int load_idx = sd->forkexec_idx;
6022 int imbalance = 100 + (sd->imbalance_pct-100)/2;
6024 if (sd_flag & SD_BALANCE_WAKE)
6025 load_idx = sd->wake_idx;
6028 unsigned long load, avg_load, spare_cap, max_spare_cap;
6032 /* Skip over this group if it has no CPUs allowed */
6033 if (!cpumask_intersects(sched_group_cpus(group),
6034 tsk_cpus_allowed(p)))
6037 local_group = cpumask_test_cpu(this_cpu,
6038 sched_group_cpus(group));
6041 * Tally up the load of all CPUs in the group and find
6042 * the group containing the CPU with most spare capacity.
6047 for_each_cpu(i, sched_group_cpus(group)) {
6048 /* Bias balancing toward cpus of our domain */
6050 load = source_load(i, load_idx);
6052 load = target_load(i, load_idx);
6056 spare_cap = capacity_spare_wake(i, p);
6058 if (spare_cap > max_spare_cap)
6059 max_spare_cap = spare_cap;
6062 /* Adjust by relative CPU capacity of the group */
6063 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
6066 this_load = avg_load;
6067 this_spare = max_spare_cap;
6069 if (avg_load < min_load) {
6070 min_load = avg_load;
6074 if (most_spare < max_spare_cap) {
6075 most_spare = max_spare_cap;
6076 most_spare_sg = group;
6079 } while (group = group->next, group != sd->groups);
6082 * The cross-over point between using spare capacity or least load
6083 * is too conservative for high utilization tasks on partially
6084 * utilized systems if we require spare_capacity > task_util(p),
6085 * so we allow for some task stuffing by using
6086 * spare_capacity > task_util(p)/2.
6088 * Spare capacity can't be used for fork because the utilization has
6089 * not been set yet, we must first select a rq to compute the initial
6092 if (sd_flag & SD_BALANCE_FORK)
6095 if (this_spare > task_util(p) / 2 &&
6096 imbalance*this_spare > 100*most_spare)
6098 else if (most_spare > task_util(p) / 2)
6099 return most_spare_sg;
6102 if (!idlest || 100*this_load < imbalance*min_load)
6108 * find_idlest_group_cpu - find the idlest cpu among the cpus in group.
6111 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6113 unsigned long load, min_load = ULONG_MAX;
6114 unsigned int min_exit_latency = UINT_MAX;
6115 u64 latest_idle_timestamp = 0;
6116 int least_loaded_cpu = this_cpu;
6117 int shallowest_idle_cpu = -1;
6120 /* Check if we have any choice: */
6121 if (group->group_weight == 1)
6122 return cpumask_first(sched_group_cpus(group));
6124 /* Traverse only the allowed CPUs */
6125 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
6127 struct rq *rq = cpu_rq(i);
6128 struct cpuidle_state *idle = idle_get_state(rq);
6129 if (idle && idle->exit_latency < min_exit_latency) {
6131 * We give priority to a CPU whose idle state
6132 * has the smallest exit latency irrespective
6133 * of any idle timestamp.
6135 min_exit_latency = idle->exit_latency;
6136 latest_idle_timestamp = rq->idle_stamp;
6137 shallowest_idle_cpu = i;
6138 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6139 rq->idle_stamp > latest_idle_timestamp) {
6141 * If equal or no active idle state, then
6142 * the most recently idled CPU might have
6145 latest_idle_timestamp = rq->idle_stamp;
6146 shallowest_idle_cpu = i;
6148 } else if (shallowest_idle_cpu == -1) {
6149 load = weighted_cpuload(i);
6150 if (load < min_load || (load == min_load && i == this_cpu)) {
6152 least_loaded_cpu = i;
6157 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6160 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6161 int cpu, int prev_cpu, int sd_flag)
6164 int wu = sd_flag & SD_BALANCE_WAKE;
6168 schedstat_inc(p, se.statistics.nr_wakeups_cas_attempts);
6169 schedstat_inc(this_rq(), eas_stats.cas_attempts);
6172 if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
6176 struct sched_group *group;
6177 struct sched_domain *tmp;
6181 schedstat_inc(sd, eas_stats.cas_attempts);
6183 if (!(sd->flags & sd_flag)) {
6188 group = find_idlest_group(sd, p, cpu, sd_flag);
6194 new_cpu = find_idlest_group_cpu(group, p, cpu);
6195 if (new_cpu == cpu) {
6196 /* Now try balancing at a lower domain level of cpu */
6201 /* Now try balancing at a lower domain level of new_cpu */
6202 cpu = cas_cpu = new_cpu;
6203 weight = sd->span_weight;
6205 for_each_domain(cpu, tmp) {
6206 if (weight <= tmp->span_weight)
6208 if (tmp->flags & sd_flag)
6211 /* while loop will break here if sd == NULL */
6214 if (wu && (cas_cpu >= 0)) {
6215 schedstat_inc(p, se.statistics.nr_wakeups_cas_count);
6216 schedstat_inc(this_rq(), eas_stats.cas_count);
6223 * Try and locate an idle CPU in the sched_domain.
6225 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6227 struct sched_domain *sd;
6228 struct sched_group *sg;
6229 int best_idle_cpu = -1;
6230 int best_idle_cstate = INT_MAX;
6231 unsigned long best_idle_capacity = ULONG_MAX;
6233 schedstat_inc(p, se.statistics.nr_wakeups_sis_attempts);
6234 schedstat_inc(this_rq(), eas_stats.sis_attempts);
6236 if (!sysctl_sched_cstate_aware) {
6237 if (idle_cpu(target)) {
6238 schedstat_inc(p, se.statistics.nr_wakeups_sis_idle);
6239 schedstat_inc(this_rq(), eas_stats.sis_idle);
6244 * If the prevous cpu is cache affine and idle, don't be stupid.
6246 if (prev != target && cpus_share_cache(prev, target) && idle_cpu(prev)) {
6247 schedstat_inc(p, se.statistics.nr_wakeups_sis_cache_affine);
6248 schedstat_inc(this_rq(), eas_stats.sis_cache_affine);
6254 * Otherwise, iterate the domains and find an elegible idle cpu.
6256 sd = rcu_dereference(per_cpu(sd_llc, target));
6257 for_each_lower_domain(sd) {
6261 if (!cpumask_intersects(sched_group_cpus(sg),
6262 tsk_cpus_allowed(p)))
6265 if (sysctl_sched_cstate_aware) {
6266 for_each_cpu_and(i, tsk_cpus_allowed(p), sched_group_cpus(sg)) {
6267 int idle_idx = idle_get_state_idx(cpu_rq(i));
6268 unsigned long new_usage = boosted_task_util(p);
6269 unsigned long capacity_orig = capacity_orig_of(i);
6271 if (new_usage > capacity_orig || !idle_cpu(i))
6274 if (i == target && new_usage <= capacity_curr_of(target)) {
6275 schedstat_inc(p, se.statistics.nr_wakeups_sis_suff_cap);
6276 schedstat_inc(this_rq(), eas_stats.sis_suff_cap);
6277 schedstat_inc(sd, eas_stats.sis_suff_cap);
6281 if (idle_idx < best_idle_cstate &&
6282 capacity_orig <= best_idle_capacity) {
6284 best_idle_cstate = idle_idx;
6285 best_idle_capacity = capacity_orig;
6289 for_each_cpu(i, sched_group_cpus(sg)) {
6290 if (i == target || !idle_cpu(i))
6294 target = cpumask_first_and(sched_group_cpus(sg),
6295 tsk_cpus_allowed(p));
6296 schedstat_inc(p, se.statistics.nr_wakeups_sis_idle_cpu);
6297 schedstat_inc(this_rq(), eas_stats.sis_idle_cpu);
6298 schedstat_inc(sd, eas_stats.sis_idle_cpu);
6303 } while (sg != sd->groups);
6306 if (best_idle_cpu >= 0)
6307 target = best_idle_cpu;
6310 schedstat_inc(p, se.statistics.nr_wakeups_sis_count);
6311 schedstat_inc(this_rq(), eas_stats.sis_count);
6317 * cpu_util_wake: Compute cpu utilization with any contributions from
6318 * the waking task p removed. check_for_migration() looks for a better CPU of
6319 * rq->curr. For that case we should return cpu util with contributions from
6320 * currently running task p removed.
6322 static int cpu_util_wake(int cpu, struct task_struct *p)
6324 unsigned long util, capacity;
6326 #ifdef CONFIG_SCHED_WALT
6328 * WALT does not decay idle tasks in the same manner
6329 * as PELT, so it makes little sense to subtract task
6330 * utilization from cpu utilization. Instead just use
6331 * cpu_util for this case.
6333 if (!walt_disabled && sysctl_sched_use_walt_cpu_util &&
6334 p->state == TASK_WAKING)
6335 return cpu_util(cpu);
6337 /* Task has no contribution or is new */
6338 if (cpu != task_cpu(p) || !p->se.avg.last_update_time)
6339 return cpu_util(cpu);
6341 capacity = capacity_orig_of(cpu);
6342 util = max_t(long, cpu_util(cpu) - task_util(p), 0);
6344 return (util >= capacity) ? capacity : util;
6347 static int start_cpu(bool boosted)
6349 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6351 return boosted ? rd->max_cap_orig_cpu : rd->min_cap_orig_cpu;
6354 static inline int find_best_target(struct task_struct *p, int *backup_cpu,
6355 bool boosted, bool prefer_idle)
6357 unsigned long best_idle_min_cap_orig = ULONG_MAX;
6358 unsigned long min_util = boosted_task_util(p);
6359 unsigned long target_capacity = ULONG_MAX;
6360 unsigned long min_wake_util = ULONG_MAX;
6361 unsigned long target_max_spare_cap = 0;
6362 unsigned long best_active_util = ULONG_MAX;
6363 int best_idle_cstate = INT_MAX;
6364 struct sched_domain *sd;
6365 struct sched_group *sg;
6366 int best_active_cpu = -1;
6367 int best_idle_cpu = -1;
6368 int target_cpu = -1;
6373 schedstat_inc(p, se.statistics.nr_wakeups_fbt_attempts);
6374 schedstat_inc(this_rq(), eas_stats.fbt_attempts);
6376 /* Find start CPU based on boost value */
6377 cpu = start_cpu(boosted);
6379 schedstat_inc(p, se.statistics.nr_wakeups_fbt_no_cpu);
6380 schedstat_inc(this_rq(), eas_stats.fbt_no_cpu);
6384 /* Find SD for the start CPU */
6385 sd = rcu_dereference(per_cpu(sd_ea, cpu));
6387 schedstat_inc(p, se.statistics.nr_wakeups_fbt_no_sd);
6388 schedstat_inc(this_rq(), eas_stats.fbt_no_sd);
6392 /* Scan CPUs in all SDs */
6395 for_each_cpu_and(i, tsk_cpus_allowed(p), sched_group_cpus(sg)) {
6396 unsigned long capacity_curr = capacity_curr_of(i);
6397 unsigned long capacity_orig = capacity_orig_of(i);
6398 unsigned long wake_util, new_util;
6403 if (walt_cpu_high_irqload(i))
6407 * p's blocked utilization is still accounted for on prev_cpu
6408 * so prev_cpu will receive a negative bias due to the double
6409 * accounting. However, the blocked utilization may be zero.
6411 wake_util = cpu_util_wake(i, p);
6412 new_util = wake_util + task_util(p);
6415 * Ensure minimum capacity to grant the required boost.
6416 * The target CPU can be already at a capacity level higher
6417 * than the one required to boost the task.
6419 new_util = max(min_util, new_util);
6420 if (new_util > capacity_orig)
6424 * Case A) Latency sensitive tasks
6426 * Unconditionally favoring tasks that prefer idle CPU to
6430 * - an idle CPU, whatever its idle_state is, since
6431 * the first CPUs we explore are more likely to be
6432 * reserved for latency sensitive tasks.
6433 * - a non idle CPU where the task fits in its current
6434 * capacity and has the maximum spare capacity.
6435 * - a non idle CPU with lower contention from other
6436 * tasks and running at the lowest possible OPP.
6438 * The last two goals tries to favor a non idle CPU
6439 * where the task can run as if it is "almost alone".
6440 * A maximum spare capacity CPU is favoured since
6441 * the task already fits into that CPU's capacity
6442 * without waiting for an OPP chance.
6444 * The following code path is the only one in the CPUs
6445 * exploration loop which is always used by
6446 * prefer_idle tasks. It exits the loop with wither a
6447 * best_active_cpu or a target_cpu which should
6448 * represent an optimal choice for latency sensitive
6454 * Case A.1: IDLE CPU
6455 * Return the first IDLE CPU we find.
6458 schedstat_inc(p, se.statistics.nr_wakeups_fbt_pref_idle);
6459 schedstat_inc(this_rq(), eas_stats.fbt_pref_idle);
6461 trace_sched_find_best_target(p,
6462 prefer_idle, min_util,
6464 best_active_cpu, i);
6470 * Case A.2: Target ACTIVE CPU
6471 * Favor CPUs with max spare capacity.
6473 if ((capacity_curr > new_util) &&
6474 (capacity_orig - new_util > target_max_spare_cap)) {
6475 target_max_spare_cap = capacity_orig - new_util;
6479 if (target_cpu != -1)
6484 * Case A.3: Backup ACTIVE CPU
6486 * - lower utilization due to other tasks
6487 * - lower utilization with the task in
6489 if (wake_util > min_wake_util)
6491 if (new_util > best_active_util)
6493 min_wake_util = wake_util;
6494 best_active_util = new_util;
6495 best_active_cpu = i;
6502 * For non latency sensitive tasks, skip CPUs that
6503 * will be overutilized by moving the task there.
6505 * The goal here is to remain in EAS mode as long as
6506 * possible at least for !prefer_idle tasks.
6508 if ((new_util * capacity_margin) >
6509 (capacity_orig * SCHED_CAPACITY_SCALE))
6513 * Case B) Non latency sensitive tasks on IDLE CPUs.
6515 * Find an optimal backup IDLE CPU for non latency
6519 * - minimizing the capacity_orig,
6520 * i.e. preferring LITTLE CPUs
6521 * - favoring shallowest idle states
6522 * i.e. avoid to wakeup deep-idle CPUs
6524 * The following code path is used by non latency
6525 * sensitive tasks if IDLE CPUs are available. If at
6526 * least one of such CPUs are available it sets the
6527 * best_idle_cpu to the most suitable idle CPU to be
6530 * If idle CPUs are available, favour these CPUs to
6531 * improve performances by spreading tasks.
6532 * Indeed, the energy_diff() computed by the caller
6533 * will take care to ensure the minimization of energy
6534 * consumptions without affecting performance.
6537 int idle_idx = idle_get_state_idx(cpu_rq(i));
6539 /* Select idle CPU with lower cap_orig */
6540 if (capacity_orig > best_idle_min_cap_orig)
6544 * Skip CPUs in deeper idle state, but only
6545 * if they are also less energy efficient.
6546 * IOW, prefer a deep IDLE LITTLE CPU vs a
6547 * shallow idle big CPU.
6549 if (sysctl_sched_cstate_aware &&
6550 best_idle_cstate <= idle_idx)
6553 /* Keep track of best idle CPU */
6554 best_idle_min_cap_orig = capacity_orig;
6555 best_idle_cstate = idle_idx;
6561 * Case C) Non latency sensitive tasks on ACTIVE CPUs.
6563 * Pack tasks in the most energy efficient capacities.
6565 * This task packing strategy prefers more energy
6566 * efficient CPUs (i.e. pack on smaller maximum
6567 * capacity CPUs) while also trying to spread tasks to
6568 * run them all at the lower OPP.
6570 * This assumes for example that it's more energy
6571 * efficient to run two tasks on two CPUs at a lower
6572 * OPP than packing both on a single CPU but running
6573 * that CPU at an higher OPP.
6575 * Thus, this case keep track of the CPU with the
6576 * smallest maximum capacity and highest spare maximum
6580 /* Favor CPUs with smaller capacity */
6581 if (capacity_orig > target_capacity)
6584 /* Favor CPUs with maximum spare capacity */
6585 if ((capacity_orig - new_util) < target_max_spare_cap)
6588 target_max_spare_cap = capacity_orig - new_util;
6589 target_capacity = capacity_orig;
6593 } while (sg = sg->next, sg != sd->groups);
6596 * For non latency sensitive tasks, cases B and C in the previous loop,
6597 * we pick the best IDLE CPU only if we was not able to find a target
6600 * Policies priorities:
6602 * - prefer_idle tasks:
6604 * a) IDLE CPU available, we return immediately
6605 * b) ACTIVE CPU where task fits and has the bigger maximum spare
6606 * capacity (i.e. target_cpu)
6607 * c) ACTIVE CPU with less contention due to other tasks
6608 * (i.e. best_active_cpu)
6610 * - NON prefer_idle tasks:
6612 * a) ACTIVE CPU: target_cpu
6613 * b) IDLE CPU: best_idle_cpu
6615 if (target_cpu == -1)
6616 target_cpu = prefer_idle
6620 *backup_cpu = prefer_idle
6624 trace_sched_find_best_target(p, prefer_idle, min_util, cpu,
6625 best_idle_cpu, best_active_cpu,
6628 schedstat_inc(p, se.statistics.nr_wakeups_fbt_count);
6629 schedstat_inc(this_rq(), eas_stats.fbt_count);
6635 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
6636 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
6638 * In that case WAKE_AFFINE doesn't make sense and we'll let
6639 * BALANCE_WAKE sort things out.
6641 static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
6643 long min_cap, max_cap;
6645 min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
6646 max_cap = cpu_rq(cpu)->rd->max_cpu_capacity.val;
6648 /* Minimum capacity is close to max, no need to abort wake_affine */
6649 if (max_cap - min_cap < max_cap >> 3)
6652 /* Bring task utilization in sync with prev_cpu */
6653 sync_entity_load_avg(&p->se);
6655 return min_cap * 1024 < task_util(p) * capacity_margin;
6658 static int select_energy_cpu_brute(struct task_struct *p, int prev_cpu, int sync)
6660 struct sched_domain *sd;
6661 int target_cpu = prev_cpu, tmp_target, tmp_backup;
6662 bool boosted, prefer_idle;
6664 schedstat_inc(p, se.statistics.nr_wakeups_secb_attempts);
6665 schedstat_inc(this_rq(), eas_stats.secb_attempts);
6667 if (sysctl_sched_sync_hint_enable && sync) {
6668 int cpu = smp_processor_id();
6670 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
6671 schedstat_inc(p, se.statistics.nr_wakeups_secb_sync);
6672 schedstat_inc(this_rq(), eas_stats.secb_sync);
6678 #ifdef CONFIG_CGROUP_SCHEDTUNE
6679 boosted = schedtune_task_boost(p) > 0;
6680 prefer_idle = schedtune_prefer_idle(p) > 0;
6682 boosted = get_sysctl_sched_cfs_boost() > 0;
6686 sync_entity_load_avg(&p->se);
6688 sd = rcu_dereference(per_cpu(sd_ea, prev_cpu));
6689 /* Find a cpu with sufficient capacity */
6690 tmp_target = find_best_target(p, &tmp_backup, boosted, prefer_idle);
6694 if (tmp_target >= 0) {
6695 target_cpu = tmp_target;
6696 if ((boosted || prefer_idle) && idle_cpu(target_cpu)) {
6697 schedstat_inc(p, se.statistics.nr_wakeups_secb_idle_bt);
6698 schedstat_inc(this_rq(), eas_stats.secb_idle_bt);
6703 if (target_cpu != prev_cpu) {
6705 struct energy_env eenv = {
6706 .util_delta = task_util(p),
6707 .src_cpu = prev_cpu,
6708 .dst_cpu = target_cpu,
6710 .trg_cpu = target_cpu,
6714 #ifdef CONFIG_SCHED_WALT
6715 if (!walt_disabled && sysctl_sched_use_walt_cpu_util &&
6716 p->state == TASK_WAKING)
6717 delta = task_util(p);
6719 /* Not enough spare capacity on previous cpu */
6720 if (__cpu_overutilized(prev_cpu, delta)) {
6721 schedstat_inc(p, se.statistics.nr_wakeups_secb_insuff_cap);
6722 schedstat_inc(this_rq(), eas_stats.secb_insuff_cap);
6726 if (energy_diff(&eenv) >= 0) {
6727 /* No energy saving for target_cpu, try backup */
6728 target_cpu = tmp_backup;
6729 eenv.dst_cpu = target_cpu;
6730 eenv.trg_cpu = target_cpu;
6731 if (tmp_backup < 0 ||
6732 tmp_backup == prev_cpu ||
6733 energy_diff(&eenv) >= 0) {
6734 schedstat_inc(p, se.statistics.nr_wakeups_secb_no_nrg_sav);
6735 schedstat_inc(this_rq(), eas_stats.secb_no_nrg_sav);
6736 target_cpu = prev_cpu;
6741 schedstat_inc(p, se.statistics.nr_wakeups_secb_nrg_sav);
6742 schedstat_inc(this_rq(), eas_stats.secb_nrg_sav);
6746 schedstat_inc(p, se.statistics.nr_wakeups_secb_count);
6747 schedstat_inc(this_rq(), eas_stats.secb_count);
6756 * select_task_rq_fair: Select target runqueue for the waking task in domains
6757 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
6758 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
6760 * Balances load by selecting the idlest cpu in the idlest group, or under
6761 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
6763 * Returns the target cpu number.
6765 * preempt must be disabled.
6768 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags,
6769 int sibling_count_hint)
6771 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
6772 int cpu = smp_processor_id();
6773 int new_cpu = prev_cpu;
6774 int want_affine = 0;
6775 int sync = wake_flags & WF_SYNC;
6777 if (sd_flag & SD_BALANCE_WAKE) {
6779 want_affine = !wake_wide(p, sibling_count_hint) &&
6780 !wake_cap(p, cpu, prev_cpu) &&
6781 cpumask_test_cpu(cpu, &p->cpus_allowed);
6784 if (energy_aware() && !(cpu_rq(prev_cpu)->rd->overutilized))
6785 return select_energy_cpu_brute(p, prev_cpu, sync);
6788 for_each_domain(cpu, tmp) {
6789 if (!(tmp->flags & SD_LOAD_BALANCE))
6793 * If both cpu and prev_cpu are part of this domain,
6794 * cpu is a valid SD_WAKE_AFFINE target.
6796 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6797 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
6802 if (tmp->flags & sd_flag)
6804 else if (!want_affine)
6809 sd = NULL; /* Prefer wake_affine over balance flags */
6810 if (cpu != prev_cpu && wake_affine(affine_sd, p, prev_cpu, sync))
6814 if (sd && !(sd_flag & SD_BALANCE_FORK)) {
6816 * We're going to need the task's util for capacity_spare_wake
6817 * in find_idlest_group. Sync it up to prev_cpu's
6820 sync_entity_load_avg(&p->se);
6824 if (sd_flag & SD_BALANCE_WAKE) /* XXX always ? */
6825 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6828 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
6836 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
6837 * cfs_rq_of(p) references at time of call are still valid and identify the
6838 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
6839 * other assumptions, including the state of rq->lock, should be made.
6841 static void migrate_task_rq_fair(struct task_struct *p)
6844 * We are supposed to update the task to "current" time, then its up to date
6845 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
6846 * what current time is, so simply throw away the out-of-date time. This
6847 * will result in the wakee task is less decayed, but giving the wakee more
6848 * load sounds not bad.
6850 remove_entity_load_avg(&p->se);
6852 /* Tell new CPU we are migrated */
6853 p->se.avg.last_update_time = 0;
6855 /* We have migrated, no longer consider this task hot */
6856 p->se.exec_start = 0;
6859 static void task_dead_fair(struct task_struct *p)
6861 remove_entity_load_avg(&p->se);
6864 #define task_fits_max(p, cpu) true
6865 #endif /* CONFIG_SMP */
6867 static unsigned long
6868 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
6870 unsigned long gran = sysctl_sched_wakeup_granularity;
6873 * Since its curr running now, convert the gran from real-time
6874 * to virtual-time in his units.
6876 * By using 'se' instead of 'curr' we penalize light tasks, so
6877 * they get preempted easier. That is, if 'se' < 'curr' then
6878 * the resulting gran will be larger, therefore penalizing the
6879 * lighter, if otoh 'se' > 'curr' then the resulting gran will
6880 * be smaller, again penalizing the lighter task.
6882 * This is especially important for buddies when the leftmost
6883 * task is higher priority than the buddy.
6885 return calc_delta_fair(gran, se);
6889 * Should 'se' preempt 'curr'.
6903 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
6905 s64 gran, vdiff = curr->vruntime - se->vruntime;
6910 gran = wakeup_gran(curr, se);
6917 static void set_last_buddy(struct sched_entity *se)
6919 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
6922 for_each_sched_entity(se)
6923 cfs_rq_of(se)->last = se;
6926 static void set_next_buddy(struct sched_entity *se)
6928 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
6931 for_each_sched_entity(se)
6932 cfs_rq_of(se)->next = se;
6935 static void set_skip_buddy(struct sched_entity *se)
6937 for_each_sched_entity(se)
6938 cfs_rq_of(se)->skip = se;
6942 * Preempt the current task with a newly woken task if needed:
6944 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
6946 struct task_struct *curr = rq->curr;
6947 struct sched_entity *se = &curr->se, *pse = &p->se;
6948 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6949 int scale = cfs_rq->nr_running >= sched_nr_latency;
6950 int next_buddy_marked = 0;
6952 if (unlikely(se == pse))
6956 * This is possible from callers such as attach_tasks(), in which we
6957 * unconditionally check_prempt_curr() after an enqueue (which may have
6958 * lead to a throttle). This both saves work and prevents false
6959 * next-buddy nomination below.
6961 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
6964 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
6965 set_next_buddy(pse);
6966 next_buddy_marked = 1;
6970 * We can come here with TIF_NEED_RESCHED already set from new task
6973 * Note: this also catches the edge-case of curr being in a throttled
6974 * group (e.g. via set_curr_task), since update_curr() (in the
6975 * enqueue of curr) will have resulted in resched being set. This
6976 * prevents us from potentially nominating it as a false LAST_BUDDY
6979 if (test_tsk_need_resched(curr))
6982 /* Idle tasks are by definition preempted by non-idle tasks. */
6983 if (unlikely(curr->policy == SCHED_IDLE) &&
6984 likely(p->policy != SCHED_IDLE))
6988 * Batch and idle tasks do not preempt non-idle tasks (their preemption
6989 * is driven by the tick):
6991 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
6994 find_matching_se(&se, &pse);
6995 update_curr(cfs_rq_of(se));
6997 if (wakeup_preempt_entity(se, pse) == 1) {
6999 * Bias pick_next to pick the sched entity that is
7000 * triggering this preemption.
7002 if (!next_buddy_marked)
7003 set_next_buddy(pse);
7012 * Only set the backward buddy when the current task is still
7013 * on the rq. This can happen when a wakeup gets interleaved
7014 * with schedule on the ->pre_schedule() or idle_balance()
7015 * point, either of which can * drop the rq lock.
7017 * Also, during early boot the idle thread is in the fair class,
7018 * for obvious reasons its a bad idea to schedule back to it.
7020 if (unlikely(!se->on_rq || curr == rq->idle))
7023 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7027 static struct task_struct *
7028 pick_next_task_fair(struct rq *rq, struct task_struct *prev)
7030 struct cfs_rq *cfs_rq = &rq->cfs;
7031 struct sched_entity *se;
7032 struct task_struct *p;
7036 #ifdef CONFIG_FAIR_GROUP_SCHED
7037 if (!cfs_rq->nr_running)
7040 if (prev->sched_class != &fair_sched_class)
7044 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7045 * likely that a next task is from the same cgroup as the current.
7047 * Therefore attempt to avoid putting and setting the entire cgroup
7048 * hierarchy, only change the part that actually changes.
7052 struct sched_entity *curr = cfs_rq->curr;
7055 * Since we got here without doing put_prev_entity() we also
7056 * have to consider cfs_rq->curr. If it is still a runnable
7057 * entity, update_curr() will update its vruntime, otherwise
7058 * forget we've ever seen it.
7062 update_curr(cfs_rq);
7067 * This call to check_cfs_rq_runtime() will do the
7068 * throttle and dequeue its entity in the parent(s).
7069 * Therefore the 'simple' nr_running test will indeed
7072 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
7076 se = pick_next_entity(cfs_rq, curr);
7077 cfs_rq = group_cfs_rq(se);
7083 * Since we haven't yet done put_prev_entity and if the selected task
7084 * is a different task than we started out with, try and touch the
7085 * least amount of cfs_rqs.
7088 struct sched_entity *pse = &prev->se;
7090 while (!(cfs_rq = is_same_group(se, pse))) {
7091 int se_depth = se->depth;
7092 int pse_depth = pse->depth;
7094 if (se_depth <= pse_depth) {
7095 put_prev_entity(cfs_rq_of(pse), pse);
7096 pse = parent_entity(pse);
7098 if (se_depth >= pse_depth) {
7099 set_next_entity(cfs_rq_of(se), se);
7100 se = parent_entity(se);
7104 put_prev_entity(cfs_rq, pse);
7105 set_next_entity(cfs_rq, se);
7108 if (hrtick_enabled(rq))
7109 hrtick_start_fair(rq, p);
7111 rq->misfit_task = !task_fits_max(p, rq->cpu);
7118 if (!cfs_rq->nr_running)
7121 put_prev_task(rq, prev);
7124 se = pick_next_entity(cfs_rq, NULL);
7125 set_next_entity(cfs_rq, se);
7126 cfs_rq = group_cfs_rq(se);
7131 if (hrtick_enabled(rq))
7132 hrtick_start_fair(rq, p);
7134 rq->misfit_task = !task_fits_max(p, rq->cpu);
7139 rq->misfit_task = 0;
7141 * This is OK, because current is on_cpu, which avoids it being picked
7142 * for load-balance and preemption/IRQs are still disabled avoiding
7143 * further scheduler activity on it and we're being very careful to
7144 * re-start the picking loop.
7146 lockdep_unpin_lock(&rq->lock);
7147 new_tasks = idle_balance(rq);
7148 lockdep_pin_lock(&rq->lock);
7150 * Because idle_balance() releases (and re-acquires) rq->lock, it is
7151 * possible for any higher priority task to appear. In that case we
7152 * must re-start the pick_next_entity() loop.
7164 * Account for a descheduled task:
7166 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
7168 struct sched_entity *se = &prev->se;
7169 struct cfs_rq *cfs_rq;
7171 for_each_sched_entity(se) {
7172 cfs_rq = cfs_rq_of(se);
7173 put_prev_entity(cfs_rq, se);
7178 * sched_yield() is very simple
7180 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7182 static void yield_task_fair(struct rq *rq)
7184 struct task_struct *curr = rq->curr;
7185 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7186 struct sched_entity *se = &curr->se;
7189 * Are we the only task in the tree?
7191 if (unlikely(rq->nr_running == 1))
7194 clear_buddies(cfs_rq, se);
7196 if (curr->policy != SCHED_BATCH) {
7197 update_rq_clock(rq);
7199 * Update run-time statistics of the 'current'.
7201 update_curr(cfs_rq);
7203 * Tell update_rq_clock() that we've just updated,
7204 * so we don't do microscopic update in schedule()
7205 * and double the fastpath cost.
7207 rq_clock_skip_update(rq, true);
7213 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
7215 struct sched_entity *se = &p->se;
7217 /* throttled hierarchies are not runnable */
7218 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
7221 /* Tell the scheduler that we'd really like pse to run next. */
7224 yield_task_fair(rq);
7230 /**************************************************
7231 * Fair scheduling class load-balancing methods.
7235 * The purpose of load-balancing is to achieve the same basic fairness the
7236 * per-cpu scheduler provides, namely provide a proportional amount of compute
7237 * time to each task. This is expressed in the following equation:
7239 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
7241 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
7242 * W_i,0 is defined as:
7244 * W_i,0 = \Sum_j w_i,j (2)
7246 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
7247 * is derived from the nice value as per prio_to_weight[].
7249 * The weight average is an exponential decay average of the instantaneous
7252 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
7254 * C_i is the compute capacity of cpu i, typically it is the
7255 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7256 * can also include other factors [XXX].
7258 * To achieve this balance we define a measure of imbalance which follows
7259 * directly from (1):
7261 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
7263 * We them move tasks around to minimize the imbalance. In the continuous
7264 * function space it is obvious this converges, in the discrete case we get
7265 * a few fun cases generally called infeasible weight scenarios.
7268 * - infeasible weights;
7269 * - local vs global optima in the discrete case. ]
7274 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
7275 * for all i,j solution, we create a tree of cpus that follows the hardware
7276 * topology where each level pairs two lower groups (or better). This results
7277 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
7278 * tree to only the first of the previous level and we decrease the frequency
7279 * of load-balance at each level inv. proportional to the number of cpus in
7285 * \Sum { --- * --- * 2^i } = O(n) (5)
7287 * `- size of each group
7288 * | | `- number of cpus doing load-balance
7290 * `- sum over all levels
7292 * Coupled with a limit on how many tasks we can migrate every balance pass,
7293 * this makes (5) the runtime complexity of the balancer.
7295 * An important property here is that each CPU is still (indirectly) connected
7296 * to every other cpu in at most O(log n) steps:
7298 * The adjacency matrix of the resulting graph is given by:
7301 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
7304 * And you'll find that:
7306 * A^(log_2 n)_i,j != 0 for all i,j (7)
7308 * Showing there's indeed a path between every cpu in at most O(log n) steps.
7309 * The task movement gives a factor of O(m), giving a convergence complexity
7312 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
7317 * In order to avoid CPUs going idle while there's still work to do, new idle
7318 * balancing is more aggressive and has the newly idle cpu iterate up the domain
7319 * tree itself instead of relying on other CPUs to bring it work.
7321 * This adds some complexity to both (5) and (8) but it reduces the total idle
7329 * Cgroups make a horror show out of (2), instead of a simple sum we get:
7332 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
7337 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
7339 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
7341 * The big problem is S_k, its a global sum needed to compute a local (W_i)
7344 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7345 * rewrite all of this once again.]
7348 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7350 enum fbq_type { regular, remote, all };
7359 #define LBF_ALL_PINNED 0x01
7360 #define LBF_NEED_BREAK 0x02
7361 #define LBF_DST_PINNED 0x04
7362 #define LBF_SOME_PINNED 0x08
7365 struct sched_domain *sd;
7373 struct cpumask *dst_grpmask;
7375 enum cpu_idle_type idle;
7377 unsigned int src_grp_nr_running;
7378 /* The set of CPUs under consideration for load-balancing */
7379 struct cpumask *cpus;
7384 unsigned int loop_break;
7385 unsigned int loop_max;
7387 enum fbq_type fbq_type;
7388 enum group_type busiest_group_type;
7389 struct list_head tasks;
7393 * Is this task likely cache-hot:
7395 static int task_hot(struct task_struct *p, struct lb_env *env)
7399 lockdep_assert_held(&env->src_rq->lock);
7401 if (p->sched_class != &fair_sched_class)
7404 if (unlikely(p->policy == SCHED_IDLE))
7408 * Buddy candidates are cache hot:
7410 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
7411 (&p->se == cfs_rq_of(&p->se)->next ||
7412 &p->se == cfs_rq_of(&p->se)->last))
7415 if (sysctl_sched_migration_cost == -1)
7417 if (sysctl_sched_migration_cost == 0)
7420 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
7422 return delta < (s64)sysctl_sched_migration_cost;
7425 #ifdef CONFIG_NUMA_BALANCING
7427 * Returns 1, if task migration degrades locality
7428 * Returns 0, if task migration improves locality i.e migration preferred.
7429 * Returns -1, if task migration is not affected by locality.
7431 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
7433 struct numa_group *numa_group = rcu_dereference(p->numa_group);
7434 unsigned long src_faults, dst_faults;
7435 int src_nid, dst_nid;
7437 if (!static_branch_likely(&sched_numa_balancing))
7440 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
7443 src_nid = cpu_to_node(env->src_cpu);
7444 dst_nid = cpu_to_node(env->dst_cpu);
7446 if (src_nid == dst_nid)
7449 /* Migrating away from the preferred node is always bad. */
7450 if (src_nid == p->numa_preferred_nid) {
7451 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7457 /* Encourage migration to the preferred node. */
7458 if (dst_nid == p->numa_preferred_nid)
7462 src_faults = group_faults(p, src_nid);
7463 dst_faults = group_faults(p, dst_nid);
7465 src_faults = task_faults(p, src_nid);
7466 dst_faults = task_faults(p, dst_nid);
7469 return dst_faults < src_faults;
7473 static inline int migrate_degrades_locality(struct task_struct *p,
7481 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7484 int can_migrate_task(struct task_struct *p, struct lb_env *env)
7488 lockdep_assert_held(&env->src_rq->lock);
7491 * We do not migrate tasks that are:
7492 * 1) throttled_lb_pair, or
7493 * 2) cannot be migrated to this CPU due to cpus_allowed, or
7494 * 3) running (obviously), or
7495 * 4) are cache-hot on their current CPU.
7497 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7500 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
7503 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
7505 env->flags |= LBF_SOME_PINNED;
7508 * Remember if this task can be migrated to any other cpu in
7509 * our sched_group. We may want to revisit it if we couldn't
7510 * meet load balance goals by pulling other tasks on src_cpu.
7512 * Also avoid computing new_dst_cpu if we have already computed
7513 * one in current iteration.
7515 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
7518 /* Prevent to re-select dst_cpu via env's cpus */
7519 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
7520 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
7521 env->flags |= LBF_DST_PINNED;
7522 env->new_dst_cpu = cpu;
7530 /* Record that we found atleast one task that could run on dst_cpu */
7531 env->flags &= ~LBF_ALL_PINNED;
7533 if (task_running(env->src_rq, p)) {
7534 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
7539 * Aggressive migration if:
7540 * 1) destination numa is preferred
7541 * 2) task is cache cold, or
7542 * 3) too many balance attempts have failed.
7544 tsk_cache_hot = migrate_degrades_locality(p, env);
7545 if (tsk_cache_hot == -1)
7546 tsk_cache_hot = task_hot(p, env);
7548 if (tsk_cache_hot <= 0 ||
7549 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
7550 if (tsk_cache_hot == 1) {
7551 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
7552 schedstat_inc(p, se.statistics.nr_forced_migrations);
7557 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
7562 * detach_task() -- detach the task for the migration specified in env
7564 static void detach_task(struct task_struct *p, struct lb_env *env)
7566 lockdep_assert_held(&env->src_rq->lock);
7568 deactivate_task(env->src_rq, p, 0);
7569 p->on_rq = TASK_ON_RQ_MIGRATING;
7570 double_lock_balance(env->src_rq, env->dst_rq);
7571 set_task_cpu(p, env->dst_cpu);
7572 double_unlock_balance(env->src_rq, env->dst_rq);
7576 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
7577 * part of active balancing operations within "domain".
7579 * Returns a task if successful and NULL otherwise.
7581 static struct task_struct *detach_one_task(struct lb_env *env)
7583 struct task_struct *p, *n;
7585 lockdep_assert_held(&env->src_rq->lock);
7587 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
7588 if (!can_migrate_task(p, env))
7591 detach_task(p, env);
7594 * Right now, this is only the second place where
7595 * lb_gained[env->idle] is updated (other is detach_tasks)
7596 * so we can safely collect stats here rather than
7597 * inside detach_tasks().
7599 schedstat_inc(env->sd, lb_gained[env->idle]);
7605 static const unsigned int sched_nr_migrate_break = 32;
7608 * detach_tasks() -- tries to detach up to imbalance weighted load from
7609 * busiest_rq, as part of a balancing operation within domain "sd".
7611 * Returns number of detached tasks if successful and 0 otherwise.
7613 static int detach_tasks(struct lb_env *env)
7615 struct list_head *tasks = &env->src_rq->cfs_tasks;
7616 struct task_struct *p;
7620 lockdep_assert_held(&env->src_rq->lock);
7622 if (env->imbalance <= 0)
7625 while (!list_empty(tasks)) {
7627 * We don't want to steal all, otherwise we may be treated likewise,
7628 * which could at worst lead to a livelock crash.
7630 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
7633 p = list_first_entry(tasks, struct task_struct, se.group_node);
7636 /* We've more or less seen every task there is, call it quits */
7637 if (env->loop > env->loop_max)
7640 /* take a breather every nr_migrate tasks */
7641 if (env->loop > env->loop_break) {
7642 env->loop_break += sched_nr_migrate_break;
7643 env->flags |= LBF_NEED_BREAK;
7647 if (!can_migrate_task(p, env))
7650 load = task_h_load(p);
7652 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
7655 if ((load / 2) > env->imbalance)
7658 detach_task(p, env);
7659 list_add(&p->se.group_node, &env->tasks);
7662 env->imbalance -= load;
7664 #ifdef CONFIG_PREEMPT
7666 * NEWIDLE balancing is a source of latency, so preemptible
7667 * kernels will stop after the first task is detached to minimize
7668 * the critical section.
7670 if (env->idle == CPU_NEWLY_IDLE)
7675 * We only want to steal up to the prescribed amount of
7678 if (env->imbalance <= 0)
7683 list_move_tail(&p->se.group_node, tasks);
7687 * Right now, this is one of only two places we collect this stat
7688 * so we can safely collect detach_one_task() stats here rather
7689 * than inside detach_one_task().
7691 schedstat_add(env->sd, lb_gained[env->idle], detached);
7697 * attach_task() -- attach the task detached by detach_task() to its new rq.
7699 static void attach_task(struct rq *rq, struct task_struct *p)
7701 lockdep_assert_held(&rq->lock);
7703 BUG_ON(task_rq(p) != rq);
7704 p->on_rq = TASK_ON_RQ_QUEUED;
7705 activate_task(rq, p, 0);
7706 check_preempt_curr(rq, p, 0);
7710 * attach_one_task() -- attaches the task returned from detach_one_task() to
7713 static void attach_one_task(struct rq *rq, struct task_struct *p)
7715 raw_spin_lock(&rq->lock);
7717 raw_spin_unlock(&rq->lock);
7721 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
7724 static void attach_tasks(struct lb_env *env)
7726 struct list_head *tasks = &env->tasks;
7727 struct task_struct *p;
7729 raw_spin_lock(&env->dst_rq->lock);
7731 while (!list_empty(tasks)) {
7732 p = list_first_entry(tasks, struct task_struct, se.group_node);
7733 list_del_init(&p->se.group_node);
7735 attach_task(env->dst_rq, p);
7738 raw_spin_unlock(&env->dst_rq->lock);
7741 #ifdef CONFIG_FAIR_GROUP_SCHED
7742 static void update_blocked_averages(int cpu)
7744 struct rq *rq = cpu_rq(cpu);
7745 struct cfs_rq *cfs_rq;
7746 unsigned long flags;
7748 raw_spin_lock_irqsave(&rq->lock, flags);
7749 update_rq_clock(rq);
7752 * Iterates the task_group tree in a bottom up fashion, see
7753 * list_add_leaf_cfs_rq() for details.
7755 for_each_leaf_cfs_rq(rq, cfs_rq) {
7756 /* throttled entities do not contribute to load */
7757 if (throttled_hierarchy(cfs_rq))
7760 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq,
7762 update_tg_load_avg(cfs_rq, 0);
7764 /* Propagate pending load changes to the parent */
7765 if (cfs_rq->tg->se[cpu])
7766 update_load_avg(cfs_rq->tg->se[cpu], 0);
7768 raw_spin_unlock_irqrestore(&rq->lock, flags);
7772 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
7773 * This needs to be done in a top-down fashion because the load of a child
7774 * group is a fraction of its parents load.
7776 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
7778 struct rq *rq = rq_of(cfs_rq);
7779 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
7780 unsigned long now = jiffies;
7783 if (cfs_rq->last_h_load_update == now)
7786 cfs_rq->h_load_next = NULL;
7787 for_each_sched_entity(se) {
7788 cfs_rq = cfs_rq_of(se);
7789 cfs_rq->h_load_next = se;
7790 if (cfs_rq->last_h_load_update == now)
7795 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
7796 cfs_rq->last_h_load_update = now;
7799 while ((se = cfs_rq->h_load_next) != NULL) {
7800 load = cfs_rq->h_load;
7801 load = div64_ul(load * se->avg.load_avg,
7802 cfs_rq_load_avg(cfs_rq) + 1);
7803 cfs_rq = group_cfs_rq(se);
7804 cfs_rq->h_load = load;
7805 cfs_rq->last_h_load_update = now;
7809 static unsigned long task_h_load(struct task_struct *p)
7811 struct cfs_rq *cfs_rq = task_cfs_rq(p);
7813 update_cfs_rq_h_load(cfs_rq);
7814 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
7815 cfs_rq_load_avg(cfs_rq) + 1);
7818 static inline void update_blocked_averages(int cpu)
7820 struct rq *rq = cpu_rq(cpu);
7821 struct cfs_rq *cfs_rq = &rq->cfs;
7822 unsigned long flags;
7824 raw_spin_lock_irqsave(&rq->lock, flags);
7825 update_rq_clock(rq);
7826 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true);
7827 raw_spin_unlock_irqrestore(&rq->lock, flags);
7830 static unsigned long task_h_load(struct task_struct *p)
7832 return p->se.avg.load_avg;
7836 /********** Helpers for find_busiest_group ************************/
7839 * sg_lb_stats - stats of a sched_group required for load_balancing
7841 struct sg_lb_stats {
7842 unsigned long avg_load; /*Avg load across the CPUs of the group */
7843 unsigned long group_load; /* Total load over the CPUs of the group */
7844 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
7845 unsigned long load_per_task;
7846 unsigned long group_capacity;
7847 unsigned long group_util; /* Total utilization of the group */
7848 unsigned int sum_nr_running; /* Nr tasks running in the group */
7849 unsigned int idle_cpus;
7850 unsigned int group_weight;
7851 enum group_type group_type;
7852 int group_no_capacity;
7853 int group_misfit_task; /* A cpu has a task too big for its capacity */
7854 #ifdef CONFIG_NUMA_BALANCING
7855 unsigned int nr_numa_running;
7856 unsigned int nr_preferred_running;
7861 * sd_lb_stats - Structure to store the statistics of a sched_domain
7862 * during load balancing.
7864 struct sd_lb_stats {
7865 struct sched_group *busiest; /* Busiest group in this sd */
7866 struct sched_group *local; /* Local group in this sd */
7867 unsigned long total_load; /* Total load of all groups in sd */
7868 unsigned long total_capacity; /* Total capacity of all groups in sd */
7869 unsigned long avg_load; /* Average load across all groups in sd */
7871 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
7872 struct sg_lb_stats local_stat; /* Statistics of the local group */
7875 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
7878 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
7879 * local_stat because update_sg_lb_stats() does a full clear/assignment.
7880 * We must however clear busiest_stat::avg_load because
7881 * update_sd_pick_busiest() reads this before assignment.
7883 *sds = (struct sd_lb_stats){
7887 .total_capacity = 0UL,
7890 .sum_nr_running = 0,
7891 .group_type = group_other,
7897 * get_sd_load_idx - Obtain the load index for a given sched domain.
7898 * @sd: The sched_domain whose load_idx is to be obtained.
7899 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
7901 * Return: The load index.
7903 static inline int get_sd_load_idx(struct sched_domain *sd,
7904 enum cpu_idle_type idle)
7910 load_idx = sd->busy_idx;
7913 case CPU_NEWLY_IDLE:
7914 load_idx = sd->newidle_idx;
7917 load_idx = sd->idle_idx;
7924 static unsigned long scale_rt_capacity(int cpu)
7926 struct rq *rq = cpu_rq(cpu);
7927 u64 total, used, age_stamp, avg;
7931 * Since we're reading these variables without serialization make sure
7932 * we read them once before doing sanity checks on them.
7934 age_stamp = READ_ONCE(rq->age_stamp);
7935 avg = READ_ONCE(rq->rt_avg);
7936 delta = __rq_clock_broken(rq) - age_stamp;
7938 if (unlikely(delta < 0))
7941 total = sched_avg_period() + delta;
7943 used = div_u64(avg, total);
7946 * deadline bandwidth is defined at system level so we must
7947 * weight this bandwidth with the max capacity of the system.
7948 * As a reminder, avg_bw is 20bits width and
7949 * scale_cpu_capacity is 10 bits width
7951 used += div_u64(rq->dl.avg_bw, arch_scale_cpu_capacity(NULL, cpu));
7953 if (likely(used < SCHED_CAPACITY_SCALE))
7954 return SCHED_CAPACITY_SCALE - used;
7959 void init_max_cpu_capacity(struct max_cpu_capacity *mcc)
7961 raw_spin_lock_init(&mcc->lock);
7966 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
7968 unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
7969 struct sched_group *sdg = sd->groups;
7970 struct max_cpu_capacity *mcc;
7971 unsigned long max_capacity;
7973 unsigned long flags;
7975 cpu_rq(cpu)->cpu_capacity_orig = capacity;
7977 mcc = &cpu_rq(cpu)->rd->max_cpu_capacity;
7979 raw_spin_lock_irqsave(&mcc->lock, flags);
7980 max_capacity = mcc->val;
7981 max_cap_cpu = mcc->cpu;
7983 if ((max_capacity > capacity && max_cap_cpu == cpu) ||
7984 (max_capacity < capacity)) {
7985 mcc->val = capacity;
7987 #ifdef CONFIG_SCHED_DEBUG
7988 raw_spin_unlock_irqrestore(&mcc->lock, flags);
7989 printk_deferred(KERN_INFO "CPU%d: update max cpu_capacity %lu\n",
7994 raw_spin_unlock_irqrestore(&mcc->lock, flags);
7996 skip_unlock: __attribute__ ((unused));
7997 capacity *= scale_rt_capacity(cpu);
7998 capacity >>= SCHED_CAPACITY_SHIFT;
8003 cpu_rq(cpu)->cpu_capacity = capacity;
8004 sdg->sgc->capacity = capacity;
8005 sdg->sgc->max_capacity = capacity;
8006 sdg->sgc->min_capacity = capacity;
8009 void update_group_capacity(struct sched_domain *sd, int cpu)
8011 struct sched_domain *child = sd->child;
8012 struct sched_group *group, *sdg = sd->groups;
8013 unsigned long capacity, max_capacity, min_capacity;
8014 unsigned long interval;
8016 interval = msecs_to_jiffies(sd->balance_interval);
8017 interval = clamp(interval, 1UL, max_load_balance_interval);
8018 sdg->sgc->next_update = jiffies + interval;
8021 update_cpu_capacity(sd, cpu);
8027 min_capacity = ULONG_MAX;
8029 if (child->flags & SD_OVERLAP) {
8031 * SD_OVERLAP domains cannot assume that child groups
8032 * span the current group.
8035 for_each_cpu(cpu, sched_group_cpus(sdg)) {
8036 struct sched_group_capacity *sgc;
8037 struct rq *rq = cpu_rq(cpu);
8040 * build_sched_domains() -> init_sched_groups_capacity()
8041 * gets here before we've attached the domains to the
8044 * Use capacity_of(), which is set irrespective of domains
8045 * in update_cpu_capacity().
8047 * This avoids capacity from being 0 and
8048 * causing divide-by-zero issues on boot.
8050 if (unlikely(!rq->sd)) {
8051 capacity += capacity_of(cpu);
8053 sgc = rq->sd->groups->sgc;
8054 capacity += sgc->capacity;
8057 max_capacity = max(capacity, max_capacity);
8058 min_capacity = min(capacity, min_capacity);
8062 * !SD_OVERLAP domains can assume that child groups
8063 * span the current group.
8066 group = child->groups;
8068 struct sched_group_capacity *sgc = group->sgc;
8070 capacity += sgc->capacity;
8071 max_capacity = max(sgc->max_capacity, max_capacity);
8072 min_capacity = min(sgc->min_capacity, min_capacity);
8073 group = group->next;
8074 } while (group != child->groups);
8077 sdg->sgc->capacity = capacity;
8078 sdg->sgc->max_capacity = max_capacity;
8079 sdg->sgc->min_capacity = min_capacity;
8083 * Check whether the capacity of the rq has been noticeably reduced by side
8084 * activity. The imbalance_pct is used for the threshold.
8085 * Return true is the capacity is reduced
8088 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
8090 return ((rq->cpu_capacity * sd->imbalance_pct) <
8091 (rq->cpu_capacity_orig * 100));
8095 * Group imbalance indicates (and tries to solve) the problem where balancing
8096 * groups is inadequate due to tsk_cpus_allowed() constraints.
8098 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
8099 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
8102 * { 0 1 2 3 } { 4 5 6 7 }
8105 * If we were to balance group-wise we'd place two tasks in the first group and
8106 * two tasks in the second group. Clearly this is undesired as it will overload
8107 * cpu 3 and leave one of the cpus in the second group unused.
8109 * The current solution to this issue is detecting the skew in the first group
8110 * by noticing the lower domain failed to reach balance and had difficulty
8111 * moving tasks due to affinity constraints.
8113 * When this is so detected; this group becomes a candidate for busiest; see
8114 * update_sd_pick_busiest(). And calculate_imbalance() and
8115 * find_busiest_group() avoid some of the usual balance conditions to allow it
8116 * to create an effective group imbalance.
8118 * This is a somewhat tricky proposition since the next run might not find the
8119 * group imbalance and decide the groups need to be balanced again. A most
8120 * subtle and fragile situation.
8123 static inline int sg_imbalanced(struct sched_group *group)
8125 return group->sgc->imbalance;
8129 * group_has_capacity returns true if the group has spare capacity that could
8130 * be used by some tasks.
8131 * We consider that a group has spare capacity if the * number of task is
8132 * smaller than the number of CPUs or if the utilization is lower than the
8133 * available capacity for CFS tasks.
8134 * For the latter, we use a threshold to stabilize the state, to take into
8135 * account the variance of the tasks' load and to return true if the available
8136 * capacity in meaningful for the load balancer.
8137 * As an example, an available capacity of 1% can appear but it doesn't make
8138 * any benefit for the load balance.
8141 group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
8143 if (sgs->sum_nr_running < sgs->group_weight)
8146 if ((sgs->group_capacity * 100) >
8147 (sgs->group_util * env->sd->imbalance_pct))
8154 * group_is_overloaded returns true if the group has more tasks than it can
8156 * group_is_overloaded is not equals to !group_has_capacity because a group
8157 * with the exact right number of tasks, has no more spare capacity but is not
8158 * overloaded so both group_has_capacity and group_is_overloaded return
8162 group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
8164 if (sgs->sum_nr_running <= sgs->group_weight)
8167 if ((sgs->group_capacity * 100) <
8168 (sgs->group_util * env->sd->imbalance_pct))
8176 * group_smaller_cpu_capacity: Returns true if sched_group sg has smaller
8177 * per-cpu capacity than sched_group ref.
8180 group_smaller_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8182 return sg->sgc->max_capacity + capacity_margin - SCHED_LOAD_SCALE <
8183 ref->sgc->max_capacity;
8187 group_type group_classify(struct sched_group *group,
8188 struct sg_lb_stats *sgs)
8190 if (sgs->group_no_capacity)
8191 return group_overloaded;
8193 if (sg_imbalanced(group))
8194 return group_imbalanced;
8196 if (sgs->group_misfit_task)
8197 return group_misfit_task;
8202 #ifdef CONFIG_NO_HZ_COMMON
8204 * idle load balancing data
8205 * - used by the nohz balance, but we want it available here
8206 * so that we can see which CPUs have no tick.
8209 cpumask_var_t idle_cpus_mask;
8211 unsigned long next_balance; /* in jiffy units */
8212 } nohz ____cacheline_aligned;
8214 static inline void update_cpu_stats_if_tickless(struct rq *rq)
8216 /* only called from update_sg_lb_stats when irqs are disabled */
8217 if (cpumask_test_cpu(rq->cpu, nohz.idle_cpus_mask)) {
8218 /* rate limit updates to once-per-jiffie at most */
8219 if (READ_ONCE(jiffies) <= rq->last_load_update_tick)
8222 raw_spin_lock(&rq->lock);
8223 update_rq_clock(rq);
8224 update_idle_cpu_load(rq);
8225 update_cfs_rq_load_avg(rq->clock_task, &rq->cfs, false);
8226 raw_spin_unlock(&rq->lock);
8231 static inline void update_cpu_stats_if_tickless(struct rq *rq) { }
8235 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
8236 * @env: The load balancing environment.
8237 * @group: sched_group whose statistics are to be updated.
8238 * @load_idx: Load index of sched_domain of this_cpu for load calc.
8239 * @local_group: Does group contain this_cpu.
8240 * @sgs: variable to hold the statistics for this group.
8241 * @overload: Indicate more than one runnable task for any CPU.
8242 * @overutilized: Indicate overutilization for any CPU.
8244 static inline void update_sg_lb_stats(struct lb_env *env,
8245 struct sched_group *group, int load_idx,
8246 int local_group, struct sg_lb_stats *sgs,
8247 bool *overload, bool *overutilized)
8252 memset(sgs, 0, sizeof(*sgs));
8254 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
8255 struct rq *rq = cpu_rq(i);
8257 /* if we are entering idle and there are CPUs with
8258 * their tick stopped, do an update for them
8260 if (env->idle == CPU_NEWLY_IDLE)
8261 update_cpu_stats_if_tickless(rq);
8263 /* Bias balancing toward cpus of our domain */
8265 load = target_load(i, load_idx);
8267 load = source_load(i, load_idx);
8269 sgs->group_load += load;
8270 sgs->group_util += cpu_util(i);
8271 sgs->sum_nr_running += rq->cfs.h_nr_running;
8273 nr_running = rq->nr_running;
8277 #ifdef CONFIG_NUMA_BALANCING
8278 sgs->nr_numa_running += rq->nr_numa_running;
8279 sgs->nr_preferred_running += rq->nr_preferred_running;
8281 sgs->sum_weighted_load += weighted_cpuload(i);
8283 * No need to call idle_cpu() if nr_running is not 0
8285 if (!nr_running && idle_cpu(i))
8288 if (cpu_overutilized(i)) {
8289 *overutilized = true;
8290 if (!sgs->group_misfit_task && rq->misfit_task)
8291 sgs->group_misfit_task = capacity_of(i);
8295 /* Adjust by relative CPU capacity of the group */
8296 sgs->group_capacity = group->sgc->capacity;
8297 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
8299 if (sgs->sum_nr_running)
8300 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
8302 sgs->group_weight = group->group_weight;
8304 sgs->group_no_capacity = group_is_overloaded(env, sgs);
8305 sgs->group_type = group_classify(group, sgs);
8309 * update_sd_pick_busiest - return 1 on busiest group
8310 * @env: The load balancing environment.
8311 * @sds: sched_domain statistics
8312 * @sg: sched_group candidate to be checked for being the busiest
8313 * @sgs: sched_group statistics
8315 * Determine if @sg is a busier group than the previously selected
8318 * Return: %true if @sg is a busier group than the previously selected
8319 * busiest group. %false otherwise.
8321 static bool update_sd_pick_busiest(struct lb_env *env,
8322 struct sd_lb_stats *sds,
8323 struct sched_group *sg,
8324 struct sg_lb_stats *sgs)
8326 struct sg_lb_stats *busiest = &sds->busiest_stat;
8328 if (sgs->group_type > busiest->group_type)
8331 if (sgs->group_type < busiest->group_type)
8335 * Candidate sg doesn't face any serious load-balance problems
8336 * so don't pick it if the local sg is already filled up.
8338 if (sgs->group_type == group_other &&
8339 !group_has_capacity(env, &sds->local_stat))
8342 if (sgs->avg_load <= busiest->avg_load)
8345 if (!(env->sd->flags & SD_ASYM_CPUCAPACITY))
8349 * Candidate sg has no more than one task per CPU and
8350 * has higher per-CPU capacity. Migrating tasks to less
8351 * capable CPUs may harm throughput. Maximize throughput,
8352 * power/energy consequences are not considered.
8354 if (sgs->sum_nr_running <= sgs->group_weight &&
8355 group_smaller_cpu_capacity(sds->local, sg))
8359 /* This is the busiest node in its class. */
8360 if (!(env->sd->flags & SD_ASYM_PACKING))
8364 * ASYM_PACKING needs to move all the work to the lowest
8365 * numbered CPUs in the group, therefore mark all groups
8366 * higher than ourself as busy.
8368 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
8372 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
8379 #ifdef CONFIG_NUMA_BALANCING
8380 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8382 if (sgs->sum_nr_running > sgs->nr_numa_running)
8384 if (sgs->sum_nr_running > sgs->nr_preferred_running)
8389 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8391 if (rq->nr_running > rq->nr_numa_running)
8393 if (rq->nr_running > rq->nr_preferred_running)
8398 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
8403 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
8407 #endif /* CONFIG_NUMA_BALANCING */
8409 #define lb_sd_parent(sd) \
8410 (sd->parent && sd->parent->groups != sd->parent->groups->next)
8413 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
8414 * @env: The load balancing environment.
8415 * @sds: variable to hold the statistics for this sched_domain.
8417 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
8419 struct sched_domain *child = env->sd->child;
8420 struct sched_group *sg = env->sd->groups;
8421 struct sg_lb_stats tmp_sgs;
8422 int load_idx, prefer_sibling = 0;
8423 bool overload = false, overutilized = false;
8425 if (child && child->flags & SD_PREFER_SIBLING)
8428 load_idx = get_sd_load_idx(env->sd, env->idle);
8431 struct sg_lb_stats *sgs = &tmp_sgs;
8434 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
8437 sgs = &sds->local_stat;
8439 if (env->idle != CPU_NEWLY_IDLE ||
8440 time_after_eq(jiffies, sg->sgc->next_update))
8441 update_group_capacity(env->sd, env->dst_cpu);
8444 update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
8445 &overload, &overutilized);
8451 * In case the child domain prefers tasks go to siblings
8452 * first, lower the sg capacity so that we'll try
8453 * and move all the excess tasks away. We lower the capacity
8454 * of a group only if the local group has the capacity to fit
8455 * these excess tasks. The extra check prevents the case where
8456 * you always pull from the heaviest group when it is already
8457 * under-utilized (possible with a large weight task outweighs
8458 * the tasks on the system).
8460 if (prefer_sibling && sds->local &&
8461 group_has_capacity(env, &sds->local_stat) &&
8462 (sgs->sum_nr_running > 1)) {
8463 sgs->group_no_capacity = 1;
8464 sgs->group_type = group_classify(sg, sgs);
8468 * Ignore task groups with misfit tasks if local group has no
8469 * capacity or if per-cpu capacity isn't higher.
8471 if (sgs->group_type == group_misfit_task &&
8472 (!group_has_capacity(env, &sds->local_stat) ||
8473 !group_smaller_cpu_capacity(sg, sds->local)))
8474 sgs->group_type = group_other;
8476 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
8478 sds->busiest_stat = *sgs;
8482 /* Now, start updating sd_lb_stats */
8483 sds->total_load += sgs->group_load;
8484 sds->total_capacity += sgs->group_capacity;
8487 } while (sg != env->sd->groups);
8489 if (env->sd->flags & SD_NUMA)
8490 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
8492 env->src_grp_nr_running = sds->busiest_stat.sum_nr_running;
8494 if (!lb_sd_parent(env->sd)) {
8495 /* update overload indicator if we are at root domain */
8496 if (env->dst_rq->rd->overload != overload)
8497 env->dst_rq->rd->overload = overload;
8499 /* Update over-utilization (tipping point, U >= 0) indicator */
8500 if (env->dst_rq->rd->overutilized != overutilized) {
8501 env->dst_rq->rd->overutilized = overutilized;
8502 trace_sched_overutilized(overutilized);
8505 if (!env->dst_rq->rd->overutilized && overutilized) {
8506 env->dst_rq->rd->overutilized = true;
8507 trace_sched_overutilized(true);
8514 * check_asym_packing - Check to see if the group is packed into the
8517 * This is primarily intended to used at the sibling level. Some
8518 * cores like POWER7 prefer to use lower numbered SMT threads. In the
8519 * case of POWER7, it can move to lower SMT modes only when higher
8520 * threads are idle. When in lower SMT modes, the threads will
8521 * perform better since they share less core resources. Hence when we
8522 * have idle threads, we want them to be the higher ones.
8524 * This packing function is run on idle threads. It checks to see if
8525 * the busiest CPU in this domain (core in the P7 case) has a higher
8526 * CPU number than the packing function is being run on. Here we are
8527 * assuming lower CPU number will be equivalent to lower a SMT thread
8530 * Return: 1 when packing is required and a task should be moved to
8531 * this CPU. The amount of the imbalance is returned in *imbalance.
8533 * @env: The load balancing environment.
8534 * @sds: Statistics of the sched_domain which is to be packed
8536 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
8540 if (!(env->sd->flags & SD_ASYM_PACKING))
8546 busiest_cpu = group_first_cpu(sds->busiest);
8547 if (env->dst_cpu > busiest_cpu)
8550 env->imbalance = DIV_ROUND_CLOSEST(
8551 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
8552 SCHED_CAPACITY_SCALE);
8558 * fix_small_imbalance - Calculate the minor imbalance that exists
8559 * amongst the groups of a sched_domain, during
8561 * @env: The load balancing environment.
8562 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
8565 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
8567 unsigned long tmp, capa_now = 0, capa_move = 0;
8568 unsigned int imbn = 2;
8569 unsigned long scaled_busy_load_per_task;
8570 struct sg_lb_stats *local, *busiest;
8572 local = &sds->local_stat;
8573 busiest = &sds->busiest_stat;
8575 if (!local->sum_nr_running)
8576 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
8577 else if (busiest->load_per_task > local->load_per_task)
8580 scaled_busy_load_per_task =
8581 (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
8582 busiest->group_capacity;
8584 if (busiest->avg_load + scaled_busy_load_per_task >=
8585 local->avg_load + (scaled_busy_load_per_task * imbn)) {
8586 env->imbalance = busiest->load_per_task;
8591 * OK, we don't have enough imbalance to justify moving tasks,
8592 * however we may be able to increase total CPU capacity used by
8596 capa_now += busiest->group_capacity *
8597 min(busiest->load_per_task, busiest->avg_load);
8598 capa_now += local->group_capacity *
8599 min(local->load_per_task, local->avg_load);
8600 capa_now /= SCHED_CAPACITY_SCALE;
8602 /* Amount of load we'd subtract */
8603 if (busiest->avg_load > scaled_busy_load_per_task) {
8604 capa_move += busiest->group_capacity *
8605 min(busiest->load_per_task,
8606 busiest->avg_load - scaled_busy_load_per_task);
8609 /* Amount of load we'd add */
8610 if (busiest->avg_load * busiest->group_capacity <
8611 busiest->load_per_task * SCHED_CAPACITY_SCALE) {
8612 tmp = (busiest->avg_load * busiest->group_capacity) /
8613 local->group_capacity;
8615 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
8616 local->group_capacity;
8618 capa_move += local->group_capacity *
8619 min(local->load_per_task, local->avg_load + tmp);
8620 capa_move /= SCHED_CAPACITY_SCALE;
8622 /* Move if we gain throughput */
8623 if (capa_move > capa_now)
8624 env->imbalance = busiest->load_per_task;
8628 * calculate_imbalance - Calculate the amount of imbalance present within the
8629 * groups of a given sched_domain during load balance.
8630 * @env: load balance environment
8631 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
8633 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
8635 unsigned long max_pull, load_above_capacity = ~0UL;
8636 struct sg_lb_stats *local, *busiest;
8638 local = &sds->local_stat;
8639 busiest = &sds->busiest_stat;
8641 if (busiest->group_type == group_imbalanced) {
8643 * In the group_imb case we cannot rely on group-wide averages
8644 * to ensure cpu-load equilibrium, look at wider averages. XXX
8646 busiest->load_per_task =
8647 min(busiest->load_per_task, sds->avg_load);
8651 * In the presence of smp nice balancing, certain scenarios can have
8652 * max load less than avg load(as we skip the groups at or below
8653 * its cpu_capacity, while calculating max_load..)
8655 if (busiest->avg_load <= sds->avg_load ||
8656 local->avg_load >= sds->avg_load) {
8657 /* Misfitting tasks should be migrated in any case */
8658 if (busiest->group_type == group_misfit_task) {
8659 env->imbalance = busiest->group_misfit_task;
8664 * Busiest group is overloaded, local is not, use the spare
8665 * cycles to maximize throughput
8667 if (busiest->group_type == group_overloaded &&
8668 local->group_type <= group_misfit_task) {
8669 env->imbalance = busiest->load_per_task;
8674 return fix_small_imbalance(env, sds);
8678 * If there aren't any idle cpus, avoid creating some.
8680 if (busiest->group_type == group_overloaded &&
8681 local->group_type == group_overloaded) {
8682 load_above_capacity = busiest->sum_nr_running *
8684 if (load_above_capacity > busiest->group_capacity)
8685 load_above_capacity -= busiest->group_capacity;
8687 load_above_capacity = ~0UL;
8691 * We're trying to get all the cpus to the average_load, so we don't
8692 * want to push ourselves above the average load, nor do we wish to
8693 * reduce the max loaded cpu below the average load. At the same time,
8694 * we also don't want to reduce the group load below the group capacity
8695 * (so that we can implement power-savings policies etc). Thus we look
8696 * for the minimum possible imbalance.
8698 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
8700 /* How much load to actually move to equalise the imbalance */
8701 env->imbalance = min(
8702 max_pull * busiest->group_capacity,
8703 (sds->avg_load - local->avg_load) * local->group_capacity
8704 ) / SCHED_CAPACITY_SCALE;
8706 /* Boost imbalance to allow misfit task to be balanced. */
8707 if (busiest->group_type == group_misfit_task)
8708 env->imbalance = max_t(long, env->imbalance,
8709 busiest->group_misfit_task);
8712 * if *imbalance is less than the average load per runnable task
8713 * there is no guarantee that any tasks will be moved so we'll have
8714 * a think about bumping its value to force at least one task to be
8717 if (env->imbalance < busiest->load_per_task)
8718 return fix_small_imbalance(env, sds);
8721 /******* find_busiest_group() helpers end here *********************/
8724 * find_busiest_group - Returns the busiest group within the sched_domain
8725 * if there is an imbalance. If there isn't an imbalance, and
8726 * the user has opted for power-savings, it returns a group whose
8727 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
8728 * such a group exists.
8730 * Also calculates the amount of weighted load which should be moved
8731 * to restore balance.
8733 * @env: The load balancing environment.
8735 * Return: - The busiest group if imbalance exists.
8736 * - If no imbalance and user has opted for power-savings balance,
8737 * return the least loaded group whose CPUs can be
8738 * put to idle by rebalancing its tasks onto our group.
8740 static struct sched_group *find_busiest_group(struct lb_env *env)
8742 struct sg_lb_stats *local, *busiest;
8743 struct sd_lb_stats sds;
8745 init_sd_lb_stats(&sds);
8748 * Compute the various statistics relavent for load balancing at
8751 update_sd_lb_stats(env, &sds);
8753 if (energy_aware() && !env->dst_rq->rd->overutilized)
8756 local = &sds.local_stat;
8757 busiest = &sds.busiest_stat;
8759 /* ASYM feature bypasses nice load balance check */
8760 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
8761 check_asym_packing(env, &sds))
8764 /* There is no busy sibling group to pull tasks from */
8765 if (!sds.busiest || busiest->sum_nr_running == 0)
8768 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
8769 / sds.total_capacity;
8772 * If the busiest group is imbalanced the below checks don't
8773 * work because they assume all things are equal, which typically
8774 * isn't true due to cpus_allowed constraints and the like.
8776 if (busiest->group_type == group_imbalanced)
8780 * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
8781 * capacities from resulting in underutilization due to avg_load.
8783 if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
8784 busiest->group_no_capacity)
8787 /* Misfitting tasks should be dealt with regardless of the avg load */
8788 if (busiest->group_type == group_misfit_task) {
8793 * If the local group is busier than the selected busiest group
8794 * don't try and pull any tasks.
8796 if (local->avg_load >= busiest->avg_load)
8800 * Don't pull any tasks if this group is already above the domain
8803 if (local->avg_load >= sds.avg_load)
8806 if (env->idle == CPU_IDLE) {
8808 * This cpu is idle. If the busiest group is not overloaded
8809 * and there is no imbalance between this and busiest group
8810 * wrt idle cpus, it is balanced. The imbalance becomes
8811 * significant if the diff is greater than 1 otherwise we
8812 * might end up to just move the imbalance on another group
8814 if ((busiest->group_type != group_overloaded) &&
8815 (local->idle_cpus <= (busiest->idle_cpus + 1)) &&
8816 !group_smaller_cpu_capacity(sds.busiest, sds.local))
8820 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
8821 * imbalance_pct to be conservative.
8823 if (100 * busiest->avg_load <=
8824 env->sd->imbalance_pct * local->avg_load)
8829 env->busiest_group_type = busiest->group_type;
8830 /* Looks like there is an imbalance. Compute it */
8831 calculate_imbalance(env, &sds);
8840 * find_busiest_queue - find the busiest runqueue among the cpus in group.
8842 static struct rq *find_busiest_queue(struct lb_env *env,
8843 struct sched_group *group)
8845 struct rq *busiest = NULL, *rq;
8846 unsigned long busiest_load = 0, busiest_capacity = 1;
8849 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
8850 unsigned long capacity, wl;
8854 rt = fbq_classify_rq(rq);
8857 * We classify groups/runqueues into three groups:
8858 * - regular: there are !numa tasks
8859 * - remote: there are numa tasks that run on the 'wrong' node
8860 * - all: there is no distinction
8862 * In order to avoid migrating ideally placed numa tasks,
8863 * ignore those when there's better options.
8865 * If we ignore the actual busiest queue to migrate another
8866 * task, the next balance pass can still reduce the busiest
8867 * queue by moving tasks around inside the node.
8869 * If we cannot move enough load due to this classification
8870 * the next pass will adjust the group classification and
8871 * allow migration of more tasks.
8873 * Both cases only affect the total convergence complexity.
8875 if (rt > env->fbq_type)
8878 capacity = capacity_of(i);
8880 wl = weighted_cpuload(i);
8883 * When comparing with imbalance, use weighted_cpuload()
8884 * which is not scaled with the cpu capacity.
8887 if (rq->nr_running == 1 && wl > env->imbalance &&
8888 !check_cpu_capacity(rq, env->sd) &&
8889 env->busiest_group_type != group_misfit_task)
8893 * For the load comparisons with the other cpu's, consider
8894 * the weighted_cpuload() scaled with the cpu capacity, so
8895 * that the load can be moved away from the cpu that is
8896 * potentially running at a lower capacity.
8898 * Thus we're looking for max(wl_i / capacity_i), crosswise
8899 * multiplication to rid ourselves of the division works out
8900 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
8901 * our previous maximum.
8903 if (wl * busiest_capacity > busiest_load * capacity) {
8905 busiest_capacity = capacity;
8914 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
8915 * so long as it is large enough.
8917 #define MAX_PINNED_INTERVAL 512
8919 /* Working cpumask for load_balance and load_balance_newidle. */
8920 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
8922 static int need_active_balance(struct lb_env *env)
8924 struct sched_domain *sd = env->sd;
8926 if (env->idle == CPU_NEWLY_IDLE) {
8929 * ASYM_PACKING needs to force migrate tasks from busy but
8930 * higher numbered CPUs in order to pack all tasks in the
8931 * lowest numbered CPUs.
8933 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
8938 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
8939 * It's worth migrating the task if the src_cpu's capacity is reduced
8940 * because of other sched_class or IRQs if more capacity stays
8941 * available on dst_cpu.
8943 if ((env->idle != CPU_NOT_IDLE) &&
8944 (env->src_rq->cfs.h_nr_running == 1)) {
8945 if ((check_cpu_capacity(env->src_rq, sd)) &&
8946 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
8950 if ((capacity_of(env->src_cpu) < capacity_of(env->dst_cpu)) &&
8951 ((capacity_orig_of(env->src_cpu) < capacity_orig_of(env->dst_cpu))) &&
8952 env->src_rq->cfs.h_nr_running == 1 &&
8953 cpu_overutilized(env->src_cpu) &&
8954 !cpu_overutilized(env->dst_cpu)) {
8958 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
8961 static int active_load_balance_cpu_stop(void *data);
8963 static int should_we_balance(struct lb_env *env)
8965 struct sched_group *sg = env->sd->groups;
8966 struct cpumask *sg_cpus, *sg_mask;
8967 int cpu, balance_cpu = -1;
8970 * In the newly idle case, we will allow all the cpu's
8971 * to do the newly idle load balance.
8973 if (env->idle == CPU_NEWLY_IDLE)
8976 sg_cpus = sched_group_cpus(sg);
8977 sg_mask = sched_group_mask(sg);
8978 /* Try to find first idle cpu */
8979 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
8980 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
8987 if (balance_cpu == -1)
8988 balance_cpu = group_balance_cpu(sg);
8991 * First idle cpu or the first cpu(busiest) in this sched group
8992 * is eligible for doing load balancing at this and above domains.
8994 return balance_cpu == env->dst_cpu;
8998 * Check this_cpu to ensure it is balanced within domain. Attempt to move
8999 * tasks if there is an imbalance.
9001 static int load_balance(int this_cpu, struct rq *this_rq,
9002 struct sched_domain *sd, enum cpu_idle_type idle,
9003 int *continue_balancing)
9005 int ld_moved, cur_ld_moved, active_balance = 0;
9006 struct sched_domain *sd_parent = lb_sd_parent(sd) ? sd->parent : NULL;
9007 struct sched_group *group;
9009 unsigned long flags;
9010 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
9012 struct lb_env env = {
9014 .dst_cpu = this_cpu,
9016 .dst_grpmask = sched_group_cpus(sd->groups),
9018 .loop_break = sched_nr_migrate_break,
9021 .tasks = LIST_HEAD_INIT(env.tasks),
9025 * For NEWLY_IDLE load_balancing, we don't need to consider
9026 * other cpus in our group
9028 if (idle == CPU_NEWLY_IDLE)
9029 env.dst_grpmask = NULL;
9031 cpumask_copy(cpus, cpu_active_mask);
9033 schedstat_inc(sd, lb_count[idle]);
9036 if (!should_we_balance(&env)) {
9037 *continue_balancing = 0;
9041 group = find_busiest_group(&env);
9043 schedstat_inc(sd, lb_nobusyg[idle]);
9047 busiest = find_busiest_queue(&env, group);
9049 schedstat_inc(sd, lb_nobusyq[idle]);
9053 BUG_ON(busiest == env.dst_rq);
9055 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
9057 env.src_cpu = busiest->cpu;
9058 env.src_rq = busiest;
9061 if (busiest->nr_running > 1) {
9063 * Attempt to move tasks. If find_busiest_group has found
9064 * an imbalance but busiest->nr_running <= 1, the group is
9065 * still unbalanced. ld_moved simply stays zero, so it is
9066 * correctly treated as an imbalance.
9068 env.flags |= LBF_ALL_PINNED;
9069 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
9072 raw_spin_lock_irqsave(&busiest->lock, flags);
9073 update_rq_clock(busiest);
9076 * cur_ld_moved - load moved in current iteration
9077 * ld_moved - cumulative load moved across iterations
9079 cur_ld_moved = detach_tasks(&env);
9082 * We've detached some tasks from busiest_rq. Every
9083 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9084 * unlock busiest->lock, and we are able to be sure
9085 * that nobody can manipulate the tasks in parallel.
9086 * See task_rq_lock() family for the details.
9089 raw_spin_unlock(&busiest->lock);
9093 ld_moved += cur_ld_moved;
9096 local_irq_restore(flags);
9098 if (env.flags & LBF_NEED_BREAK) {
9099 env.flags &= ~LBF_NEED_BREAK;
9104 * Revisit (affine) tasks on src_cpu that couldn't be moved to
9105 * us and move them to an alternate dst_cpu in our sched_group
9106 * where they can run. The upper limit on how many times we
9107 * iterate on same src_cpu is dependent on number of cpus in our
9110 * This changes load balance semantics a bit on who can move
9111 * load to a given_cpu. In addition to the given_cpu itself
9112 * (or a ilb_cpu acting on its behalf where given_cpu is
9113 * nohz-idle), we now have balance_cpu in a position to move
9114 * load to given_cpu. In rare situations, this may cause
9115 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
9116 * _independently_ and at _same_ time to move some load to
9117 * given_cpu) causing exceess load to be moved to given_cpu.
9118 * This however should not happen so much in practice and
9119 * moreover subsequent load balance cycles should correct the
9120 * excess load moved.
9122 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
9124 /* Prevent to re-select dst_cpu via env's cpus */
9125 cpumask_clear_cpu(env.dst_cpu, env.cpus);
9127 env.dst_rq = cpu_rq(env.new_dst_cpu);
9128 env.dst_cpu = env.new_dst_cpu;
9129 env.flags &= ~LBF_DST_PINNED;
9131 env.loop_break = sched_nr_migrate_break;
9134 * Go back to "more_balance" rather than "redo" since we
9135 * need to continue with same src_cpu.
9141 * We failed to reach balance because of affinity.
9144 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9146 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
9147 *group_imbalance = 1;
9150 /* All tasks on this runqueue were pinned by CPU affinity */
9151 if (unlikely(env.flags & LBF_ALL_PINNED)) {
9152 cpumask_clear_cpu(cpu_of(busiest), cpus);
9153 if (!cpumask_empty(cpus)) {
9155 env.loop_break = sched_nr_migrate_break;
9158 goto out_all_pinned;
9163 schedstat_inc(sd, lb_failed[idle]);
9165 * Increment the failure counter only on periodic balance.
9166 * We do not want newidle balance, which can be very
9167 * frequent, pollute the failure counter causing
9168 * excessive cache_hot migrations and active balances.
9170 if (idle != CPU_NEWLY_IDLE)
9171 if (env.src_grp_nr_running > 1)
9172 sd->nr_balance_failed++;
9174 if (need_active_balance(&env)) {
9175 raw_spin_lock_irqsave(&busiest->lock, flags);
9177 /* don't kick the active_load_balance_cpu_stop,
9178 * if the curr task on busiest cpu can't be
9181 if (!cpumask_test_cpu(this_cpu,
9182 tsk_cpus_allowed(busiest->curr))) {
9183 raw_spin_unlock_irqrestore(&busiest->lock,
9185 env.flags |= LBF_ALL_PINNED;
9186 goto out_one_pinned;
9190 * ->active_balance synchronizes accesses to
9191 * ->active_balance_work. Once set, it's cleared
9192 * only after active load balance is finished.
9194 if (!busiest->active_balance) {
9195 busiest->active_balance = 1;
9196 busiest->push_cpu = this_cpu;
9199 raw_spin_unlock_irqrestore(&busiest->lock, flags);
9201 if (active_balance) {
9202 stop_one_cpu_nowait(cpu_of(busiest),
9203 active_load_balance_cpu_stop, busiest,
9204 &busiest->active_balance_work);
9208 * We've kicked active balancing, reset the failure
9211 sd->nr_balance_failed = sd->cache_nice_tries+1;
9214 sd->nr_balance_failed = 0;
9216 if (likely(!active_balance)) {
9217 /* We were unbalanced, so reset the balancing interval */
9218 sd->balance_interval = sd->min_interval;
9221 * If we've begun active balancing, start to back off. This
9222 * case may not be covered by the all_pinned logic if there
9223 * is only 1 task on the busy runqueue (because we don't call
9226 if (sd->balance_interval < sd->max_interval)
9227 sd->balance_interval *= 2;
9234 * We reach balance although we may have faced some affinity
9235 * constraints. Clear the imbalance flag if it was set.
9238 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
9240 if (*group_imbalance)
9241 *group_imbalance = 0;
9246 * We reach balance because all tasks are pinned at this level so
9247 * we can't migrate them. Let the imbalance flag set so parent level
9248 * can try to migrate them.
9250 schedstat_inc(sd, lb_balanced[idle]);
9252 sd->nr_balance_failed = 0;
9255 /* tune up the balancing interval */
9256 if (((env.flags & LBF_ALL_PINNED) &&
9257 sd->balance_interval < MAX_PINNED_INTERVAL) ||
9258 (sd->balance_interval < sd->max_interval))
9259 sd->balance_interval *= 2;
9266 static inline unsigned long
9267 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
9269 unsigned long interval = sd->balance_interval;
9272 interval *= sd->busy_factor;
9274 /* scale ms to jiffies */
9275 interval = msecs_to_jiffies(interval);
9276 interval = clamp(interval, 1UL, max_load_balance_interval);
9282 update_next_balance(struct sched_domain *sd, int cpu_busy, unsigned long *next_balance)
9284 unsigned long interval, next;
9286 interval = get_sd_balance_interval(sd, cpu_busy);
9287 next = sd->last_balance + interval;
9289 if (time_after(*next_balance, next))
9290 *next_balance = next;
9294 * idle_balance is called by schedule() if this_cpu is about to become
9295 * idle. Attempts to pull tasks from other CPUs.
9297 static int idle_balance(struct rq *this_rq)
9299 unsigned long next_balance = jiffies + HZ;
9300 int this_cpu = this_rq->cpu;
9301 struct sched_domain *sd;
9302 int pulled_task = 0;
9305 idle_enter_fair(this_rq);
9308 * We must set idle_stamp _before_ calling idle_balance(), such that we
9309 * measure the duration of idle_balance() as idle time.
9311 this_rq->idle_stamp = rq_clock(this_rq);
9313 if (!energy_aware() &&
9314 (this_rq->avg_idle < sysctl_sched_migration_cost ||
9315 !this_rq->rd->overload)) {
9317 sd = rcu_dereference_check_sched_domain(this_rq->sd);
9319 update_next_balance(sd, 0, &next_balance);
9325 raw_spin_unlock(&this_rq->lock);
9327 update_blocked_averages(this_cpu);
9329 for_each_domain(this_cpu, sd) {
9330 int continue_balancing = 1;
9331 u64 t0, domain_cost;
9333 if (!(sd->flags & SD_LOAD_BALANCE))
9336 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
9337 update_next_balance(sd, 0, &next_balance);
9341 if (sd->flags & SD_BALANCE_NEWIDLE) {
9342 t0 = sched_clock_cpu(this_cpu);
9344 pulled_task = load_balance(this_cpu, this_rq,
9346 &continue_balancing);
9348 domain_cost = sched_clock_cpu(this_cpu) - t0;
9349 if (domain_cost > sd->max_newidle_lb_cost)
9350 sd->max_newidle_lb_cost = domain_cost;
9352 curr_cost += domain_cost;
9355 update_next_balance(sd, 0, &next_balance);
9358 * Stop searching for tasks to pull if there are
9359 * now runnable tasks on this rq.
9361 if (pulled_task || this_rq->nr_running > 0)
9366 raw_spin_lock(&this_rq->lock);
9368 if (curr_cost > this_rq->max_idle_balance_cost)
9369 this_rq->max_idle_balance_cost = curr_cost;
9372 * While browsing the domains, we released the rq lock, a task could
9373 * have been enqueued in the meantime. Since we're not going idle,
9374 * pretend we pulled a task.
9376 if (this_rq->cfs.h_nr_running && !pulled_task)
9380 /* Move the next balance forward */
9381 if (time_after(this_rq->next_balance, next_balance))
9382 this_rq->next_balance = next_balance;
9384 /* Is there a task of a high priority class? */
9385 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
9389 idle_exit_fair(this_rq);
9390 this_rq->idle_stamp = 0;
9397 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
9398 * running tasks off the busiest CPU onto idle CPUs. It requires at
9399 * least 1 task to be running on each physical CPU where possible, and
9400 * avoids physical / logical imbalances.
9402 static int active_load_balance_cpu_stop(void *data)
9404 struct rq *busiest_rq = data;
9405 int busiest_cpu = cpu_of(busiest_rq);
9406 int target_cpu = busiest_rq->push_cpu;
9407 struct rq *target_rq = cpu_rq(target_cpu);
9408 struct sched_domain *sd = NULL;
9409 struct task_struct *p = NULL;
9410 struct task_struct *push_task = NULL;
9411 int push_task_detached = 0;
9412 struct lb_env env = {
9414 .dst_cpu = target_cpu,
9415 .dst_rq = target_rq,
9416 .src_cpu = busiest_rq->cpu,
9417 .src_rq = busiest_rq,
9421 raw_spin_lock_irq(&busiest_rq->lock);
9423 /* make sure the requested cpu hasn't gone down in the meantime */
9424 if (unlikely(busiest_cpu != smp_processor_id() ||
9425 !busiest_rq->active_balance))
9428 /* Is there any task to move? */
9429 if (busiest_rq->nr_running <= 1)
9433 * This condition is "impossible", if it occurs
9434 * we need to fix it. Originally reported by
9435 * Bjorn Helgaas on a 128-cpu setup.
9437 BUG_ON(busiest_rq == target_rq);
9439 push_task = busiest_rq->push_task;
9441 if (task_on_rq_queued(push_task) &&
9442 task_cpu(push_task) == busiest_cpu &&
9443 cpu_online(target_cpu)) {
9444 detach_task(push_task, &env);
9445 push_task_detached = 1;
9450 /* Search for an sd spanning us and the target CPU. */
9452 for_each_domain(target_cpu, sd) {
9453 if ((sd->flags & SD_LOAD_BALANCE) &&
9454 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
9460 schedstat_inc(sd, alb_count);
9461 update_rq_clock(busiest_rq);
9463 p = detach_one_task(&env);
9465 schedstat_inc(sd, alb_pushed);
9467 schedstat_inc(sd, alb_failed);
9471 busiest_rq->active_balance = 0;
9474 busiest_rq->push_task = NULL;
9476 raw_spin_unlock(&busiest_rq->lock);
9479 if (push_task_detached)
9480 attach_one_task(target_rq, push_task);
9481 put_task_struct(push_task);
9485 attach_one_task(target_rq, p);
9492 static inline int on_null_domain(struct rq *rq)
9494 return unlikely(!rcu_dereference_sched(rq->sd));
9497 #ifdef CONFIG_NO_HZ_COMMON
9499 * idle load balancing details
9500 * - When one of the busy CPUs notice that there may be an idle rebalancing
9501 * needed, they will kick the idle load balancer, which then does idle
9502 * load balancing for all the idle CPUs.
9504 static inline int find_new_ilb(void)
9506 int ilb = cpumask_first(nohz.idle_cpus_mask);
9508 if (ilb < nr_cpu_ids && idle_cpu(ilb))
9515 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
9516 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
9517 * CPU (if there is one).
9519 static void nohz_balancer_kick(void)
9523 nohz.next_balance++;
9525 ilb_cpu = find_new_ilb();
9527 if (ilb_cpu >= nr_cpu_ids)
9530 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
9533 * Use smp_send_reschedule() instead of resched_cpu().
9534 * This way we generate a sched IPI on the target cpu which
9535 * is idle. And the softirq performing nohz idle load balance
9536 * will be run before returning from the IPI.
9538 smp_send_reschedule(ilb_cpu);
9542 static inline void nohz_balance_exit_idle(int cpu)
9544 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
9546 * Completely isolated CPUs don't ever set, so we must test.
9548 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
9549 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
9550 atomic_dec(&nohz.nr_cpus);
9552 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
9556 static inline void set_cpu_sd_state_busy(void)
9558 struct sched_domain *sd;
9559 int cpu = smp_processor_id();
9562 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9564 if (!sd || !sd->nohz_idle)
9568 atomic_inc(&sd->groups->sgc->nr_busy_cpus);
9573 void set_cpu_sd_state_idle(void)
9575 struct sched_domain *sd;
9576 int cpu = smp_processor_id();
9579 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9581 if (!sd || sd->nohz_idle)
9585 atomic_dec(&sd->groups->sgc->nr_busy_cpus);
9591 * This routine will record that the cpu is going idle with tick stopped.
9592 * This info will be used in performing idle load balancing in the future.
9594 void nohz_balance_enter_idle(int cpu)
9597 * If this cpu is going down, then nothing needs to be done.
9599 if (!cpu_active(cpu))
9602 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
9606 * If we're a completely isolated CPU, we don't play.
9608 if (on_null_domain(cpu_rq(cpu)))
9611 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
9612 atomic_inc(&nohz.nr_cpus);
9613 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
9616 static int sched_ilb_notifier(struct notifier_block *nfb,
9617 unsigned long action, void *hcpu)
9619 switch (action & ~CPU_TASKS_FROZEN) {
9621 nohz_balance_exit_idle(smp_processor_id());
9629 static DEFINE_SPINLOCK(balancing);
9632 * Scale the max load_balance interval with the number of CPUs in the system.
9633 * This trades load-balance latency on larger machines for less cross talk.
9635 void update_max_interval(void)
9637 max_load_balance_interval = HZ*num_online_cpus()/10;
9641 * It checks each scheduling domain to see if it is due to be balanced,
9642 * and initiates a balancing operation if so.
9644 * Balancing parameters are set up in init_sched_domains.
9646 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
9648 int continue_balancing = 1;
9650 unsigned long interval;
9651 struct sched_domain *sd;
9652 /* Earliest time when we have to do rebalance again */
9653 unsigned long next_balance = jiffies + 60*HZ;
9654 int update_next_balance = 0;
9655 int need_serialize, need_decay = 0;
9658 update_blocked_averages(cpu);
9661 for_each_domain(cpu, sd) {
9663 * Decay the newidle max times here because this is a regular
9664 * visit to all the domains. Decay ~1% per second.
9666 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
9667 sd->max_newidle_lb_cost =
9668 (sd->max_newidle_lb_cost * 253) / 256;
9669 sd->next_decay_max_lb_cost = jiffies + HZ;
9672 max_cost += sd->max_newidle_lb_cost;
9674 if (!(sd->flags & SD_LOAD_BALANCE))
9678 * Stop the load balance at this level. There is another
9679 * CPU in our sched group which is doing load balancing more
9682 if (!continue_balancing) {
9688 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
9690 need_serialize = sd->flags & SD_SERIALIZE;
9691 if (need_serialize) {
9692 if (!spin_trylock(&balancing))
9696 if (time_after_eq(jiffies, sd->last_balance + interval)) {
9697 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
9699 * The LBF_DST_PINNED logic could have changed
9700 * env->dst_cpu, so we can't know our idle
9701 * state even if we migrated tasks. Update it.
9703 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
9705 sd->last_balance = jiffies;
9706 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
9709 spin_unlock(&balancing);
9711 if (time_after(next_balance, sd->last_balance + interval)) {
9712 next_balance = sd->last_balance + interval;
9713 update_next_balance = 1;
9718 * Ensure the rq-wide value also decays but keep it at a
9719 * reasonable floor to avoid funnies with rq->avg_idle.
9721 rq->max_idle_balance_cost =
9722 max((u64)sysctl_sched_migration_cost, max_cost);
9727 * next_balance will be updated only when there is a need.
9728 * When the cpu is attached to null domain for ex, it will not be
9731 if (likely(update_next_balance)) {
9732 rq->next_balance = next_balance;
9734 #ifdef CONFIG_NO_HZ_COMMON
9736 * If this CPU has been elected to perform the nohz idle
9737 * balance. Other idle CPUs have already rebalanced with
9738 * nohz_idle_balance() and nohz.next_balance has been
9739 * updated accordingly. This CPU is now running the idle load
9740 * balance for itself and we need to update the
9741 * nohz.next_balance accordingly.
9743 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
9744 nohz.next_balance = rq->next_balance;
9749 #ifdef CONFIG_NO_HZ_COMMON
9751 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
9752 * rebalancing for all the cpus for whom scheduler ticks are stopped.
9754 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
9756 int this_cpu = this_rq->cpu;
9759 /* Earliest time when we have to do rebalance again */
9760 unsigned long next_balance = jiffies + 60*HZ;
9761 int update_next_balance = 0;
9763 if (idle != CPU_IDLE ||
9764 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
9767 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
9768 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
9772 * If this cpu gets work to do, stop the load balancing
9773 * work being done for other cpus. Next load
9774 * balancing owner will pick it up.
9779 rq = cpu_rq(balance_cpu);
9782 * If time for next balance is due,
9785 if (time_after_eq(jiffies, rq->next_balance)) {
9786 raw_spin_lock_irq(&rq->lock);
9787 update_rq_clock(rq);
9788 update_idle_cpu_load(rq);
9789 raw_spin_unlock_irq(&rq->lock);
9790 rebalance_domains(rq, CPU_IDLE);
9793 if (time_after(next_balance, rq->next_balance)) {
9794 next_balance = rq->next_balance;
9795 update_next_balance = 1;
9800 * next_balance will be updated only when there is a need.
9801 * When the CPU is attached to null domain for ex, it will not be
9804 if (likely(update_next_balance))
9805 nohz.next_balance = next_balance;
9807 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
9811 * Current heuristic for kicking the idle load balancer in the presence
9812 * of an idle cpu in the system.
9813 * - This rq has more than one task.
9814 * - This rq has at least one CFS task and the capacity of the CPU is
9815 * significantly reduced because of RT tasks or IRQs.
9816 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
9817 * multiple busy cpu.
9818 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
9819 * domain span are idle.
9821 static inline bool nohz_kick_needed(struct rq *rq)
9823 unsigned long now = jiffies;
9824 struct sched_domain *sd;
9825 struct sched_group_capacity *sgc;
9826 int nr_busy, cpu = rq->cpu;
9829 if (unlikely(rq->idle_balance))
9833 * We may be recently in ticked or tickless idle mode. At the first
9834 * busy tick after returning from idle, we will update the busy stats.
9836 set_cpu_sd_state_busy();
9837 nohz_balance_exit_idle(cpu);
9840 * None are in tickless mode and hence no need for NOHZ idle load
9843 if (likely(!atomic_read(&nohz.nr_cpus)))
9846 if (time_before(now, nohz.next_balance))
9849 if (rq->nr_running >= 2 &&
9850 (!energy_aware() || cpu_overutilized(cpu)))
9853 /* Do idle load balance if there have misfit task */
9855 return rq->misfit_task;
9858 sd = rcu_dereference(per_cpu(sd_busy, cpu));
9860 sgc = sd->groups->sgc;
9861 nr_busy = atomic_read(&sgc->nr_busy_cpus);
9870 sd = rcu_dereference(rq->sd);
9872 if ((rq->cfs.h_nr_running >= 1) &&
9873 check_cpu_capacity(rq, sd)) {
9879 sd = rcu_dereference(per_cpu(sd_asym, cpu));
9880 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
9881 sched_domain_span(sd)) < cpu)) {
9891 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
9895 * run_rebalance_domains is triggered when needed from the scheduler tick.
9896 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
9898 static void run_rebalance_domains(struct softirq_action *h)
9900 struct rq *this_rq = this_rq();
9901 enum cpu_idle_type idle = this_rq->idle_balance ?
9902 CPU_IDLE : CPU_NOT_IDLE;
9905 * If this cpu has a pending nohz_balance_kick, then do the
9906 * balancing on behalf of the other idle cpus whose ticks are
9907 * stopped. Do nohz_idle_balance *before* rebalance_domains to
9908 * give the idle cpus a chance to load balance. Else we may
9909 * load balance only within the local sched_domain hierarchy
9910 * and abort nohz_idle_balance altogether if we pull some load.
9912 nohz_idle_balance(this_rq, idle);
9913 rebalance_domains(this_rq, idle);
9917 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
9919 void trigger_load_balance(struct rq *rq)
9921 /* Don't need to rebalance while attached to NULL domain */
9922 if (unlikely(on_null_domain(rq)))
9925 if (time_after_eq(jiffies, rq->next_balance))
9926 raise_softirq(SCHED_SOFTIRQ);
9927 #ifdef CONFIG_NO_HZ_COMMON
9928 if (nohz_kick_needed(rq))
9929 nohz_balancer_kick();
9933 static void rq_online_fair(struct rq *rq)
9937 update_runtime_enabled(rq);
9940 static void rq_offline_fair(struct rq *rq)
9944 /* Ensure any throttled groups are reachable by pick_next_task */
9945 unthrottle_offline_cfs_rqs(rq);
9949 kick_active_balance(struct rq *rq, struct task_struct *p, int new_cpu)
9953 /* Invoke active balance to force migrate currently running task */
9954 raw_spin_lock(&rq->lock);
9955 if (!rq->active_balance) {
9956 rq->active_balance = 1;
9957 rq->push_cpu = new_cpu;
9962 raw_spin_unlock(&rq->lock);
9967 void check_for_migration(struct rq *rq, struct task_struct *p)
9971 int cpu = task_cpu(p);
9973 if (energy_aware() && rq->misfit_task) {
9974 if (rq->curr->state != TASK_RUNNING ||
9975 rq->curr->nr_cpus_allowed == 1)
9978 new_cpu = select_energy_cpu_brute(p, cpu, 0);
9979 if (capacity_orig_of(new_cpu) > capacity_orig_of(cpu)) {
9980 active_balance = kick_active_balance(rq, p, new_cpu);
9982 stop_one_cpu_nowait(cpu,
9983 active_load_balance_cpu_stop,
9984 rq, &rq->active_balance_work);
9989 #endif /* CONFIG_SMP */
9992 * scheduler tick hitting a task of our scheduling class:
9994 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
9996 struct cfs_rq *cfs_rq;
9997 struct sched_entity *se = &curr->se;
9999 for_each_sched_entity(se) {
10000 cfs_rq = cfs_rq_of(se);
10001 entity_tick(cfs_rq, se, queued);
10004 if (static_branch_unlikely(&sched_numa_balancing))
10005 task_tick_numa(rq, curr);
10008 if (!rq->rd->overutilized && cpu_overutilized(task_cpu(curr))) {
10009 rq->rd->overutilized = true;
10010 trace_sched_overutilized(true);
10013 rq->misfit_task = !task_fits_max(curr, rq->cpu);
10019 * called on fork with the child task as argument from the parent's context
10020 * - child not yet on the tasklist
10021 * - preemption disabled
10023 static void task_fork_fair(struct task_struct *p)
10025 struct cfs_rq *cfs_rq;
10026 struct sched_entity *se = &p->se, *curr;
10027 struct rq *rq = this_rq();
10029 raw_spin_lock(&rq->lock);
10030 update_rq_clock(rq);
10032 cfs_rq = task_cfs_rq(current);
10033 curr = cfs_rq->curr;
10035 update_curr(cfs_rq);
10036 se->vruntime = curr->vruntime;
10038 place_entity(cfs_rq, se, 1);
10040 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
10042 * Upon rescheduling, sched_class::put_prev_task() will place
10043 * 'current' within the tree based on its new key value.
10045 swap(curr->vruntime, se->vruntime);
10049 se->vruntime -= cfs_rq->min_vruntime;
10050 raw_spin_unlock(&rq->lock);
10054 * Priority of the task has changed. Check to see if we preempt
10055 * the current task.
10058 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
10060 if (!task_on_rq_queued(p))
10064 * Reschedule if we are currently running on this runqueue and
10065 * our priority decreased, or if we are not currently running on
10066 * this runqueue and our priority is higher than the current's
10068 if (rq->curr == p) {
10069 if (p->prio > oldprio)
10072 check_preempt_curr(rq, p, 0);
10075 static inline bool vruntime_normalized(struct task_struct *p)
10077 struct sched_entity *se = &p->se;
10080 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
10081 * the dequeue_entity(.flags=0) will already have normalized the
10088 * When !on_rq, vruntime of the task has usually NOT been normalized.
10089 * But there are some cases where it has already been normalized:
10091 * - A forked child which is waiting for being woken up by
10092 * wake_up_new_task().
10093 * - A task which has been woken up by try_to_wake_up() and
10094 * waiting for actually being woken up by sched_ttwu_pending().
10096 if (!se->sum_exec_runtime || p->state == TASK_WAKING)
10102 #ifdef CONFIG_FAIR_GROUP_SCHED
10104 * Propagate the changes of the sched_entity across the tg tree to make it
10105 * visible to the root
10107 static void propagate_entity_cfs_rq(struct sched_entity *se)
10109 struct cfs_rq *cfs_rq;
10111 /* Start to propagate at parent */
10114 for_each_sched_entity(se) {
10115 cfs_rq = cfs_rq_of(se);
10117 if (cfs_rq_throttled(cfs_rq))
10120 update_load_avg(se, UPDATE_TG);
10124 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
10127 static void detach_entity_cfs_rq(struct sched_entity *se)
10129 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10131 /* Catch up with the cfs_rq and remove our load when we leave */
10132 update_load_avg(se, 0);
10133 detach_entity_load_avg(cfs_rq, se);
10134 update_tg_load_avg(cfs_rq, false);
10135 propagate_entity_cfs_rq(se);
10138 static void attach_entity_cfs_rq(struct sched_entity *se)
10140 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10142 #ifdef CONFIG_FAIR_GROUP_SCHED
10144 * Since the real-depth could have been changed (only FAIR
10145 * class maintain depth value), reset depth properly.
10147 se->depth = se->parent ? se->parent->depth + 1 : 0;
10150 /* Synchronize entity with its cfs_rq */
10151 update_load_avg(se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
10152 attach_entity_load_avg(cfs_rq, se);
10153 update_tg_load_avg(cfs_rq, false);
10154 propagate_entity_cfs_rq(se);
10157 static void detach_task_cfs_rq(struct task_struct *p)
10159 struct sched_entity *se = &p->se;
10160 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10162 if (!vruntime_normalized(p)) {
10164 * Fix up our vruntime so that the current sleep doesn't
10165 * cause 'unlimited' sleep bonus.
10167 place_entity(cfs_rq, se, 0);
10168 se->vruntime -= cfs_rq->min_vruntime;
10171 detach_entity_cfs_rq(se);
10174 static void attach_task_cfs_rq(struct task_struct *p)
10176 struct sched_entity *se = &p->se;
10177 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10179 attach_entity_cfs_rq(se);
10181 if (!vruntime_normalized(p))
10182 se->vruntime += cfs_rq->min_vruntime;
10185 static void switched_from_fair(struct rq *rq, struct task_struct *p)
10187 detach_task_cfs_rq(p);
10190 static void switched_to_fair(struct rq *rq, struct task_struct *p)
10192 attach_task_cfs_rq(p);
10194 if (task_on_rq_queued(p)) {
10196 * We were most likely switched from sched_rt, so
10197 * kick off the schedule if running, otherwise just see
10198 * if we can still preempt the current task.
10203 check_preempt_curr(rq, p, 0);
10207 /* Account for a task changing its policy or group.
10209 * This routine is mostly called to set cfs_rq->curr field when a task
10210 * migrates between groups/classes.
10212 static void set_curr_task_fair(struct rq *rq)
10214 struct sched_entity *se = &rq->curr->se;
10216 for_each_sched_entity(se) {
10217 struct cfs_rq *cfs_rq = cfs_rq_of(se);
10219 set_next_entity(cfs_rq, se);
10220 /* ensure bandwidth has been allocated on our new cfs_rq */
10221 account_cfs_rq_runtime(cfs_rq, 0);
10225 void init_cfs_rq(struct cfs_rq *cfs_rq)
10227 cfs_rq->tasks_timeline = RB_ROOT;
10228 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
10229 #ifndef CONFIG_64BIT
10230 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
10233 #ifdef CONFIG_FAIR_GROUP_SCHED
10234 cfs_rq->propagate_avg = 0;
10236 atomic_long_set(&cfs_rq->removed_load_avg, 0);
10237 atomic_long_set(&cfs_rq->removed_util_avg, 0);
10241 #ifdef CONFIG_FAIR_GROUP_SCHED
10242 static void task_set_group_fair(struct task_struct *p)
10244 struct sched_entity *se = &p->se;
10246 set_task_rq(p, task_cpu(p));
10247 se->depth = se->parent ? se->parent->depth + 1 : 0;
10250 static void task_move_group_fair(struct task_struct *p)
10252 detach_task_cfs_rq(p);
10253 set_task_rq(p, task_cpu(p));
10256 /* Tell se's cfs_rq has been changed -- migrated */
10257 p->se.avg.last_update_time = 0;
10259 attach_task_cfs_rq(p);
10262 static void task_change_group_fair(struct task_struct *p, int type)
10265 case TASK_SET_GROUP:
10266 task_set_group_fair(p);
10269 case TASK_MOVE_GROUP:
10270 task_move_group_fair(p);
10275 void free_fair_sched_group(struct task_group *tg)
10279 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
10281 for_each_possible_cpu(i) {
10283 kfree(tg->cfs_rq[i]);
10292 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
10294 struct sched_entity *se;
10295 struct cfs_rq *cfs_rq;
10299 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
10302 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
10306 tg->shares = NICE_0_LOAD;
10308 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
10310 for_each_possible_cpu(i) {
10313 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
10314 GFP_KERNEL, cpu_to_node(i));
10318 se = kzalloc_node(sizeof(struct sched_entity),
10319 GFP_KERNEL, cpu_to_node(i));
10323 init_cfs_rq(cfs_rq);
10324 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
10325 init_entity_runnable_average(se);
10327 raw_spin_lock_irq(&rq->lock);
10328 post_init_entity_util_avg(se);
10329 raw_spin_unlock_irq(&rq->lock);
10340 void unregister_fair_sched_group(struct task_group *tg)
10342 unsigned long flags;
10346 for_each_possible_cpu(cpu) {
10348 remove_entity_load_avg(tg->se[cpu]);
10351 * Only empty task groups can be destroyed; so we can speculatively
10352 * check on_list without danger of it being re-added.
10354 if (!tg->cfs_rq[cpu]->on_list)
10359 raw_spin_lock_irqsave(&rq->lock, flags);
10360 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
10361 raw_spin_unlock_irqrestore(&rq->lock, flags);
10365 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
10366 struct sched_entity *se, int cpu,
10367 struct sched_entity *parent)
10369 struct rq *rq = cpu_rq(cpu);
10373 init_cfs_rq_runtime(cfs_rq);
10375 tg->cfs_rq[cpu] = cfs_rq;
10378 /* se could be NULL for root_task_group */
10383 se->cfs_rq = &rq->cfs;
10386 se->cfs_rq = parent->my_q;
10387 se->depth = parent->depth + 1;
10391 /* guarantee group entities always have weight */
10392 update_load_set(&se->load, NICE_0_LOAD);
10393 se->parent = parent;
10396 static DEFINE_MUTEX(shares_mutex);
10398 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10401 unsigned long flags;
10404 * We can't change the weight of the root cgroup.
10409 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
10411 mutex_lock(&shares_mutex);
10412 if (tg->shares == shares)
10415 tg->shares = shares;
10416 for_each_possible_cpu(i) {
10417 struct rq *rq = cpu_rq(i);
10418 struct sched_entity *se;
10421 /* Propagate contribution to hierarchy */
10422 raw_spin_lock_irqsave(&rq->lock, flags);
10424 /* Possible calls to update_curr() need rq clock */
10425 update_rq_clock(rq);
10426 for_each_sched_entity(se) {
10427 update_load_avg(se, UPDATE_TG);
10428 update_cfs_shares(se);
10430 raw_spin_unlock_irqrestore(&rq->lock, flags);
10434 mutex_unlock(&shares_mutex);
10437 #else /* CONFIG_FAIR_GROUP_SCHED */
10439 void free_fair_sched_group(struct task_group *tg) { }
10441 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
10446 void unregister_fair_sched_group(struct task_group *tg) { }
10448 #endif /* CONFIG_FAIR_GROUP_SCHED */
10451 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
10453 struct sched_entity *se = &task->se;
10454 unsigned int rr_interval = 0;
10457 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
10460 if (rq->cfs.load.weight)
10461 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
10463 return rr_interval;
10467 * All the scheduling class methods:
10469 const struct sched_class fair_sched_class = {
10470 .next = &idle_sched_class,
10471 .enqueue_task = enqueue_task_fair,
10472 .dequeue_task = dequeue_task_fair,
10473 .yield_task = yield_task_fair,
10474 .yield_to_task = yield_to_task_fair,
10476 .check_preempt_curr = check_preempt_wakeup,
10478 .pick_next_task = pick_next_task_fair,
10479 .put_prev_task = put_prev_task_fair,
10482 .select_task_rq = select_task_rq_fair,
10483 .migrate_task_rq = migrate_task_rq_fair,
10485 .rq_online = rq_online_fair,
10486 .rq_offline = rq_offline_fair,
10488 .task_waking = task_waking_fair,
10489 .task_dead = task_dead_fair,
10490 .set_cpus_allowed = set_cpus_allowed_common,
10493 .set_curr_task = set_curr_task_fair,
10494 .task_tick = task_tick_fair,
10495 .task_fork = task_fork_fair,
10497 .prio_changed = prio_changed_fair,
10498 .switched_from = switched_from_fair,
10499 .switched_to = switched_to_fair,
10501 .get_rr_interval = get_rr_interval_fair,
10503 .update_curr = update_curr_fair,
10505 #ifdef CONFIG_FAIR_GROUP_SCHED
10506 .task_change_group = task_change_group_fair,
10510 #ifdef CONFIG_SCHED_DEBUG
10511 void print_cfs_stats(struct seq_file *m, int cpu)
10513 struct cfs_rq *cfs_rq;
10516 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
10517 print_cfs_rq(m, cpu, cfs_rq);
10521 #ifdef CONFIG_NUMA_BALANCING
10522 void show_numa_stats(struct task_struct *p, struct seq_file *m)
10525 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
10527 for_each_online_node(node) {
10528 if (p->numa_faults) {
10529 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
10530 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
10532 if (p->numa_group) {
10533 gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
10534 gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
10536 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
10539 #endif /* CONFIG_NUMA_BALANCING */
10540 #endif /* CONFIG_SCHED_DEBUG */
10542 __init void init_sched_fair_class(void)
10545 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
10547 #ifdef CONFIG_NO_HZ_COMMON
10548 nohz.next_balance = jiffies;
10549 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
10550 cpu_notifier(sched_ilb_notifier, 0);