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/sched.h>
24 #include <linux/latencytop.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>
34 #include <trace/events/sched.h>
39 * Targeted preemption latency for CPU-bound tasks:
40 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
42 * NOTE: this latency value is not the same as the concept of
43 * 'timeslice length' - timeslices in CFS are of variable length
44 * and have no persistent notion like in traditional, time-slice
45 * based scheduling concepts.
47 * (to see the precise effective timeslice length of your workload,
48 * run vmstat and monitor the context-switches (cs) field)
50 unsigned int sysctl_sched_latency = 6000000ULL;
51 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
54 * The initial- and re-scaling of tunables is configurable
55 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
58 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
59 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
60 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
62 enum sched_tunable_scaling sysctl_sched_tunable_scaling
63 = SCHED_TUNABLESCALING_LOG;
66 * Minimal preemption granularity for CPU-bound tasks:
67 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
69 unsigned int sysctl_sched_min_granularity = 750000ULL;
70 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
73 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
75 static unsigned int sched_nr_latency = 8;
78 * After fork, child runs first. If set to 0 (default) then
79 * parent will (try to) run first.
81 unsigned int sysctl_sched_child_runs_first __read_mostly;
84 * SCHED_OTHER wake-up granularity.
85 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
87 * This option delays the preemption effects of decoupled workloads
88 * and reduces their over-scheduling. Synchronous workloads will still
89 * have immediate wakeup/sleep latencies.
91 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
92 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
94 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
97 * The exponential sliding window over which load is averaged for shares
101 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
103 #ifdef CONFIG_CFS_BANDWIDTH
105 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
106 * each time a cfs_rq requests quota.
108 * Note: in the case that the slice exceeds the runtime remaining (either due
109 * to consumption or the quota being specified to be smaller than the slice)
110 * we will always only issue the remaining available time.
112 * default: 5 msec, units: microseconds
114 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
118 * The margin used when comparing utilization with CPU capacity:
119 * util * 1024 < capacity * margin
121 unsigned int capacity_margin = 1280; /* ~20% */
123 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
129 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
135 static inline void update_load_set(struct load_weight *lw, unsigned long w)
142 * Increase the granularity value when there are more CPUs,
143 * because with more CPUs the 'effective latency' as visible
144 * to users decreases. But the relationship is not linear,
145 * so pick a second-best guess by going with the log2 of the
148 * This idea comes from the SD scheduler of Con Kolivas:
150 static unsigned int get_update_sysctl_factor(void)
152 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
155 switch (sysctl_sched_tunable_scaling) {
156 case SCHED_TUNABLESCALING_NONE:
159 case SCHED_TUNABLESCALING_LINEAR:
162 case SCHED_TUNABLESCALING_LOG:
164 factor = 1 + ilog2(cpus);
171 static void update_sysctl(void)
173 unsigned int factor = get_update_sysctl_factor();
175 #define SET_SYSCTL(name) \
176 (sysctl_##name = (factor) * normalized_sysctl_##name)
177 SET_SYSCTL(sched_min_granularity);
178 SET_SYSCTL(sched_latency);
179 SET_SYSCTL(sched_wakeup_granularity);
183 void sched_init_granularity(void)
188 #define WMULT_CONST (~0U)
189 #define WMULT_SHIFT 32
191 static void __update_inv_weight(struct load_weight *lw)
195 if (likely(lw->inv_weight))
198 w = scale_load_down(lw->weight);
200 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
202 else if (unlikely(!w))
203 lw->inv_weight = WMULT_CONST;
205 lw->inv_weight = WMULT_CONST / w;
209 * delta_exec * weight / lw.weight
211 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
213 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
214 * we're guaranteed shift stays positive because inv_weight is guaranteed to
215 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
217 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
218 * weight/lw.weight <= 1, and therefore our shift will also be positive.
220 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
222 u64 fact = scale_load_down(weight);
223 int shift = WMULT_SHIFT;
225 __update_inv_weight(lw);
227 if (unlikely(fact >> 32)) {
234 /* hint to use a 32x32->64 mul */
235 fact = (u64)(u32)fact * lw->inv_weight;
242 return mul_u64_u32_shr(delta_exec, fact, shift);
246 const struct sched_class fair_sched_class;
248 /**************************************************************
249 * CFS operations on generic schedulable entities:
252 #ifdef CONFIG_FAIR_GROUP_SCHED
254 /* cpu runqueue to which this cfs_rq is attached */
255 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
260 /* An entity is a task if it doesn't "own" a runqueue */
261 #define entity_is_task(se) (!se->my_q)
263 static inline struct task_struct *task_of(struct sched_entity *se)
265 SCHED_WARN_ON(!entity_is_task(se));
266 return container_of(se, struct task_struct, se);
269 /* Walk up scheduling entities hierarchy */
270 #define for_each_sched_entity(se) \
271 for (; se; se = se->parent)
273 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
278 /* runqueue on which this entity is (to be) queued */
279 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
284 /* runqueue "owned" by this group */
285 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
290 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
292 if (!cfs_rq->on_list) {
294 * Ensure we either appear before our parent (if already
295 * enqueued) or force our parent to appear after us when it is
296 * enqueued. The fact that we always enqueue bottom-up
297 * reduces this to two cases.
299 if (cfs_rq->tg->parent &&
300 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
301 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
302 &rq_of(cfs_rq)->leaf_cfs_rq_list);
304 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
305 &rq_of(cfs_rq)->leaf_cfs_rq_list);
312 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
314 if (cfs_rq->on_list) {
315 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
320 /* Iterate thr' all leaf cfs_rq's on a runqueue */
321 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
322 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
324 /* Do the two (enqueued) entities belong to the same group ? */
325 static inline struct cfs_rq *
326 is_same_group(struct sched_entity *se, struct sched_entity *pse)
328 if (se->cfs_rq == pse->cfs_rq)
334 static inline struct sched_entity *parent_entity(struct sched_entity *se)
340 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
342 int se_depth, pse_depth;
345 * preemption test can be made between sibling entities who are in the
346 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
347 * both tasks until we find their ancestors who are siblings of common
351 /* First walk up until both entities are at same depth */
352 se_depth = (*se)->depth;
353 pse_depth = (*pse)->depth;
355 while (se_depth > pse_depth) {
357 *se = parent_entity(*se);
360 while (pse_depth > se_depth) {
362 *pse = parent_entity(*pse);
365 while (!is_same_group(*se, *pse)) {
366 *se = parent_entity(*se);
367 *pse = parent_entity(*pse);
371 #else /* !CONFIG_FAIR_GROUP_SCHED */
373 static inline struct task_struct *task_of(struct sched_entity *se)
375 return container_of(se, struct task_struct, se);
378 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
380 return container_of(cfs_rq, struct rq, cfs);
383 #define entity_is_task(se) 1
385 #define for_each_sched_entity(se) \
386 for (; se; se = NULL)
388 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
390 return &task_rq(p)->cfs;
393 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
395 struct task_struct *p = task_of(se);
396 struct rq *rq = task_rq(p);
401 /* runqueue "owned" by this group */
402 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
407 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
411 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
415 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
416 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
418 static inline struct sched_entity *parent_entity(struct sched_entity *se)
424 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
428 #endif /* CONFIG_FAIR_GROUP_SCHED */
430 static __always_inline
431 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
433 /**************************************************************
434 * Scheduling class tree data structure manipulation methods:
437 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
439 s64 delta = (s64)(vruntime - max_vruntime);
441 max_vruntime = vruntime;
446 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
448 s64 delta = (s64)(vruntime - min_vruntime);
450 min_vruntime = vruntime;
455 static inline int entity_before(struct sched_entity *a,
456 struct sched_entity *b)
458 return (s64)(a->vruntime - b->vruntime) < 0;
461 static void update_min_vruntime(struct cfs_rq *cfs_rq)
463 struct sched_entity *curr = cfs_rq->curr;
465 u64 vruntime = cfs_rq->min_vruntime;
469 vruntime = curr->vruntime;
474 if (cfs_rq->rb_leftmost) {
475 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
480 vruntime = se->vruntime;
482 vruntime = min_vruntime(vruntime, se->vruntime);
485 /* ensure we never gain time by being placed backwards. */
486 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
489 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
494 * Enqueue an entity into the rb-tree:
496 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
498 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
499 struct rb_node *parent = NULL;
500 struct sched_entity *entry;
504 * Find the right place in the rbtree:
508 entry = rb_entry(parent, struct sched_entity, run_node);
510 * We dont care about collisions. Nodes with
511 * the same key stay together.
513 if (entity_before(se, entry)) {
514 link = &parent->rb_left;
516 link = &parent->rb_right;
522 * Maintain a cache of leftmost tree entries (it is frequently
526 cfs_rq->rb_leftmost = &se->run_node;
528 rb_link_node(&se->run_node, parent, link);
529 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
532 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
534 if (cfs_rq->rb_leftmost == &se->run_node) {
535 struct rb_node *next_node;
537 next_node = rb_next(&se->run_node);
538 cfs_rq->rb_leftmost = next_node;
541 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
544 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
546 struct rb_node *left = cfs_rq->rb_leftmost;
551 return rb_entry(left, struct sched_entity, run_node);
554 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
556 struct rb_node *next = rb_next(&se->run_node);
561 return rb_entry(next, struct sched_entity, run_node);
564 #ifdef CONFIG_SCHED_DEBUG
565 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
567 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
572 return rb_entry(last, struct sched_entity, run_node);
575 /**************************************************************
576 * Scheduling class statistics methods:
579 int sched_proc_update_handler(struct ctl_table *table, int write,
580 void __user *buffer, size_t *lenp,
583 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
584 unsigned int factor = get_update_sysctl_factor();
589 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
590 sysctl_sched_min_granularity);
592 #define WRT_SYSCTL(name) \
593 (normalized_sysctl_##name = sysctl_##name / (factor))
594 WRT_SYSCTL(sched_min_granularity);
595 WRT_SYSCTL(sched_latency);
596 WRT_SYSCTL(sched_wakeup_granularity);
606 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
608 if (unlikely(se->load.weight != NICE_0_LOAD))
609 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
615 * The idea is to set a period in which each task runs once.
617 * When there are too many tasks (sched_nr_latency) we have to stretch
618 * this period because otherwise the slices get too small.
620 * p = (nr <= nl) ? l : l*nr/nl
622 static u64 __sched_period(unsigned long nr_running)
624 if (unlikely(nr_running > sched_nr_latency))
625 return nr_running * sysctl_sched_min_granularity;
627 return sysctl_sched_latency;
631 * We calculate the wall-time slice from the period by taking a part
632 * proportional to the weight.
636 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
638 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
640 for_each_sched_entity(se) {
641 struct load_weight *load;
642 struct load_weight lw;
644 cfs_rq = cfs_rq_of(se);
645 load = &cfs_rq->load;
647 if (unlikely(!se->on_rq)) {
650 update_load_add(&lw, se->load.weight);
653 slice = __calc_delta(slice, se->load.weight, load);
659 * We calculate the vruntime slice of a to-be-inserted task.
663 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
665 return calc_delta_fair(sched_slice(cfs_rq, se), se);
669 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
670 static unsigned long task_h_load(struct task_struct *p);
673 * We choose a half-life close to 1 scheduling period.
674 * Note: The tables runnable_avg_yN_inv and runnable_avg_yN_sum are
675 * dependent on this value.
677 #define LOAD_AVG_PERIOD 32
678 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
679 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_AVG_MAX */
681 /* Give new sched_entity start runnable values to heavy its load in infant time */
682 void init_entity_runnable_average(struct sched_entity *se)
684 struct sched_avg *sa = &se->avg;
686 sa->last_update_time = 0;
688 * sched_avg's period_contrib should be strictly less then 1024, so
689 * we give it 1023 to make sure it is almost a period (1024us), and
690 * will definitely be update (after enqueue).
692 sa->period_contrib = 1023;
693 sa->load_avg = scale_load_down(se->load.weight);
694 sa->load_sum = sa->load_avg * LOAD_AVG_MAX;
696 * At this point, util_avg won't be used in select_task_rq_fair anyway
700 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
703 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
704 static int update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq);
705 static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force);
706 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se);
709 * With new tasks being created, their initial util_avgs are extrapolated
710 * based on the cfs_rq's current util_avg:
712 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
714 * However, in many cases, the above util_avg does not give a desired
715 * value. Moreover, the sum of the util_avgs may be divergent, such
716 * as when the series is a harmonic series.
718 * To solve this problem, we also cap the util_avg of successive tasks to
719 * only 1/2 of the left utilization budget:
721 * util_avg_cap = (1024 - cfs_rq->avg.util_avg) / 2^n
723 * where n denotes the nth task.
725 * For example, a simplest series from the beginning would be like:
727 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
728 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
730 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
731 * if util_avg > util_avg_cap.
733 void post_init_entity_util_avg(struct sched_entity *se)
735 struct cfs_rq *cfs_rq = cfs_rq_of(se);
736 struct sched_avg *sa = &se->avg;
737 long cap = (long)(SCHED_CAPACITY_SCALE - cfs_rq->avg.util_avg) / 2;
738 u64 now = cfs_rq_clock_task(cfs_rq);
741 if (cfs_rq->avg.util_avg != 0) {
742 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
743 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
745 if (sa->util_avg > cap)
750 sa->util_sum = sa->util_avg * LOAD_AVG_MAX;
753 if (entity_is_task(se)) {
754 struct task_struct *p = task_of(se);
755 if (p->sched_class != &fair_sched_class) {
757 * For !fair tasks do:
759 update_cfs_rq_load_avg(now, cfs_rq, false);
760 attach_entity_load_avg(cfs_rq, se);
761 switched_from_fair(rq, p);
763 * such that the next switched_to_fair() has the
766 se->avg.last_update_time = now;
771 update_cfs_rq_load_avg(now, cfs_rq, false);
772 attach_entity_load_avg(cfs_rq, se);
773 update_tg_load_avg(cfs_rq, false);
776 #else /* !CONFIG_SMP */
777 void init_entity_runnable_average(struct sched_entity *se)
780 void post_init_entity_util_avg(struct sched_entity *se)
783 static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
786 #endif /* CONFIG_SMP */
789 * Update the current task's runtime statistics.
791 static void update_curr(struct cfs_rq *cfs_rq)
793 struct sched_entity *curr = cfs_rq->curr;
794 u64 now = rq_clock_task(rq_of(cfs_rq));
800 delta_exec = now - curr->exec_start;
801 if (unlikely((s64)delta_exec <= 0))
804 curr->exec_start = now;
806 schedstat_set(curr->statistics.exec_max,
807 max(delta_exec, curr->statistics.exec_max));
809 curr->sum_exec_runtime += delta_exec;
810 schedstat_add(cfs_rq->exec_clock, delta_exec);
812 curr->vruntime += calc_delta_fair(delta_exec, curr);
813 update_min_vruntime(cfs_rq);
815 if (entity_is_task(curr)) {
816 struct task_struct *curtask = task_of(curr);
818 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
819 cpuacct_charge(curtask, delta_exec);
820 account_group_exec_runtime(curtask, delta_exec);
823 account_cfs_rq_runtime(cfs_rq, delta_exec);
826 static void update_curr_fair(struct rq *rq)
828 update_curr(cfs_rq_of(&rq->curr->se));
832 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
834 u64 wait_start, prev_wait_start;
836 if (!schedstat_enabled())
839 wait_start = rq_clock(rq_of(cfs_rq));
840 prev_wait_start = schedstat_val(se->statistics.wait_start);
842 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
843 likely(wait_start > prev_wait_start))
844 wait_start -= prev_wait_start;
846 schedstat_set(se->statistics.wait_start, wait_start);
850 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
852 struct task_struct *p;
855 if (!schedstat_enabled())
858 delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
860 if (entity_is_task(se)) {
862 if (task_on_rq_migrating(p)) {
864 * Preserve migrating task's wait time so wait_start
865 * time stamp can be adjusted to accumulate wait time
866 * prior to migration.
868 schedstat_set(se->statistics.wait_start, delta);
871 trace_sched_stat_wait(p, delta);
874 schedstat_set(se->statistics.wait_max,
875 max(schedstat_val(se->statistics.wait_max), delta));
876 schedstat_inc(se->statistics.wait_count);
877 schedstat_add(se->statistics.wait_sum, delta);
878 schedstat_set(se->statistics.wait_start, 0);
882 update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
884 struct task_struct *tsk = NULL;
885 u64 sleep_start, block_start;
887 if (!schedstat_enabled())
890 sleep_start = schedstat_val(se->statistics.sleep_start);
891 block_start = schedstat_val(se->statistics.block_start);
893 if (entity_is_task(se))
897 u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
902 if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
903 schedstat_set(se->statistics.sleep_max, delta);
905 schedstat_set(se->statistics.sleep_start, 0);
906 schedstat_add(se->statistics.sum_sleep_runtime, delta);
909 account_scheduler_latency(tsk, delta >> 10, 1);
910 trace_sched_stat_sleep(tsk, delta);
914 u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
919 if (unlikely(delta > schedstat_val(se->statistics.block_max)))
920 schedstat_set(se->statistics.block_max, delta);
922 schedstat_set(se->statistics.block_start, 0);
923 schedstat_add(se->statistics.sum_sleep_runtime, delta);
926 if (tsk->in_iowait) {
927 schedstat_add(se->statistics.iowait_sum, delta);
928 schedstat_inc(se->statistics.iowait_count);
929 trace_sched_stat_iowait(tsk, delta);
932 trace_sched_stat_blocked(tsk, delta);
935 * Blocking time is in units of nanosecs, so shift by
936 * 20 to get a milliseconds-range estimation of the
937 * amount of time that the task spent sleeping:
939 if (unlikely(prof_on == SLEEP_PROFILING)) {
940 profile_hits(SLEEP_PROFILING,
941 (void *)get_wchan(tsk),
944 account_scheduler_latency(tsk, delta >> 10, 0);
950 * Task is being enqueued - update stats:
953 update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
955 if (!schedstat_enabled())
959 * Are we enqueueing a waiting task? (for current tasks
960 * a dequeue/enqueue event is a NOP)
962 if (se != cfs_rq->curr)
963 update_stats_wait_start(cfs_rq, se);
965 if (flags & ENQUEUE_WAKEUP)
966 update_stats_enqueue_sleeper(cfs_rq, se);
970 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
973 if (!schedstat_enabled())
977 * Mark the end of the wait period if dequeueing a
980 if (se != cfs_rq->curr)
981 update_stats_wait_end(cfs_rq, se);
983 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
984 struct task_struct *tsk = task_of(se);
986 if (tsk->state & TASK_INTERRUPTIBLE)
987 schedstat_set(se->statistics.sleep_start,
988 rq_clock(rq_of(cfs_rq)));
989 if (tsk->state & TASK_UNINTERRUPTIBLE)
990 schedstat_set(se->statistics.block_start,
991 rq_clock(rq_of(cfs_rq)));
996 * We are picking a new current task - update its stats:
999 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1002 * We are starting a new run period:
1004 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1007 /**************************************************
1008 * Scheduling class queueing methods:
1011 #ifdef CONFIG_NUMA_BALANCING
1013 * Approximate time to scan a full NUMA task in ms. The task scan period is
1014 * calculated based on the tasks virtual memory size and
1015 * numa_balancing_scan_size.
1017 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1018 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1020 /* Portion of address space to scan in MB */
1021 unsigned int sysctl_numa_balancing_scan_size = 256;
1023 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1024 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1026 static unsigned int task_nr_scan_windows(struct task_struct *p)
1028 unsigned long rss = 0;
1029 unsigned long nr_scan_pages;
1032 * Calculations based on RSS as non-present and empty pages are skipped
1033 * by the PTE scanner and NUMA hinting faults should be trapped based
1036 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1037 rss = get_mm_rss(p->mm);
1039 rss = nr_scan_pages;
1041 rss = round_up(rss, nr_scan_pages);
1042 return rss / nr_scan_pages;
1045 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1046 #define MAX_SCAN_WINDOW 2560
1048 static unsigned int task_scan_min(struct task_struct *p)
1050 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1051 unsigned int scan, floor;
1052 unsigned int windows = 1;
1054 if (scan_size < MAX_SCAN_WINDOW)
1055 windows = MAX_SCAN_WINDOW / scan_size;
1056 floor = 1000 / windows;
1058 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1059 return max_t(unsigned int, floor, scan);
1062 static unsigned int task_scan_max(struct task_struct *p)
1064 unsigned int smin = task_scan_min(p);
1067 /* Watch for min being lower than max due to floor calculations */
1068 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1069 return max(smin, smax);
1072 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1074 rq->nr_numa_running += (p->numa_preferred_nid != -1);
1075 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1078 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1080 rq->nr_numa_running -= (p->numa_preferred_nid != -1);
1081 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1087 spinlock_t lock; /* nr_tasks, tasks */
1092 struct rcu_head rcu;
1093 unsigned long total_faults;
1094 unsigned long max_faults_cpu;
1096 * Faults_cpu is used to decide whether memory should move
1097 * towards the CPU. As a consequence, these stats are weighted
1098 * more by CPU use than by memory faults.
1100 unsigned long *faults_cpu;
1101 unsigned long faults[0];
1104 /* Shared or private faults. */
1105 #define NR_NUMA_HINT_FAULT_TYPES 2
1107 /* Memory and CPU locality */
1108 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1110 /* Averaged statistics, and temporary buffers. */
1111 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1113 pid_t task_numa_group_id(struct task_struct *p)
1115 return p->numa_group ? p->numa_group->gid : 0;
1119 * The averaged statistics, shared & private, memory & cpu,
1120 * occupy the first half of the array. The second half of the
1121 * array is for current counters, which are averaged into the
1122 * first set by task_numa_placement.
1124 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1126 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1129 static inline unsigned long task_faults(struct task_struct *p, int nid)
1131 if (!p->numa_faults)
1134 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1135 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1138 static inline unsigned long group_faults(struct task_struct *p, int nid)
1143 return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1144 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1147 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1149 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
1150 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
1154 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1155 * considered part of a numa group's pseudo-interleaving set. Migrations
1156 * between these nodes are slowed down, to allow things to settle down.
1158 #define ACTIVE_NODE_FRACTION 3
1160 static bool numa_is_active_node(int nid, struct numa_group *ng)
1162 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1165 /* Handle placement on systems where not all nodes are directly connected. */
1166 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1167 int maxdist, bool task)
1169 unsigned long score = 0;
1173 * All nodes are directly connected, and the same distance
1174 * from each other. No need for fancy placement algorithms.
1176 if (sched_numa_topology_type == NUMA_DIRECT)
1180 * This code is called for each node, introducing N^2 complexity,
1181 * which should be ok given the number of nodes rarely exceeds 8.
1183 for_each_online_node(node) {
1184 unsigned long faults;
1185 int dist = node_distance(nid, node);
1188 * The furthest away nodes in the system are not interesting
1189 * for placement; nid was already counted.
1191 if (dist == sched_max_numa_distance || node == nid)
1195 * On systems with a backplane NUMA topology, compare groups
1196 * of nodes, and move tasks towards the group with the most
1197 * memory accesses. When comparing two nodes at distance
1198 * "hoplimit", only nodes closer by than "hoplimit" are part
1199 * of each group. Skip other nodes.
1201 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1205 /* Add up the faults from nearby nodes. */
1207 faults = task_faults(p, node);
1209 faults = group_faults(p, node);
1212 * On systems with a glueless mesh NUMA topology, there are
1213 * no fixed "groups of nodes". Instead, nodes that are not
1214 * directly connected bounce traffic through intermediate
1215 * nodes; a numa_group can occupy any set of nodes.
1216 * The further away a node is, the less the faults count.
1217 * This seems to result in good task placement.
1219 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1220 faults *= (sched_max_numa_distance - dist);
1221 faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
1231 * These return the fraction of accesses done by a particular task, or
1232 * task group, on a particular numa node. The group weight is given a
1233 * larger multiplier, in order to group tasks together that are almost
1234 * evenly spread out between numa nodes.
1236 static inline unsigned long task_weight(struct task_struct *p, int nid,
1239 unsigned long faults, total_faults;
1241 if (!p->numa_faults)
1244 total_faults = p->total_numa_faults;
1249 faults = task_faults(p, nid);
1250 faults += score_nearby_nodes(p, nid, dist, true);
1252 return 1000 * faults / total_faults;
1255 static inline unsigned long group_weight(struct task_struct *p, int nid,
1258 unsigned long faults, total_faults;
1263 total_faults = p->numa_group->total_faults;
1268 faults = group_faults(p, nid);
1269 faults += score_nearby_nodes(p, nid, dist, false);
1271 return 1000 * faults / total_faults;
1274 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1275 int src_nid, int dst_cpu)
1277 struct numa_group *ng = p->numa_group;
1278 int dst_nid = cpu_to_node(dst_cpu);
1279 int last_cpupid, this_cpupid;
1281 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1284 * Multi-stage node selection is used in conjunction with a periodic
1285 * migration fault to build a temporal task<->page relation. By using
1286 * a two-stage filter we remove short/unlikely relations.
1288 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1289 * a task's usage of a particular page (n_p) per total usage of this
1290 * page (n_t) (in a given time-span) to a probability.
1292 * Our periodic faults will sample this probability and getting the
1293 * same result twice in a row, given these samples are fully
1294 * independent, is then given by P(n)^2, provided our sample period
1295 * is sufficiently short compared to the usage pattern.
1297 * This quadric squishes small probabilities, making it less likely we
1298 * act on an unlikely task<->page relation.
1300 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1301 if (!cpupid_pid_unset(last_cpupid) &&
1302 cpupid_to_nid(last_cpupid) != dst_nid)
1305 /* Always allow migrate on private faults */
1306 if (cpupid_match_pid(p, last_cpupid))
1309 /* A shared fault, but p->numa_group has not been set up yet. */
1314 * Destination node is much more heavily used than the source
1315 * node? Allow migration.
1317 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1318 ACTIVE_NODE_FRACTION)
1322 * Distribute memory according to CPU & memory use on each node,
1323 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1325 * faults_cpu(dst) 3 faults_cpu(src)
1326 * --------------- * - > ---------------
1327 * faults_mem(dst) 4 faults_mem(src)
1329 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1330 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1333 static unsigned long weighted_cpuload(const int cpu);
1334 static unsigned long source_load(int cpu, int type);
1335 static unsigned long target_load(int cpu, int type);
1336 static unsigned long capacity_of(int cpu);
1337 static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
1339 /* Cached statistics for all CPUs within a node */
1341 unsigned long nr_running;
1344 /* Total compute capacity of CPUs on a node */
1345 unsigned long compute_capacity;
1347 /* Approximate capacity in terms of runnable tasks on a node */
1348 unsigned long task_capacity;
1349 int has_free_capacity;
1353 * XXX borrowed from update_sg_lb_stats
1355 static void update_numa_stats(struct numa_stats *ns, int nid)
1357 int smt, cpu, cpus = 0;
1358 unsigned long capacity;
1360 memset(ns, 0, sizeof(*ns));
1361 for_each_cpu(cpu, cpumask_of_node(nid)) {
1362 struct rq *rq = cpu_rq(cpu);
1364 ns->nr_running += rq->nr_running;
1365 ns->load += weighted_cpuload(cpu);
1366 ns->compute_capacity += capacity_of(cpu);
1372 * If we raced with hotplug and there are no CPUs left in our mask
1373 * the @ns structure is NULL'ed and task_numa_compare() will
1374 * not find this node attractive.
1376 * We'll either bail at !has_free_capacity, or we'll detect a huge
1377 * imbalance and bail there.
1382 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1383 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
1384 capacity = cpus / smt; /* cores */
1386 ns->task_capacity = min_t(unsigned, capacity,
1387 DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
1388 ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
1391 struct task_numa_env {
1392 struct task_struct *p;
1394 int src_cpu, src_nid;
1395 int dst_cpu, dst_nid;
1397 struct numa_stats src_stats, dst_stats;
1402 struct task_struct *best_task;
1407 static void task_numa_assign(struct task_numa_env *env,
1408 struct task_struct *p, long imp)
1411 put_task_struct(env->best_task);
1416 env->best_imp = imp;
1417 env->best_cpu = env->dst_cpu;
1420 static bool load_too_imbalanced(long src_load, long dst_load,
1421 struct task_numa_env *env)
1424 long orig_src_load, orig_dst_load;
1425 long src_capacity, dst_capacity;
1428 * The load is corrected for the CPU capacity available on each node.
1431 * ------------ vs ---------
1432 * src_capacity dst_capacity
1434 src_capacity = env->src_stats.compute_capacity;
1435 dst_capacity = env->dst_stats.compute_capacity;
1437 /* We care about the slope of the imbalance, not the direction. */
1438 if (dst_load < src_load)
1439 swap(dst_load, src_load);
1441 /* Is the difference below the threshold? */
1442 imb = dst_load * src_capacity * 100 -
1443 src_load * dst_capacity * env->imbalance_pct;
1448 * The imbalance is above the allowed threshold.
1449 * Compare it with the old imbalance.
1451 orig_src_load = env->src_stats.load;
1452 orig_dst_load = env->dst_stats.load;
1454 if (orig_dst_load < orig_src_load)
1455 swap(orig_dst_load, orig_src_load);
1457 old_imb = orig_dst_load * src_capacity * 100 -
1458 orig_src_load * dst_capacity * env->imbalance_pct;
1460 /* Would this change make things worse? */
1461 return (imb > old_imb);
1465 * This checks if the overall compute and NUMA accesses of the system would
1466 * be improved if the source tasks was migrated to the target dst_cpu taking
1467 * into account that it might be best if task running on the dst_cpu should
1468 * be exchanged with the source task
1470 static void task_numa_compare(struct task_numa_env *env,
1471 long taskimp, long groupimp)
1473 struct rq *src_rq = cpu_rq(env->src_cpu);
1474 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1475 struct task_struct *cur;
1476 long src_load, dst_load;
1478 long imp = env->p->numa_group ? groupimp : taskimp;
1480 int dist = env->dist;
1483 cur = task_rcu_dereference(&dst_rq->curr);
1484 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
1488 * Because we have preemption enabled we can get migrated around and
1489 * end try selecting ourselves (current == env->p) as a swap candidate.
1495 * "imp" is the fault differential for the source task between the
1496 * source and destination node. Calculate the total differential for
1497 * the source task and potential destination task. The more negative
1498 * the value is, the more rmeote accesses that would be expected to
1499 * be incurred if the tasks were swapped.
1502 /* Skip this swap candidate if cannot move to the source cpu */
1503 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
1507 * If dst and source tasks are in the same NUMA group, or not
1508 * in any group then look only at task weights.
1510 if (cur->numa_group == env->p->numa_group) {
1511 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1512 task_weight(cur, env->dst_nid, dist);
1514 * Add some hysteresis to prevent swapping the
1515 * tasks within a group over tiny differences.
1517 if (cur->numa_group)
1521 * Compare the group weights. If a task is all by
1522 * itself (not part of a group), use the task weight
1525 if (cur->numa_group)
1526 imp += group_weight(cur, env->src_nid, dist) -
1527 group_weight(cur, env->dst_nid, dist);
1529 imp += task_weight(cur, env->src_nid, dist) -
1530 task_weight(cur, env->dst_nid, dist);
1534 if (imp <= env->best_imp && moveimp <= env->best_imp)
1538 /* Is there capacity at our destination? */
1539 if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
1540 !env->dst_stats.has_free_capacity)
1546 /* Balance doesn't matter much if we're running a task per cpu */
1547 if (imp > env->best_imp && src_rq->nr_running == 1 &&
1548 dst_rq->nr_running == 1)
1552 * In the overloaded case, try and keep the load balanced.
1555 load = task_h_load(env->p);
1556 dst_load = env->dst_stats.load + load;
1557 src_load = env->src_stats.load - load;
1559 if (moveimp > imp && moveimp > env->best_imp) {
1561 * If the improvement from just moving env->p direction is
1562 * better than swapping tasks around, check if a move is
1563 * possible. Store a slightly smaller score than moveimp,
1564 * so an actually idle CPU will win.
1566 if (!load_too_imbalanced(src_load, dst_load, env)) {
1573 if (imp <= env->best_imp)
1577 load = task_h_load(cur);
1582 if (load_too_imbalanced(src_load, dst_load, env))
1586 * One idle CPU per node is evaluated for a task numa move.
1587 * Call select_idle_sibling to maybe find a better one.
1591 * select_idle_siblings() uses an per-cpu cpumask that
1592 * can be used from IRQ context.
1594 local_irq_disable();
1595 env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
1601 task_numa_assign(env, cur, imp);
1606 static void task_numa_find_cpu(struct task_numa_env *env,
1607 long taskimp, long groupimp)
1611 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1612 /* Skip this CPU if the source task cannot migrate */
1613 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
1617 task_numa_compare(env, taskimp, groupimp);
1621 /* Only move tasks to a NUMA node less busy than the current node. */
1622 static bool numa_has_capacity(struct task_numa_env *env)
1624 struct numa_stats *src = &env->src_stats;
1625 struct numa_stats *dst = &env->dst_stats;
1627 if (src->has_free_capacity && !dst->has_free_capacity)
1631 * Only consider a task move if the source has a higher load
1632 * than the destination, corrected for CPU capacity on each node.
1634 * src->load dst->load
1635 * --------------------- vs ---------------------
1636 * src->compute_capacity dst->compute_capacity
1638 if (src->load * dst->compute_capacity * env->imbalance_pct >
1640 dst->load * src->compute_capacity * 100)
1646 static int task_numa_migrate(struct task_struct *p)
1648 struct task_numa_env env = {
1651 .src_cpu = task_cpu(p),
1652 .src_nid = task_node(p),
1654 .imbalance_pct = 112,
1660 struct sched_domain *sd;
1661 unsigned long taskweight, groupweight;
1663 long taskimp, groupimp;
1666 * Pick the lowest SD_NUMA domain, as that would have the smallest
1667 * imbalance and would be the first to start moving tasks about.
1669 * And we want to avoid any moving of tasks about, as that would create
1670 * random movement of tasks -- counter the numa conditions we're trying
1674 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
1676 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
1680 * Cpusets can break the scheduler domain tree into smaller
1681 * balance domains, some of which do not cross NUMA boundaries.
1682 * Tasks that are "trapped" in such domains cannot be migrated
1683 * elsewhere, so there is no point in (re)trying.
1685 if (unlikely(!sd)) {
1686 p->numa_preferred_nid = task_node(p);
1690 env.dst_nid = p->numa_preferred_nid;
1691 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
1692 taskweight = task_weight(p, env.src_nid, dist);
1693 groupweight = group_weight(p, env.src_nid, dist);
1694 update_numa_stats(&env.src_stats, env.src_nid);
1695 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
1696 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
1697 update_numa_stats(&env.dst_stats, env.dst_nid);
1699 /* Try to find a spot on the preferred nid. */
1700 if (numa_has_capacity(&env))
1701 task_numa_find_cpu(&env, taskimp, groupimp);
1704 * Look at other nodes in these cases:
1705 * - there is no space available on the preferred_nid
1706 * - the task is part of a numa_group that is interleaved across
1707 * multiple NUMA nodes; in order to better consolidate the group,
1708 * we need to check other locations.
1710 if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
1711 for_each_online_node(nid) {
1712 if (nid == env.src_nid || nid == p->numa_preferred_nid)
1715 dist = node_distance(env.src_nid, env.dst_nid);
1716 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1718 taskweight = task_weight(p, env.src_nid, dist);
1719 groupweight = group_weight(p, env.src_nid, dist);
1722 /* Only consider nodes where both task and groups benefit */
1723 taskimp = task_weight(p, nid, dist) - taskweight;
1724 groupimp = group_weight(p, nid, dist) - groupweight;
1725 if (taskimp < 0 && groupimp < 0)
1730 update_numa_stats(&env.dst_stats, env.dst_nid);
1731 if (numa_has_capacity(&env))
1732 task_numa_find_cpu(&env, taskimp, groupimp);
1737 * If the task is part of a workload that spans multiple NUMA nodes,
1738 * and is migrating into one of the workload's active nodes, remember
1739 * this node as the task's preferred numa node, so the workload can
1741 * A task that migrated to a second choice node will be better off
1742 * trying for a better one later. Do not set the preferred node here.
1744 if (p->numa_group) {
1745 struct numa_group *ng = p->numa_group;
1747 if (env.best_cpu == -1)
1752 if (ng->active_nodes > 1 && numa_is_active_node(env.dst_nid, ng))
1753 sched_setnuma(p, env.dst_nid);
1756 /* No better CPU than the current one was found. */
1757 if (env.best_cpu == -1)
1761 * Reset the scan period if the task is being rescheduled on an
1762 * alternative node to recheck if the tasks is now properly placed.
1764 p->numa_scan_period = task_scan_min(p);
1766 if (env.best_task == NULL) {
1767 ret = migrate_task_to(p, env.best_cpu);
1769 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
1773 ret = migrate_swap(p, env.best_task);
1775 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
1776 put_task_struct(env.best_task);
1780 /* Attempt to migrate a task to a CPU on the preferred node. */
1781 static void numa_migrate_preferred(struct task_struct *p)
1783 unsigned long interval = HZ;
1785 /* This task has no NUMA fault statistics yet */
1786 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
1789 /* Periodically retry migrating the task to the preferred node */
1790 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
1791 p->numa_migrate_retry = jiffies + interval;
1793 /* Success if task is already running on preferred CPU */
1794 if (task_node(p) == p->numa_preferred_nid)
1797 /* Otherwise, try migrate to a CPU on the preferred node */
1798 task_numa_migrate(p);
1802 * Find out how many nodes on the workload is actively running on. Do this by
1803 * tracking the nodes from which NUMA hinting faults are triggered. This can
1804 * be different from the set of nodes where the workload's memory is currently
1807 static void numa_group_count_active_nodes(struct numa_group *numa_group)
1809 unsigned long faults, max_faults = 0;
1810 int nid, active_nodes = 0;
1812 for_each_online_node(nid) {
1813 faults = group_faults_cpu(numa_group, nid);
1814 if (faults > max_faults)
1815 max_faults = faults;
1818 for_each_online_node(nid) {
1819 faults = group_faults_cpu(numa_group, nid);
1820 if (faults * ACTIVE_NODE_FRACTION > max_faults)
1824 numa_group->max_faults_cpu = max_faults;
1825 numa_group->active_nodes = active_nodes;
1829 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1830 * increments. The more local the fault statistics are, the higher the scan
1831 * period will be for the next scan window. If local/(local+remote) ratio is
1832 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1833 * the scan period will decrease. Aim for 70% local accesses.
1835 #define NUMA_PERIOD_SLOTS 10
1836 #define NUMA_PERIOD_THRESHOLD 7
1839 * Increase the scan period (slow down scanning) if the majority of
1840 * our memory is already on our local node, or if the majority of
1841 * the page accesses are shared with other processes.
1842 * Otherwise, decrease the scan period.
1844 static void update_task_scan_period(struct task_struct *p,
1845 unsigned long shared, unsigned long private)
1847 unsigned int period_slot;
1851 unsigned long remote = p->numa_faults_locality[0];
1852 unsigned long local = p->numa_faults_locality[1];
1855 * If there were no record hinting faults then either the task is
1856 * completely idle or all activity is areas that are not of interest
1857 * to automatic numa balancing. Related to that, if there were failed
1858 * migration then it implies we are migrating too quickly or the local
1859 * node is overloaded. In either case, scan slower
1861 if (local + shared == 0 || p->numa_faults_locality[2]) {
1862 p->numa_scan_period = min(p->numa_scan_period_max,
1863 p->numa_scan_period << 1);
1865 p->mm->numa_next_scan = jiffies +
1866 msecs_to_jiffies(p->numa_scan_period);
1872 * Prepare to scale scan period relative to the current period.
1873 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1874 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1875 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1877 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1878 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1879 if (ratio >= NUMA_PERIOD_THRESHOLD) {
1880 int slot = ratio - NUMA_PERIOD_THRESHOLD;
1883 diff = slot * period_slot;
1885 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1888 * Scale scan rate increases based on sharing. There is an
1889 * inverse relationship between the degree of sharing and
1890 * the adjustment made to the scanning period. Broadly
1891 * speaking the intent is that there is little point
1892 * scanning faster if shared accesses dominate as it may
1893 * simply bounce migrations uselessly
1895 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared + 1));
1896 diff = (diff * ratio) / NUMA_PERIOD_SLOTS;
1899 p->numa_scan_period = clamp(p->numa_scan_period + diff,
1900 task_scan_min(p), task_scan_max(p));
1901 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1905 * Get the fraction of time the task has been running since the last
1906 * NUMA placement cycle. The scheduler keeps similar statistics, but
1907 * decays those on a 32ms period, which is orders of magnitude off
1908 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1909 * stats only if the task is so new there are no NUMA statistics yet.
1911 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1913 u64 runtime, delta, now;
1914 /* Use the start of this time slice to avoid calculations. */
1915 now = p->se.exec_start;
1916 runtime = p->se.sum_exec_runtime;
1918 if (p->last_task_numa_placement) {
1919 delta = runtime - p->last_sum_exec_runtime;
1920 *period = now - p->last_task_numa_placement;
1922 delta = p->se.avg.load_sum / p->se.load.weight;
1923 *period = LOAD_AVG_MAX;
1926 p->last_sum_exec_runtime = runtime;
1927 p->last_task_numa_placement = now;
1933 * Determine the preferred nid for a task in a numa_group. This needs to
1934 * be done in a way that produces consistent results with group_weight,
1935 * otherwise workloads might not converge.
1937 static int preferred_group_nid(struct task_struct *p, int nid)
1942 /* Direct connections between all NUMA nodes. */
1943 if (sched_numa_topology_type == NUMA_DIRECT)
1947 * On a system with glueless mesh NUMA topology, group_weight
1948 * scores nodes according to the number of NUMA hinting faults on
1949 * both the node itself, and on nearby nodes.
1951 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1952 unsigned long score, max_score = 0;
1953 int node, max_node = nid;
1955 dist = sched_max_numa_distance;
1957 for_each_online_node(node) {
1958 score = group_weight(p, node, dist);
1959 if (score > max_score) {
1968 * Finding the preferred nid in a system with NUMA backplane
1969 * interconnect topology is more involved. The goal is to locate
1970 * tasks from numa_groups near each other in the system, and
1971 * untangle workloads from different sides of the system. This requires
1972 * searching down the hierarchy of node groups, recursively searching
1973 * inside the highest scoring group of nodes. The nodemask tricks
1974 * keep the complexity of the search down.
1976 nodes = node_online_map;
1977 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
1978 unsigned long max_faults = 0;
1979 nodemask_t max_group = NODE_MASK_NONE;
1982 /* Are there nodes at this distance from each other? */
1983 if (!find_numa_distance(dist))
1986 for_each_node_mask(a, nodes) {
1987 unsigned long faults = 0;
1988 nodemask_t this_group;
1989 nodes_clear(this_group);
1991 /* Sum group's NUMA faults; includes a==b case. */
1992 for_each_node_mask(b, nodes) {
1993 if (node_distance(a, b) < dist) {
1994 faults += group_faults(p, b);
1995 node_set(b, this_group);
1996 node_clear(b, nodes);
2000 /* Remember the top group. */
2001 if (faults > max_faults) {
2002 max_faults = faults;
2003 max_group = this_group;
2005 * subtle: at the smallest distance there is
2006 * just one node left in each "group", the
2007 * winner is the preferred nid.
2012 /* Next round, evaluate the nodes within max_group. */
2020 static void task_numa_placement(struct task_struct *p)
2022 int seq, nid, max_nid = -1, max_group_nid = -1;
2023 unsigned long max_faults = 0, max_group_faults = 0;
2024 unsigned long fault_types[2] = { 0, 0 };
2025 unsigned long total_faults;
2026 u64 runtime, period;
2027 spinlock_t *group_lock = NULL;
2030 * The p->mm->numa_scan_seq field gets updated without
2031 * exclusive access. Use READ_ONCE() here to ensure
2032 * that the field is read in a single access:
2034 seq = READ_ONCE(p->mm->numa_scan_seq);
2035 if (p->numa_scan_seq == seq)
2037 p->numa_scan_seq = seq;
2038 p->numa_scan_period_max = task_scan_max(p);
2040 total_faults = p->numa_faults_locality[0] +
2041 p->numa_faults_locality[1];
2042 runtime = numa_get_avg_runtime(p, &period);
2044 /* If the task is part of a group prevent parallel updates to group stats */
2045 if (p->numa_group) {
2046 group_lock = &p->numa_group->lock;
2047 spin_lock_irq(group_lock);
2050 /* Find the node with the highest number of faults */
2051 for_each_online_node(nid) {
2052 /* Keep track of the offsets in numa_faults array */
2053 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2054 unsigned long faults = 0, group_faults = 0;
2057 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2058 long diff, f_diff, f_weight;
2060 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2061 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2062 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2063 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2065 /* Decay existing window, copy faults since last scan */
2066 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2067 fault_types[priv] += p->numa_faults[membuf_idx];
2068 p->numa_faults[membuf_idx] = 0;
2071 * Normalize the faults_from, so all tasks in a group
2072 * count according to CPU use, instead of by the raw
2073 * number of faults. Tasks with little runtime have
2074 * little over-all impact on throughput, and thus their
2075 * faults are less important.
2077 f_weight = div64_u64(runtime << 16, period + 1);
2078 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2080 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2081 p->numa_faults[cpubuf_idx] = 0;
2083 p->numa_faults[mem_idx] += diff;
2084 p->numa_faults[cpu_idx] += f_diff;
2085 faults += p->numa_faults[mem_idx];
2086 p->total_numa_faults += diff;
2087 if (p->numa_group) {
2089 * safe because we can only change our own group
2091 * mem_idx represents the offset for a given
2092 * nid and priv in a specific region because it
2093 * is at the beginning of the numa_faults array.
2095 p->numa_group->faults[mem_idx] += diff;
2096 p->numa_group->faults_cpu[mem_idx] += f_diff;
2097 p->numa_group->total_faults += diff;
2098 group_faults += p->numa_group->faults[mem_idx];
2102 if (faults > max_faults) {
2103 max_faults = faults;
2107 if (group_faults > max_group_faults) {
2108 max_group_faults = group_faults;
2109 max_group_nid = nid;
2113 update_task_scan_period(p, fault_types[0], fault_types[1]);
2115 if (p->numa_group) {
2116 numa_group_count_active_nodes(p->numa_group);
2117 spin_unlock_irq(group_lock);
2118 max_nid = preferred_group_nid(p, max_group_nid);
2122 /* Set the new preferred node */
2123 if (max_nid != p->numa_preferred_nid)
2124 sched_setnuma(p, max_nid);
2126 if (task_node(p) != p->numa_preferred_nid)
2127 numa_migrate_preferred(p);
2131 static inline int get_numa_group(struct numa_group *grp)
2133 return atomic_inc_not_zero(&grp->refcount);
2136 static inline void put_numa_group(struct numa_group *grp)
2138 if (atomic_dec_and_test(&grp->refcount))
2139 kfree_rcu(grp, rcu);
2142 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2145 struct numa_group *grp, *my_grp;
2146 struct task_struct *tsk;
2148 int cpu = cpupid_to_cpu(cpupid);
2151 if (unlikely(!p->numa_group)) {
2152 unsigned int size = sizeof(struct numa_group) +
2153 4*nr_node_ids*sizeof(unsigned long);
2155 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2159 atomic_set(&grp->refcount, 1);
2160 grp->active_nodes = 1;
2161 grp->max_faults_cpu = 0;
2162 spin_lock_init(&grp->lock);
2164 /* Second half of the array tracks nids where faults happen */
2165 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2168 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2169 grp->faults[i] = p->numa_faults[i];
2171 grp->total_faults = p->total_numa_faults;
2174 rcu_assign_pointer(p->numa_group, grp);
2178 tsk = READ_ONCE(cpu_rq(cpu)->curr);
2180 if (!cpupid_match_pid(tsk, cpupid))
2183 grp = rcu_dereference(tsk->numa_group);
2187 my_grp = p->numa_group;
2192 * Only join the other group if its bigger; if we're the bigger group,
2193 * the other task will join us.
2195 if (my_grp->nr_tasks > grp->nr_tasks)
2199 * Tie-break on the grp address.
2201 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2204 /* Always join threads in the same process. */
2205 if (tsk->mm == current->mm)
2208 /* Simple filter to avoid false positives due to PID collisions */
2209 if (flags & TNF_SHARED)
2212 /* Update priv based on whether false sharing was detected */
2215 if (join && !get_numa_group(grp))
2223 BUG_ON(irqs_disabled());
2224 double_lock_irq(&my_grp->lock, &grp->lock);
2226 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2227 my_grp->faults[i] -= p->numa_faults[i];
2228 grp->faults[i] += p->numa_faults[i];
2230 my_grp->total_faults -= p->total_numa_faults;
2231 grp->total_faults += p->total_numa_faults;
2236 spin_unlock(&my_grp->lock);
2237 spin_unlock_irq(&grp->lock);
2239 rcu_assign_pointer(p->numa_group, grp);
2241 put_numa_group(my_grp);
2249 void task_numa_free(struct task_struct *p)
2251 struct numa_group *grp = p->numa_group;
2252 void *numa_faults = p->numa_faults;
2253 unsigned long flags;
2257 spin_lock_irqsave(&grp->lock, flags);
2258 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2259 grp->faults[i] -= p->numa_faults[i];
2260 grp->total_faults -= p->total_numa_faults;
2263 spin_unlock_irqrestore(&grp->lock, flags);
2264 RCU_INIT_POINTER(p->numa_group, NULL);
2265 put_numa_group(grp);
2268 p->numa_faults = NULL;
2273 * Got a PROT_NONE fault for a page on @node.
2275 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2277 struct task_struct *p = current;
2278 bool migrated = flags & TNF_MIGRATED;
2279 int cpu_node = task_node(current);
2280 int local = !!(flags & TNF_FAULT_LOCAL);
2281 struct numa_group *ng;
2284 if (!static_branch_likely(&sched_numa_balancing))
2287 /* for example, ksmd faulting in a user's mm */
2291 /* Allocate buffer to track faults on a per-node basis */
2292 if (unlikely(!p->numa_faults)) {
2293 int size = sizeof(*p->numa_faults) *
2294 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2296 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2297 if (!p->numa_faults)
2300 p->total_numa_faults = 0;
2301 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2305 * First accesses are treated as private, otherwise consider accesses
2306 * to be private if the accessing pid has not changed
2308 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2311 priv = cpupid_match_pid(p, last_cpupid);
2312 if (!priv && !(flags & TNF_NO_GROUP))
2313 task_numa_group(p, last_cpupid, flags, &priv);
2317 * If a workload spans multiple NUMA nodes, a shared fault that
2318 * occurs wholly within the set of nodes that the workload is
2319 * actively using should be counted as local. This allows the
2320 * scan rate to slow down when a workload has settled down.
2323 if (!priv && !local && ng && ng->active_nodes > 1 &&
2324 numa_is_active_node(cpu_node, ng) &&
2325 numa_is_active_node(mem_node, ng))
2328 task_numa_placement(p);
2331 * Retry task to preferred node migration periodically, in case it
2332 * case it previously failed, or the scheduler moved us.
2334 if (time_after(jiffies, p->numa_migrate_retry))
2335 numa_migrate_preferred(p);
2338 p->numa_pages_migrated += pages;
2339 if (flags & TNF_MIGRATE_FAIL)
2340 p->numa_faults_locality[2] += pages;
2342 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2343 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2344 p->numa_faults_locality[local] += pages;
2347 static void reset_ptenuma_scan(struct task_struct *p)
2350 * We only did a read acquisition of the mmap sem, so
2351 * p->mm->numa_scan_seq is written to without exclusive access
2352 * and the update is not guaranteed to be atomic. That's not
2353 * much of an issue though, since this is just used for
2354 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2355 * expensive, to avoid any form of compiler optimizations:
2357 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
2358 p->mm->numa_scan_offset = 0;
2362 * The expensive part of numa migration is done from task_work context.
2363 * Triggered from task_tick_numa().
2365 void task_numa_work(struct callback_head *work)
2367 unsigned long migrate, next_scan, now = jiffies;
2368 struct task_struct *p = current;
2369 struct mm_struct *mm = p->mm;
2370 u64 runtime = p->se.sum_exec_runtime;
2371 struct vm_area_struct *vma;
2372 unsigned long start, end;
2373 unsigned long nr_pte_updates = 0;
2374 long pages, virtpages;
2376 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
2378 work->next = work; /* protect against double add */
2380 * Who cares about NUMA placement when they're dying.
2382 * NOTE: make sure not to dereference p->mm before this check,
2383 * exit_task_work() happens _after_ exit_mm() so we could be called
2384 * without p->mm even though we still had it when we enqueued this
2387 if (p->flags & PF_EXITING)
2390 if (!mm->numa_next_scan) {
2391 mm->numa_next_scan = now +
2392 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2396 * Enforce maximal scan/migration frequency..
2398 migrate = mm->numa_next_scan;
2399 if (time_before(now, migrate))
2402 if (p->numa_scan_period == 0) {
2403 p->numa_scan_period_max = task_scan_max(p);
2404 p->numa_scan_period = task_scan_min(p);
2407 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2408 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2412 * Delay this task enough that another task of this mm will likely win
2413 * the next time around.
2415 p->node_stamp += 2 * TICK_NSEC;
2417 start = mm->numa_scan_offset;
2418 pages = sysctl_numa_balancing_scan_size;
2419 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2420 virtpages = pages * 8; /* Scan up to this much virtual space */
2425 down_read(&mm->mmap_sem);
2426 vma = find_vma(mm, start);
2428 reset_ptenuma_scan(p);
2432 for (; vma; vma = vma->vm_next) {
2433 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
2434 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
2439 * Shared library pages mapped by multiple processes are not
2440 * migrated as it is expected they are cache replicated. Avoid
2441 * hinting faults in read-only file-backed mappings or the vdso
2442 * as migrating the pages will be of marginal benefit.
2445 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2449 * Skip inaccessible VMAs to avoid any confusion between
2450 * PROT_NONE and NUMA hinting ptes
2452 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2456 start = max(start, vma->vm_start);
2457 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2458 end = min(end, vma->vm_end);
2459 nr_pte_updates = change_prot_numa(vma, start, end);
2462 * Try to scan sysctl_numa_balancing_size worth of
2463 * hpages that have at least one present PTE that
2464 * is not already pte-numa. If the VMA contains
2465 * areas that are unused or already full of prot_numa
2466 * PTEs, scan up to virtpages, to skip through those
2470 pages -= (end - start) >> PAGE_SHIFT;
2471 virtpages -= (end - start) >> PAGE_SHIFT;
2474 if (pages <= 0 || virtpages <= 0)
2478 } while (end != vma->vm_end);
2483 * It is possible to reach the end of the VMA list but the last few
2484 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2485 * would find the !migratable VMA on the next scan but not reset the
2486 * scanner to the start so check it now.
2489 mm->numa_scan_offset = start;
2491 reset_ptenuma_scan(p);
2492 up_read(&mm->mmap_sem);
2495 * Make sure tasks use at least 32x as much time to run other code
2496 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2497 * Usually update_task_scan_period slows down scanning enough; on an
2498 * overloaded system we need to limit overhead on a per task basis.
2500 if (unlikely(p->se.sum_exec_runtime != runtime)) {
2501 u64 diff = p->se.sum_exec_runtime - runtime;
2502 p->node_stamp += 32 * diff;
2507 * Drive the periodic memory faults..
2509 void task_tick_numa(struct rq *rq, struct task_struct *curr)
2511 struct callback_head *work = &curr->numa_work;
2515 * We don't care about NUMA placement if we don't have memory.
2517 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2521 * Using runtime rather than walltime has the dual advantage that
2522 * we (mostly) drive the selection from busy threads and that the
2523 * task needs to have done some actual work before we bother with
2526 now = curr->se.sum_exec_runtime;
2527 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2529 if (now > curr->node_stamp + period) {
2530 if (!curr->node_stamp)
2531 curr->numa_scan_period = task_scan_min(curr);
2532 curr->node_stamp += period;
2534 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2535 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2536 task_work_add(curr, work, true);
2541 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2545 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2549 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2552 #endif /* CONFIG_NUMA_BALANCING */
2555 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2557 update_load_add(&cfs_rq->load, se->load.weight);
2558 if (!parent_entity(se))
2559 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
2561 if (entity_is_task(se)) {
2562 struct rq *rq = rq_of(cfs_rq);
2564 account_numa_enqueue(rq, task_of(se));
2565 list_add(&se->group_node, &rq->cfs_tasks);
2568 cfs_rq->nr_running++;
2572 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2574 update_load_sub(&cfs_rq->load, se->load.weight);
2575 if (!parent_entity(se))
2576 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
2578 if (entity_is_task(se)) {
2579 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
2580 list_del_init(&se->group_node);
2583 cfs_rq->nr_running--;
2586 #ifdef CONFIG_FAIR_GROUP_SCHED
2588 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2590 long tg_weight, load, shares;
2593 * This really should be: cfs_rq->avg.load_avg, but instead we use
2594 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2595 * the shares for small weight interactive tasks.
2597 load = scale_load_down(cfs_rq->load.weight);
2599 tg_weight = atomic_long_read(&tg->load_avg);
2601 /* Ensure tg_weight >= load */
2602 tg_weight -= cfs_rq->tg_load_avg_contrib;
2605 shares = (tg->shares * load);
2607 shares /= tg_weight;
2609 if (shares < MIN_SHARES)
2610 shares = MIN_SHARES;
2611 if (shares > tg->shares)
2612 shares = tg->shares;
2616 # else /* CONFIG_SMP */
2617 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2621 # endif /* CONFIG_SMP */
2623 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2624 unsigned long weight)
2627 /* commit outstanding execution time */
2628 if (cfs_rq->curr == se)
2629 update_curr(cfs_rq);
2630 account_entity_dequeue(cfs_rq, se);
2633 update_load_set(&se->load, weight);
2636 account_entity_enqueue(cfs_rq, se);
2639 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2641 static void update_cfs_shares(struct cfs_rq *cfs_rq)
2643 struct task_group *tg;
2644 struct sched_entity *se;
2648 se = tg->se[cpu_of(rq_of(cfs_rq))];
2649 if (!se || throttled_hierarchy(cfs_rq))
2652 if (likely(se->load.weight == tg->shares))
2655 shares = calc_cfs_shares(cfs_rq, tg);
2657 reweight_entity(cfs_rq_of(se), se, shares);
2659 #else /* CONFIG_FAIR_GROUP_SCHED */
2660 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
2663 #endif /* CONFIG_FAIR_GROUP_SCHED */
2666 /* Precomputed fixed inverse multiplies for multiplication by y^n */
2667 static const u32 runnable_avg_yN_inv[] = {
2668 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2669 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2670 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2671 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2672 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2673 0x85aac367, 0x82cd8698,
2677 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2678 * over-estimates when re-combining.
2680 static const u32 runnable_avg_yN_sum[] = {
2681 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2682 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2683 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2687 * Precomputed \Sum y^k { 1<=k<=n, where n%32=0). Values are rolled down to
2688 * lower integers. See Documentation/scheduler/sched-avg.txt how these
2691 static const u32 __accumulated_sum_N32[] = {
2692 0, 23371, 35056, 40899, 43820, 45281,
2693 46011, 46376, 46559, 46650, 46696, 46719,
2698 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2700 static __always_inline u64 decay_load(u64 val, u64 n)
2702 unsigned int local_n;
2706 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2709 /* after bounds checking we can collapse to 32-bit */
2713 * As y^PERIOD = 1/2, we can combine
2714 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2715 * With a look-up table which covers y^n (n<PERIOD)
2717 * To achieve constant time decay_load.
2719 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2720 val >>= local_n / LOAD_AVG_PERIOD;
2721 local_n %= LOAD_AVG_PERIOD;
2724 val = mul_u64_u32_shr(val, runnable_avg_yN_inv[local_n], 32);
2729 * For updates fully spanning n periods, the contribution to runnable
2730 * average will be: \Sum 1024*y^n
2732 * We can compute this reasonably efficiently by combining:
2733 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2735 static u32 __compute_runnable_contrib(u64 n)
2739 if (likely(n <= LOAD_AVG_PERIOD))
2740 return runnable_avg_yN_sum[n];
2741 else if (unlikely(n >= LOAD_AVG_MAX_N))
2742 return LOAD_AVG_MAX;
2744 /* Since n < LOAD_AVG_MAX_N, n/LOAD_AVG_PERIOD < 11 */
2745 contrib = __accumulated_sum_N32[n/LOAD_AVG_PERIOD];
2746 n %= LOAD_AVG_PERIOD;
2747 contrib = decay_load(contrib, n);
2748 return contrib + runnable_avg_yN_sum[n];
2751 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
2754 * We can represent the historical contribution to runnable average as the
2755 * coefficients of a geometric series. To do this we sub-divide our runnable
2756 * history into segments of approximately 1ms (1024us); label the segment that
2757 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2759 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2761 * (now) (~1ms ago) (~2ms ago)
2763 * Let u_i denote the fraction of p_i that the entity was runnable.
2765 * We then designate the fractions u_i as our co-efficients, yielding the
2766 * following representation of historical load:
2767 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2769 * We choose y based on the with of a reasonably scheduling period, fixing:
2772 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2773 * approximately half as much as the contribution to load within the last ms
2776 * When a period "rolls over" and we have new u_0`, multiplying the previous
2777 * sum again by y is sufficient to update:
2778 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2779 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2781 static __always_inline int
2782 __update_load_avg(u64 now, int cpu, struct sched_avg *sa,
2783 unsigned long weight, int running, struct cfs_rq *cfs_rq)
2785 u64 delta, scaled_delta, periods;
2787 unsigned int delta_w, scaled_delta_w, decayed = 0;
2788 unsigned long scale_freq, scale_cpu;
2790 delta = now - sa->last_update_time;
2792 * This should only happen when time goes backwards, which it
2793 * unfortunately does during sched clock init when we swap over to TSC.
2795 if ((s64)delta < 0) {
2796 sa->last_update_time = now;
2801 * Use 1024ns as the unit of measurement since it's a reasonable
2802 * approximation of 1us and fast to compute.
2807 sa->last_update_time = now;
2809 scale_freq = arch_scale_freq_capacity(NULL, cpu);
2810 scale_cpu = arch_scale_cpu_capacity(NULL, cpu);
2812 /* delta_w is the amount already accumulated against our next period */
2813 delta_w = sa->period_contrib;
2814 if (delta + delta_w >= 1024) {
2817 /* how much left for next period will start over, we don't know yet */
2818 sa->period_contrib = 0;
2821 * Now that we know we're crossing a period boundary, figure
2822 * out how much from delta we need to complete the current
2823 * period and accrue it.
2825 delta_w = 1024 - delta_w;
2826 scaled_delta_w = cap_scale(delta_w, scale_freq);
2828 sa->load_sum += weight * scaled_delta_w;
2830 cfs_rq->runnable_load_sum +=
2831 weight * scaled_delta_w;
2835 sa->util_sum += scaled_delta_w * scale_cpu;
2839 /* Figure out how many additional periods this update spans */
2840 periods = delta / 1024;
2843 sa->load_sum = decay_load(sa->load_sum, periods + 1);
2845 cfs_rq->runnable_load_sum =
2846 decay_load(cfs_rq->runnable_load_sum, periods + 1);
2848 sa->util_sum = decay_load((u64)(sa->util_sum), periods + 1);
2850 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
2851 contrib = __compute_runnable_contrib(periods);
2852 contrib = cap_scale(contrib, scale_freq);
2854 sa->load_sum += weight * contrib;
2856 cfs_rq->runnable_load_sum += weight * contrib;
2859 sa->util_sum += contrib * scale_cpu;
2862 /* Remainder of delta accrued against u_0` */
2863 scaled_delta = cap_scale(delta, scale_freq);
2865 sa->load_sum += weight * scaled_delta;
2867 cfs_rq->runnable_load_sum += weight * scaled_delta;
2870 sa->util_sum += scaled_delta * scale_cpu;
2872 sa->period_contrib += delta;
2875 sa->load_avg = div_u64(sa->load_sum, LOAD_AVG_MAX);
2877 cfs_rq->runnable_load_avg =
2878 div_u64(cfs_rq->runnable_load_sum, LOAD_AVG_MAX);
2880 sa->util_avg = sa->util_sum / LOAD_AVG_MAX;
2886 #ifdef CONFIG_FAIR_GROUP_SCHED
2888 * update_tg_load_avg - update the tg's load avg
2889 * @cfs_rq: the cfs_rq whose avg changed
2890 * @force: update regardless of how small the difference
2892 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
2893 * However, because tg->load_avg is a global value there are performance
2896 * In order to avoid having to look at the other cfs_rq's, we use a
2897 * differential update where we store the last value we propagated. This in
2898 * turn allows skipping updates if the differential is 'small'.
2900 * Updating tg's load_avg is necessary before update_cfs_share() (which is
2901 * done) and effective_load() (which is not done because it is too costly).
2903 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
2905 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
2908 * No need to update load_avg for root_task_group as it is not used.
2910 if (cfs_rq->tg == &root_task_group)
2913 if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
2914 atomic_long_add(delta, &cfs_rq->tg->load_avg);
2915 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
2920 * Called within set_task_rq() right before setting a task's cpu. The
2921 * caller only guarantees p->pi_lock is held; no other assumptions,
2922 * including the state of rq->lock, should be made.
2924 void set_task_rq_fair(struct sched_entity *se,
2925 struct cfs_rq *prev, struct cfs_rq *next)
2927 if (!sched_feat(ATTACH_AGE_LOAD))
2931 * We are supposed to update the task to "current" time, then its up to
2932 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
2933 * getting what current time is, so simply throw away the out-of-date
2934 * time. This will result in the wakee task is less decayed, but giving
2935 * the wakee more load sounds not bad.
2937 if (se->avg.last_update_time && prev) {
2938 u64 p_last_update_time;
2939 u64 n_last_update_time;
2941 #ifndef CONFIG_64BIT
2942 u64 p_last_update_time_copy;
2943 u64 n_last_update_time_copy;
2946 p_last_update_time_copy = prev->load_last_update_time_copy;
2947 n_last_update_time_copy = next->load_last_update_time_copy;
2951 p_last_update_time = prev->avg.last_update_time;
2952 n_last_update_time = next->avg.last_update_time;
2954 } while (p_last_update_time != p_last_update_time_copy ||
2955 n_last_update_time != n_last_update_time_copy);
2957 p_last_update_time = prev->avg.last_update_time;
2958 n_last_update_time = next->avg.last_update_time;
2960 __update_load_avg(p_last_update_time, cpu_of(rq_of(prev)),
2961 &se->avg, 0, 0, NULL);
2962 se->avg.last_update_time = n_last_update_time;
2965 #else /* CONFIG_FAIR_GROUP_SCHED */
2966 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
2967 #endif /* CONFIG_FAIR_GROUP_SCHED */
2969 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq)
2971 struct rq *rq = rq_of(cfs_rq);
2972 int cpu = cpu_of(rq);
2974 if (cpu == smp_processor_id() && &rq->cfs == cfs_rq) {
2975 unsigned long max = rq->cpu_capacity_orig;
2978 * There are a few boundary cases this might miss but it should
2979 * get called often enough that that should (hopefully) not be
2980 * a real problem -- added to that it only calls on the local
2981 * CPU, so if we enqueue remotely we'll miss an update, but
2982 * the next tick/schedule should update.
2984 * It will not get called when we go idle, because the idle
2985 * thread is a different class (!fair), nor will the utilization
2986 * number include things like RT tasks.
2988 * As is, the util number is not freq-invariant (we'd have to
2989 * implement arch_scale_freq_capacity() for that).
2993 cpufreq_update_util(rq_clock(rq),
2994 min(cfs_rq->avg.util_avg, max), max);
2999 * Unsigned subtract and clamp on underflow.
3001 * Explicitly do a load-store to ensure the intermediate value never hits
3002 * memory. This allows lockless observations without ever seeing the negative
3005 #define sub_positive(_ptr, _val) do { \
3006 typeof(_ptr) ptr = (_ptr); \
3007 typeof(*ptr) val = (_val); \
3008 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3012 WRITE_ONCE(*ptr, res); \
3016 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3017 * @now: current time, as per cfs_rq_clock_task()
3018 * @cfs_rq: cfs_rq to update
3019 * @update_freq: should we call cfs_rq_util_change() or will the call do so
3021 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3022 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3023 * post_init_entity_util_avg().
3025 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3027 * Returns true if the load decayed or we removed load.
3029 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3030 * call update_tg_load_avg() when this function returns true.
3033 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3035 struct sched_avg *sa = &cfs_rq->avg;
3036 int decayed, removed_load = 0, removed_util = 0;
3038 if (atomic_long_read(&cfs_rq->removed_load_avg)) {
3039 s64 r = atomic_long_xchg(&cfs_rq->removed_load_avg, 0);
3040 sub_positive(&sa->load_avg, r);
3041 sub_positive(&sa->load_sum, r * LOAD_AVG_MAX);
3045 if (atomic_long_read(&cfs_rq->removed_util_avg)) {
3046 long r = atomic_long_xchg(&cfs_rq->removed_util_avg, 0);
3047 sub_positive(&sa->util_avg, r);
3048 sub_positive(&sa->util_sum, r * LOAD_AVG_MAX);
3052 decayed = __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
3053 scale_load_down(cfs_rq->load.weight), cfs_rq->curr != NULL, cfs_rq);
3055 #ifndef CONFIG_64BIT
3057 cfs_rq->load_last_update_time_copy = sa->last_update_time;
3060 if (update_freq && (decayed || removed_util))
3061 cfs_rq_util_change(cfs_rq);
3063 return decayed || removed_load;
3066 /* Update task and its cfs_rq load average */
3067 static inline void update_load_avg(struct sched_entity *se, int update_tg)
3069 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3070 u64 now = cfs_rq_clock_task(cfs_rq);
3071 struct rq *rq = rq_of(cfs_rq);
3072 int cpu = cpu_of(rq);
3075 * Track task load average for carrying it to new CPU after migrated, and
3076 * track group sched_entity load average for task_h_load calc in migration
3078 __update_load_avg(now, cpu, &se->avg,
3079 se->on_rq * scale_load_down(se->load.weight),
3080 cfs_rq->curr == se, NULL);
3082 if (update_cfs_rq_load_avg(now, cfs_rq, true) && update_tg)
3083 update_tg_load_avg(cfs_rq, 0);
3087 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3088 * @cfs_rq: cfs_rq to attach to
3089 * @se: sched_entity to attach
3091 * Must call update_cfs_rq_load_avg() before this, since we rely on
3092 * cfs_rq->avg.last_update_time being current.
3094 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3096 if (!sched_feat(ATTACH_AGE_LOAD))
3100 * If we got migrated (either between CPUs or between cgroups) we'll
3101 * have aged the average right before clearing @last_update_time.
3103 * Or we're fresh through post_init_entity_util_avg().
3105 if (se->avg.last_update_time) {
3106 __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
3107 &se->avg, 0, 0, NULL);
3110 * XXX: we could have just aged the entire load away if we've been
3111 * absent from the fair class for too long.
3116 se->avg.last_update_time = cfs_rq->avg.last_update_time;
3117 cfs_rq->avg.load_avg += se->avg.load_avg;
3118 cfs_rq->avg.load_sum += se->avg.load_sum;
3119 cfs_rq->avg.util_avg += se->avg.util_avg;
3120 cfs_rq->avg.util_sum += se->avg.util_sum;
3122 cfs_rq_util_change(cfs_rq);
3126 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3127 * @cfs_rq: cfs_rq to detach from
3128 * @se: sched_entity to detach
3130 * Must call update_cfs_rq_load_avg() before this, since we rely on
3131 * cfs_rq->avg.last_update_time being current.
3133 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3135 __update_load_avg(cfs_rq->avg.last_update_time, cpu_of(rq_of(cfs_rq)),
3136 &se->avg, se->on_rq * scale_load_down(se->load.weight),
3137 cfs_rq->curr == se, NULL);
3139 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3140 sub_positive(&cfs_rq->avg.load_sum, se->avg.load_sum);
3141 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3142 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
3144 cfs_rq_util_change(cfs_rq);
3147 /* Add the load generated by se into cfs_rq's load average */
3149 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3151 struct sched_avg *sa = &se->avg;
3152 u64 now = cfs_rq_clock_task(cfs_rq);
3153 int migrated, decayed;
3155 migrated = !sa->last_update_time;
3157 __update_load_avg(now, cpu_of(rq_of(cfs_rq)), sa,
3158 se->on_rq * scale_load_down(se->load.weight),
3159 cfs_rq->curr == se, NULL);
3162 decayed = update_cfs_rq_load_avg(now, cfs_rq, !migrated);
3164 cfs_rq->runnable_load_avg += sa->load_avg;
3165 cfs_rq->runnable_load_sum += sa->load_sum;
3168 attach_entity_load_avg(cfs_rq, se);
3170 if (decayed || migrated)
3171 update_tg_load_avg(cfs_rq, 0);
3174 /* Remove the runnable load generated by se from cfs_rq's runnable load average */
3176 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3178 update_load_avg(se, 1);
3180 cfs_rq->runnable_load_avg =
3181 max_t(long, cfs_rq->runnable_load_avg - se->avg.load_avg, 0);
3182 cfs_rq->runnable_load_sum =
3183 max_t(s64, cfs_rq->runnable_load_sum - se->avg.load_sum, 0);
3186 #ifndef CONFIG_64BIT
3187 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3189 u64 last_update_time_copy;
3190 u64 last_update_time;
3193 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3195 last_update_time = cfs_rq->avg.last_update_time;
3196 } while (last_update_time != last_update_time_copy);
3198 return last_update_time;
3201 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3203 return cfs_rq->avg.last_update_time;
3208 * Task first catches up with cfs_rq, and then subtract
3209 * itself from the cfs_rq (task must be off the queue now).
3211 void remove_entity_load_avg(struct sched_entity *se)
3213 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3214 u64 last_update_time;
3217 * tasks cannot exit without having gone through wake_up_new_task() ->
3218 * post_init_entity_util_avg() which will have added things to the
3219 * cfs_rq, so we can remove unconditionally.
3221 * Similarly for groups, they will have passed through
3222 * post_init_entity_util_avg() before unregister_sched_fair_group()
3226 last_update_time = cfs_rq_last_update_time(cfs_rq);
3228 __update_load_avg(last_update_time, cpu_of(rq_of(cfs_rq)), &se->avg, 0, 0, NULL);
3229 atomic_long_add(se->avg.load_avg, &cfs_rq->removed_load_avg);
3230 atomic_long_add(se->avg.util_avg, &cfs_rq->removed_util_avg);
3233 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
3235 return cfs_rq->runnable_load_avg;
3238 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3240 return cfs_rq->avg.load_avg;
3243 static int idle_balance(struct rq *this_rq);
3245 #else /* CONFIG_SMP */
3248 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq, bool update_freq)
3253 static inline void update_load_avg(struct sched_entity *se, int not_used)
3255 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3256 struct rq *rq = rq_of(cfs_rq);
3258 cpufreq_trigger_update(rq_clock(rq));
3262 enqueue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3264 dequeue_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3265 static inline void remove_entity_load_avg(struct sched_entity *se) {}
3268 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3270 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3272 static inline int idle_balance(struct rq *rq)
3277 #endif /* CONFIG_SMP */
3279 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
3281 #ifdef CONFIG_SCHED_DEBUG
3282 s64 d = se->vruntime - cfs_rq->min_vruntime;
3287 if (d > 3*sysctl_sched_latency)
3288 schedstat_inc(cfs_rq->nr_spread_over);
3293 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
3295 u64 vruntime = cfs_rq->min_vruntime;
3298 * The 'current' period is already promised to the current tasks,
3299 * however the extra weight of the new task will slow them down a
3300 * little, place the new task so that it fits in the slot that
3301 * stays open at the end.
3303 if (initial && sched_feat(START_DEBIT))
3304 vruntime += sched_vslice(cfs_rq, se);
3306 /* sleeps up to a single latency don't count. */
3308 unsigned long thresh = sysctl_sched_latency;
3311 * Halve their sleep time's effect, to allow
3312 * for a gentler effect of sleepers:
3314 if (sched_feat(GENTLE_FAIR_SLEEPERS))
3320 /* ensure we never gain time by being placed backwards. */
3321 se->vruntime = max_vruntime(se->vruntime, vruntime);
3324 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
3326 static inline void check_schedstat_required(void)
3328 #ifdef CONFIG_SCHEDSTATS
3329 if (schedstat_enabled())
3332 /* Force schedstat enabled if a dependent tracepoint is active */
3333 if (trace_sched_stat_wait_enabled() ||
3334 trace_sched_stat_sleep_enabled() ||
3335 trace_sched_stat_iowait_enabled() ||
3336 trace_sched_stat_blocked_enabled() ||
3337 trace_sched_stat_runtime_enabled()) {
3338 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
3339 "stat_blocked and stat_runtime require the "
3340 "kernel parameter schedstats=enabled or "
3341 "kernel.sched_schedstats=1\n");
3352 * update_min_vruntime()
3353 * vruntime -= min_vruntime
3357 * update_min_vruntime()
3358 * vruntime += min_vruntime
3360 * this way the vruntime transition between RQs is done when both
3361 * min_vruntime are up-to-date.
3365 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
3366 * vruntime -= min_vruntime
3370 * update_min_vruntime()
3371 * vruntime += min_vruntime
3373 * this way we don't have the most up-to-date min_vruntime on the originating
3374 * CPU and an up-to-date min_vruntime on the destination CPU.
3378 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3380 bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
3381 bool curr = cfs_rq->curr == se;
3384 * If we're the current task, we must renormalise before calling
3388 se->vruntime += cfs_rq->min_vruntime;
3390 update_curr(cfs_rq);
3393 * Otherwise, renormalise after, such that we're placed at the current
3394 * moment in time, instead of some random moment in the past. Being
3395 * placed in the past could significantly boost this task to the
3396 * fairness detriment of existing tasks.
3398 if (renorm && !curr)
3399 se->vruntime += cfs_rq->min_vruntime;
3401 enqueue_entity_load_avg(cfs_rq, se);
3402 account_entity_enqueue(cfs_rq, se);
3403 update_cfs_shares(cfs_rq);
3405 if (flags & ENQUEUE_WAKEUP)
3406 place_entity(cfs_rq, se, 0);
3408 check_schedstat_required();
3409 update_stats_enqueue(cfs_rq, se, flags);
3410 check_spread(cfs_rq, se);
3412 __enqueue_entity(cfs_rq, se);
3415 if (cfs_rq->nr_running == 1) {
3416 list_add_leaf_cfs_rq(cfs_rq);
3417 check_enqueue_throttle(cfs_rq);
3421 static void __clear_buddies_last(struct sched_entity *se)
3423 for_each_sched_entity(se) {
3424 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3425 if (cfs_rq->last != se)
3428 cfs_rq->last = NULL;
3432 static void __clear_buddies_next(struct sched_entity *se)
3434 for_each_sched_entity(se) {
3435 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3436 if (cfs_rq->next != se)
3439 cfs_rq->next = NULL;
3443 static void __clear_buddies_skip(struct sched_entity *se)
3445 for_each_sched_entity(se) {
3446 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3447 if (cfs_rq->skip != se)
3450 cfs_rq->skip = NULL;
3454 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3456 if (cfs_rq->last == se)
3457 __clear_buddies_last(se);
3459 if (cfs_rq->next == se)
3460 __clear_buddies_next(se);
3462 if (cfs_rq->skip == se)
3463 __clear_buddies_skip(se);
3466 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3469 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3472 * Update run-time statistics of the 'current'.
3474 update_curr(cfs_rq);
3475 dequeue_entity_load_avg(cfs_rq, se);
3477 update_stats_dequeue(cfs_rq, se, flags);
3479 clear_buddies(cfs_rq, se);
3481 if (se != cfs_rq->curr)
3482 __dequeue_entity(cfs_rq, se);
3484 account_entity_dequeue(cfs_rq, se);
3487 * Normalize after update_curr(); which will also have moved
3488 * min_vruntime if @se is the one holding it back. But before doing
3489 * update_min_vruntime() again, which will discount @se's position and
3490 * can move min_vruntime forward still more.
3492 if (!(flags & DEQUEUE_SLEEP))
3493 se->vruntime -= cfs_rq->min_vruntime;
3495 /* return excess runtime on last dequeue */
3496 return_cfs_rq_runtime(cfs_rq);
3498 update_cfs_shares(cfs_rq);
3501 * Now advance min_vruntime if @se was the entity holding it back,
3502 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
3503 * put back on, and if we advance min_vruntime, we'll be placed back
3504 * further than we started -- ie. we'll be penalized.
3506 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
3507 update_min_vruntime(cfs_rq);
3511 * Preempt the current task with a newly woken task if needed:
3514 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3516 unsigned long ideal_runtime, delta_exec;
3517 struct sched_entity *se;
3520 ideal_runtime = sched_slice(cfs_rq, curr);
3521 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
3522 if (delta_exec > ideal_runtime) {
3523 resched_curr(rq_of(cfs_rq));
3525 * The current task ran long enough, ensure it doesn't get
3526 * re-elected due to buddy favours.
3528 clear_buddies(cfs_rq, curr);
3533 * Ensure that a task that missed wakeup preemption by a
3534 * narrow margin doesn't have to wait for a full slice.
3535 * This also mitigates buddy induced latencies under load.
3537 if (delta_exec < sysctl_sched_min_granularity)
3540 se = __pick_first_entity(cfs_rq);
3541 delta = curr->vruntime - se->vruntime;
3546 if (delta > ideal_runtime)
3547 resched_curr(rq_of(cfs_rq));
3551 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
3553 /* 'current' is not kept within the tree. */
3556 * Any task has to be enqueued before it get to execute on
3557 * a CPU. So account for the time it spent waiting on the
3560 update_stats_wait_end(cfs_rq, se);
3561 __dequeue_entity(cfs_rq, se);
3562 update_load_avg(se, 1);
3565 update_stats_curr_start(cfs_rq, se);
3569 * Track our maximum slice length, if the CPU's load is at
3570 * least twice that of our own weight (i.e. dont track it
3571 * when there are only lesser-weight tasks around):
3573 if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
3574 schedstat_set(se->statistics.slice_max,
3575 max((u64)schedstat_val(se->statistics.slice_max),
3576 se->sum_exec_runtime - se->prev_sum_exec_runtime));
3579 se->prev_sum_exec_runtime = se->sum_exec_runtime;
3583 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
3586 * Pick the next process, keeping these things in mind, in this order:
3587 * 1) keep things fair between processes/task groups
3588 * 2) pick the "next" process, since someone really wants that to run
3589 * 3) pick the "last" process, for cache locality
3590 * 4) do not run the "skip" process, if something else is available
3592 static struct sched_entity *
3593 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3595 struct sched_entity *left = __pick_first_entity(cfs_rq);
3596 struct sched_entity *se;
3599 * If curr is set we have to see if its left of the leftmost entity
3600 * still in the tree, provided there was anything in the tree at all.
3602 if (!left || (curr && entity_before(curr, left)))
3605 se = left; /* ideally we run the leftmost entity */
3608 * Avoid running the skip buddy, if running something else can
3609 * be done without getting too unfair.
3611 if (cfs_rq->skip == se) {
3612 struct sched_entity *second;
3615 second = __pick_first_entity(cfs_rq);
3617 second = __pick_next_entity(se);
3618 if (!second || (curr && entity_before(curr, second)))
3622 if (second && wakeup_preempt_entity(second, left) < 1)
3627 * Prefer last buddy, try to return the CPU to a preempted task.
3629 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
3633 * Someone really wants this to run. If it's not unfair, run it.
3635 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
3638 clear_buddies(cfs_rq, se);
3643 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3645 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
3648 * If still on the runqueue then deactivate_task()
3649 * was not called and update_curr() has to be done:
3652 update_curr(cfs_rq);
3654 /* throttle cfs_rqs exceeding runtime */
3655 check_cfs_rq_runtime(cfs_rq);
3657 check_spread(cfs_rq, prev);
3660 update_stats_wait_start(cfs_rq, prev);
3661 /* Put 'current' back into the tree. */
3662 __enqueue_entity(cfs_rq, prev);
3663 /* in !on_rq case, update occurred at dequeue */
3664 update_load_avg(prev, 0);
3666 cfs_rq->curr = NULL;
3670 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
3673 * Update run-time statistics of the 'current'.
3675 update_curr(cfs_rq);
3678 * Ensure that runnable average is periodically updated.
3680 update_load_avg(curr, 1);
3681 update_cfs_shares(cfs_rq);
3683 #ifdef CONFIG_SCHED_HRTICK
3685 * queued ticks are scheduled to match the slice, so don't bother
3686 * validating it and just reschedule.
3689 resched_curr(rq_of(cfs_rq));
3693 * don't let the period tick interfere with the hrtick preemption
3695 if (!sched_feat(DOUBLE_TICK) &&
3696 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3700 if (cfs_rq->nr_running > 1)
3701 check_preempt_tick(cfs_rq, curr);
3705 /**************************************************
3706 * CFS bandwidth control machinery
3709 #ifdef CONFIG_CFS_BANDWIDTH
3711 #ifdef HAVE_JUMP_LABEL
3712 static struct static_key __cfs_bandwidth_used;
3714 static inline bool cfs_bandwidth_used(void)
3716 return static_key_false(&__cfs_bandwidth_used);
3719 void cfs_bandwidth_usage_inc(void)
3721 static_key_slow_inc(&__cfs_bandwidth_used);
3724 void cfs_bandwidth_usage_dec(void)
3726 static_key_slow_dec(&__cfs_bandwidth_used);
3728 #else /* HAVE_JUMP_LABEL */
3729 static bool cfs_bandwidth_used(void)
3734 void cfs_bandwidth_usage_inc(void) {}
3735 void cfs_bandwidth_usage_dec(void) {}
3736 #endif /* HAVE_JUMP_LABEL */
3739 * default period for cfs group bandwidth.
3740 * default: 0.1s, units: nanoseconds
3742 static inline u64 default_cfs_period(void)
3744 return 100000000ULL;
3747 static inline u64 sched_cfs_bandwidth_slice(void)
3749 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3753 * Replenish runtime according to assigned quota and update expiration time.
3754 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3755 * additional synchronization around rq->lock.
3757 * requires cfs_b->lock
3759 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
3763 if (cfs_b->quota == RUNTIME_INF)
3766 now = sched_clock_cpu(smp_processor_id());
3767 cfs_b->runtime = cfs_b->quota;
3768 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3771 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3773 return &tg->cfs_bandwidth;
3776 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3777 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3779 if (unlikely(cfs_rq->throttle_count))
3780 return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
3782 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
3785 /* returns 0 on failure to allocate runtime */
3786 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3788 struct task_group *tg = cfs_rq->tg;
3789 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
3790 u64 amount = 0, min_amount, expires;
3792 /* note: this is a positive sum as runtime_remaining <= 0 */
3793 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3795 raw_spin_lock(&cfs_b->lock);
3796 if (cfs_b->quota == RUNTIME_INF)
3797 amount = min_amount;
3799 start_cfs_bandwidth(cfs_b);
3801 if (cfs_b->runtime > 0) {
3802 amount = min(cfs_b->runtime, min_amount);
3803 cfs_b->runtime -= amount;
3807 expires = cfs_b->runtime_expires;
3808 raw_spin_unlock(&cfs_b->lock);
3810 cfs_rq->runtime_remaining += amount;
3812 * we may have advanced our local expiration to account for allowed
3813 * spread between our sched_clock and the one on which runtime was
3816 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3817 cfs_rq->runtime_expires = expires;
3819 return cfs_rq->runtime_remaining > 0;
3823 * Note: This depends on the synchronization provided by sched_clock and the
3824 * fact that rq->clock snapshots this value.
3826 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3828 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3830 /* if the deadline is ahead of our clock, nothing to do */
3831 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
3834 if (cfs_rq->runtime_remaining < 0)
3838 * If the local deadline has passed we have to consider the
3839 * possibility that our sched_clock is 'fast' and the global deadline
3840 * has not truly expired.
3842 * Fortunately we can check determine whether this the case by checking
3843 * whether the global deadline has advanced. It is valid to compare
3844 * cfs_b->runtime_expires without any locks since we only care about
3845 * exact equality, so a partial write will still work.
3848 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
3849 /* extend local deadline, drift is bounded above by 2 ticks */
3850 cfs_rq->runtime_expires += TICK_NSEC;
3852 /* global deadline is ahead, expiration has passed */
3853 cfs_rq->runtime_remaining = 0;
3857 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3859 /* dock delta_exec before expiring quota (as it could span periods) */
3860 cfs_rq->runtime_remaining -= delta_exec;
3861 expire_cfs_rq_runtime(cfs_rq);
3863 if (likely(cfs_rq->runtime_remaining > 0))
3867 * if we're unable to extend our runtime we resched so that the active
3868 * hierarchy can be throttled
3870 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
3871 resched_curr(rq_of(cfs_rq));
3874 static __always_inline
3875 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3877 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
3880 __account_cfs_rq_runtime(cfs_rq, delta_exec);
3883 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
3885 return cfs_bandwidth_used() && cfs_rq->throttled;
3888 /* check whether cfs_rq, or any parent, is throttled */
3889 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
3891 return cfs_bandwidth_used() && cfs_rq->throttle_count;
3895 * Ensure that neither of the group entities corresponding to src_cpu or
3896 * dest_cpu are members of a throttled hierarchy when performing group
3897 * load-balance operations.
3899 static inline int throttled_lb_pair(struct task_group *tg,
3900 int src_cpu, int dest_cpu)
3902 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
3904 src_cfs_rq = tg->cfs_rq[src_cpu];
3905 dest_cfs_rq = tg->cfs_rq[dest_cpu];
3907 return throttled_hierarchy(src_cfs_rq) ||
3908 throttled_hierarchy(dest_cfs_rq);
3911 /* updated child weight may affect parent so we have to do this bottom up */
3912 static int tg_unthrottle_up(struct task_group *tg, void *data)
3914 struct rq *rq = data;
3915 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3917 cfs_rq->throttle_count--;
3918 if (!cfs_rq->throttle_count) {
3919 /* adjust cfs_rq_clock_task() */
3920 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
3921 cfs_rq->throttled_clock_task;
3927 static int tg_throttle_down(struct task_group *tg, void *data)
3929 struct rq *rq = data;
3930 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3932 /* group is entering throttled state, stop time */
3933 if (!cfs_rq->throttle_count)
3934 cfs_rq->throttled_clock_task = rq_clock_task(rq);
3935 cfs_rq->throttle_count++;
3940 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
3942 struct rq *rq = rq_of(cfs_rq);
3943 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3944 struct sched_entity *se;
3945 long task_delta, dequeue = 1;
3948 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
3950 /* freeze hierarchy runnable averages while throttled */
3952 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
3955 task_delta = cfs_rq->h_nr_running;
3956 for_each_sched_entity(se) {
3957 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
3958 /* throttled entity or throttle-on-deactivate */
3963 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
3964 qcfs_rq->h_nr_running -= task_delta;
3966 if (qcfs_rq->load.weight)
3971 sub_nr_running(rq, task_delta);
3973 cfs_rq->throttled = 1;
3974 cfs_rq->throttled_clock = rq_clock(rq);
3975 raw_spin_lock(&cfs_b->lock);
3976 empty = list_empty(&cfs_b->throttled_cfs_rq);
3979 * Add to the _head_ of the list, so that an already-started
3980 * distribute_cfs_runtime will not see us
3982 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
3985 * If we're the first throttled task, make sure the bandwidth
3989 start_cfs_bandwidth(cfs_b);
3991 raw_spin_unlock(&cfs_b->lock);
3994 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
3996 struct rq *rq = rq_of(cfs_rq);
3997 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3998 struct sched_entity *se;
4002 se = cfs_rq->tg->se[cpu_of(rq)];
4004 cfs_rq->throttled = 0;
4006 update_rq_clock(rq);
4008 raw_spin_lock(&cfs_b->lock);
4009 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4010 list_del_rcu(&cfs_rq->throttled_list);
4011 raw_spin_unlock(&cfs_b->lock);
4013 /* update hierarchical throttle state */
4014 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4016 if (!cfs_rq->load.weight)
4019 task_delta = cfs_rq->h_nr_running;
4020 for_each_sched_entity(se) {
4024 cfs_rq = cfs_rq_of(se);
4026 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4027 cfs_rq->h_nr_running += task_delta;
4029 if (cfs_rq_throttled(cfs_rq))
4034 add_nr_running(rq, task_delta);
4036 /* determine whether we need to wake up potentially idle cpu */
4037 if (rq->curr == rq->idle && rq->cfs.nr_running)
4041 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
4042 u64 remaining, u64 expires)
4044 struct cfs_rq *cfs_rq;
4046 u64 starting_runtime = remaining;
4049 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4051 struct rq *rq = rq_of(cfs_rq);
4053 raw_spin_lock(&rq->lock);
4054 if (!cfs_rq_throttled(cfs_rq))
4057 runtime = -cfs_rq->runtime_remaining + 1;
4058 if (runtime > remaining)
4059 runtime = remaining;
4060 remaining -= runtime;
4062 cfs_rq->runtime_remaining += runtime;
4063 cfs_rq->runtime_expires = expires;
4065 /* we check whether we're throttled above */
4066 if (cfs_rq->runtime_remaining > 0)
4067 unthrottle_cfs_rq(cfs_rq);
4070 raw_spin_unlock(&rq->lock);
4077 return starting_runtime - remaining;
4081 * Responsible for refilling a task_group's bandwidth and unthrottling its
4082 * cfs_rqs as appropriate. If there has been no activity within the last
4083 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4084 * used to track this state.
4086 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
4088 u64 runtime, runtime_expires;
4091 /* no need to continue the timer with no bandwidth constraint */
4092 if (cfs_b->quota == RUNTIME_INF)
4093 goto out_deactivate;
4095 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4096 cfs_b->nr_periods += overrun;
4099 * idle depends on !throttled (for the case of a large deficit), and if
4100 * we're going inactive then everything else can be deferred
4102 if (cfs_b->idle && !throttled)
4103 goto out_deactivate;
4105 __refill_cfs_bandwidth_runtime(cfs_b);
4108 /* mark as potentially idle for the upcoming period */
4113 /* account preceding periods in which throttling occurred */
4114 cfs_b->nr_throttled += overrun;
4116 runtime_expires = cfs_b->runtime_expires;
4119 * This check is repeated as we are holding onto the new bandwidth while
4120 * we unthrottle. This can potentially race with an unthrottled group
4121 * trying to acquire new bandwidth from the global pool. This can result
4122 * in us over-using our runtime if it is all used during this loop, but
4123 * only by limited amounts in that extreme case.
4125 while (throttled && cfs_b->runtime > 0) {
4126 runtime = cfs_b->runtime;
4127 raw_spin_unlock(&cfs_b->lock);
4128 /* we can't nest cfs_b->lock while distributing bandwidth */
4129 runtime = distribute_cfs_runtime(cfs_b, runtime,
4131 raw_spin_lock(&cfs_b->lock);
4133 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4135 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4139 * While we are ensured activity in the period following an
4140 * unthrottle, this also covers the case in which the new bandwidth is
4141 * insufficient to cover the existing bandwidth deficit. (Forcing the
4142 * timer to remain active while there are any throttled entities.)
4152 /* a cfs_rq won't donate quota below this amount */
4153 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
4154 /* minimum remaining period time to redistribute slack quota */
4155 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
4156 /* how long we wait to gather additional slack before distributing */
4157 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
4160 * Are we near the end of the current quota period?
4162 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4163 * hrtimer base being cleared by hrtimer_start. In the case of
4164 * migrate_hrtimers, base is never cleared, so we are fine.
4166 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
4168 struct hrtimer *refresh_timer = &cfs_b->period_timer;
4171 /* if the call-back is running a quota refresh is already occurring */
4172 if (hrtimer_callback_running(refresh_timer))
4175 /* is a quota refresh about to occur? */
4176 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
4177 if (remaining < min_expire)
4183 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
4185 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
4187 /* if there's a quota refresh soon don't bother with slack */
4188 if (runtime_refresh_within(cfs_b, min_left))
4191 hrtimer_start(&cfs_b->slack_timer,
4192 ns_to_ktime(cfs_bandwidth_slack_period),
4196 /* we know any runtime found here is valid as update_curr() precedes return */
4197 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4199 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4200 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
4202 if (slack_runtime <= 0)
4205 raw_spin_lock(&cfs_b->lock);
4206 if (cfs_b->quota != RUNTIME_INF &&
4207 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
4208 cfs_b->runtime += slack_runtime;
4210 /* we are under rq->lock, defer unthrottling using a timer */
4211 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
4212 !list_empty(&cfs_b->throttled_cfs_rq))
4213 start_cfs_slack_bandwidth(cfs_b);
4215 raw_spin_unlock(&cfs_b->lock);
4217 /* even if it's not valid for return we don't want to try again */
4218 cfs_rq->runtime_remaining -= slack_runtime;
4221 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4223 if (!cfs_bandwidth_used())
4226 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
4229 __return_cfs_rq_runtime(cfs_rq);
4233 * This is done with a timer (instead of inline with bandwidth return) since
4234 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4236 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
4238 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
4241 /* confirm we're still not at a refresh boundary */
4242 raw_spin_lock(&cfs_b->lock);
4243 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
4244 raw_spin_unlock(&cfs_b->lock);
4248 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
4249 runtime = cfs_b->runtime;
4251 expires = cfs_b->runtime_expires;
4252 raw_spin_unlock(&cfs_b->lock);
4257 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
4259 raw_spin_lock(&cfs_b->lock);
4260 if (expires == cfs_b->runtime_expires)
4261 cfs_b->runtime -= min(runtime, cfs_b->runtime);
4262 raw_spin_unlock(&cfs_b->lock);
4266 * When a group wakes up we want to make sure that its quota is not already
4267 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4268 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4270 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
4272 if (!cfs_bandwidth_used())
4275 /* an active group must be handled by the update_curr()->put() path */
4276 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
4279 /* ensure the group is not already throttled */
4280 if (cfs_rq_throttled(cfs_rq))
4283 /* update runtime allocation */
4284 account_cfs_rq_runtime(cfs_rq, 0);
4285 if (cfs_rq->runtime_remaining <= 0)
4286 throttle_cfs_rq(cfs_rq);
4289 static void sync_throttle(struct task_group *tg, int cpu)
4291 struct cfs_rq *pcfs_rq, *cfs_rq;
4293 if (!cfs_bandwidth_used())
4299 cfs_rq = tg->cfs_rq[cpu];
4300 pcfs_rq = tg->parent->cfs_rq[cpu];
4302 cfs_rq->throttle_count = pcfs_rq->throttle_count;
4303 cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
4306 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4307 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4309 if (!cfs_bandwidth_used())
4312 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
4316 * it's possible for a throttled entity to be forced into a running
4317 * state (e.g. set_curr_task), in this case we're finished.
4319 if (cfs_rq_throttled(cfs_rq))
4322 throttle_cfs_rq(cfs_rq);
4326 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
4328 struct cfs_bandwidth *cfs_b =
4329 container_of(timer, struct cfs_bandwidth, slack_timer);
4331 do_sched_cfs_slack_timer(cfs_b);
4333 return HRTIMER_NORESTART;
4336 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
4338 struct cfs_bandwidth *cfs_b =
4339 container_of(timer, struct cfs_bandwidth, period_timer);
4343 raw_spin_lock(&cfs_b->lock);
4345 overrun = hrtimer_forward_now(timer, cfs_b->period);
4349 idle = do_sched_cfs_period_timer(cfs_b, overrun);
4352 cfs_b->period_active = 0;
4353 raw_spin_unlock(&cfs_b->lock);
4355 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
4358 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4360 raw_spin_lock_init(&cfs_b->lock);
4362 cfs_b->quota = RUNTIME_INF;
4363 cfs_b->period = ns_to_ktime(default_cfs_period());
4365 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4366 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
4367 cfs_b->period_timer.function = sched_cfs_period_timer;
4368 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4369 cfs_b->slack_timer.function = sched_cfs_slack_timer;
4372 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4374 cfs_rq->runtime_enabled = 0;
4375 INIT_LIST_HEAD(&cfs_rq->throttled_list);
4378 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4380 lockdep_assert_held(&cfs_b->lock);
4382 if (!cfs_b->period_active) {
4383 cfs_b->period_active = 1;
4384 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
4385 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
4389 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4391 /* init_cfs_bandwidth() was not called */
4392 if (!cfs_b->throttled_cfs_rq.next)
4395 hrtimer_cancel(&cfs_b->period_timer);
4396 hrtimer_cancel(&cfs_b->slack_timer);
4399 static void __maybe_unused update_runtime_enabled(struct rq *rq)
4401 struct cfs_rq *cfs_rq;
4403 for_each_leaf_cfs_rq(rq, cfs_rq) {
4404 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
4406 raw_spin_lock(&cfs_b->lock);
4407 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4408 raw_spin_unlock(&cfs_b->lock);
4412 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
4414 struct cfs_rq *cfs_rq;
4416 for_each_leaf_cfs_rq(rq, cfs_rq) {
4417 if (!cfs_rq->runtime_enabled)
4421 * clock_task is not advancing so we just need to make sure
4422 * there's some valid quota amount
4424 cfs_rq->runtime_remaining = 1;
4426 * Offline rq is schedulable till cpu is completely disabled
4427 * in take_cpu_down(), so we prevent new cfs throttling here.
4429 cfs_rq->runtime_enabled = 0;
4431 if (cfs_rq_throttled(cfs_rq))
4432 unthrottle_cfs_rq(cfs_rq);
4436 #else /* CONFIG_CFS_BANDWIDTH */
4437 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4439 return rq_clock_task(rq_of(cfs_rq));
4442 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
4443 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
4444 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
4445 static inline void sync_throttle(struct task_group *tg, int cpu) {}
4446 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4448 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4453 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4458 static inline int throttled_lb_pair(struct task_group *tg,
4459 int src_cpu, int dest_cpu)
4464 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4466 #ifdef CONFIG_FAIR_GROUP_SCHED
4467 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4470 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4474 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4475 static inline void update_runtime_enabled(struct rq *rq) {}
4476 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
4478 #endif /* CONFIG_CFS_BANDWIDTH */
4480 /**************************************************
4481 * CFS operations on tasks:
4484 #ifdef CONFIG_SCHED_HRTICK
4485 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
4487 struct sched_entity *se = &p->se;
4488 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4490 SCHED_WARN_ON(task_rq(p) != rq);
4492 if (rq->cfs.h_nr_running > 1) {
4493 u64 slice = sched_slice(cfs_rq, se);
4494 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
4495 s64 delta = slice - ran;
4502 hrtick_start(rq, delta);
4507 * called from enqueue/dequeue and updates the hrtick when the
4508 * current task is from our class and nr_running is low enough
4511 static void hrtick_update(struct rq *rq)
4513 struct task_struct *curr = rq->curr;
4515 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
4518 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
4519 hrtick_start_fair(rq, curr);
4521 #else /* !CONFIG_SCHED_HRTICK */
4523 hrtick_start_fair(struct rq *rq, struct task_struct *p)
4527 static inline void hrtick_update(struct rq *rq)
4533 * The enqueue_task method is called before nr_running is
4534 * increased. Here we update the fair scheduling stats and
4535 * then put the task into the rbtree:
4538 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4540 struct cfs_rq *cfs_rq;
4541 struct sched_entity *se = &p->se;
4543 for_each_sched_entity(se) {
4546 cfs_rq = cfs_rq_of(se);
4547 enqueue_entity(cfs_rq, se, flags);
4550 * end evaluation on encountering a throttled cfs_rq
4552 * note: in the case of encountering a throttled cfs_rq we will
4553 * post the final h_nr_running increment below.
4555 if (cfs_rq_throttled(cfs_rq))
4557 cfs_rq->h_nr_running++;
4559 flags = ENQUEUE_WAKEUP;
4562 for_each_sched_entity(se) {
4563 cfs_rq = cfs_rq_of(se);
4564 cfs_rq->h_nr_running++;
4566 if (cfs_rq_throttled(cfs_rq))
4569 update_load_avg(se, 1);
4570 update_cfs_shares(cfs_rq);
4574 add_nr_running(rq, 1);
4579 static void set_next_buddy(struct sched_entity *se);
4582 * The dequeue_task method is called before nr_running is
4583 * decreased. We remove the task from the rbtree and
4584 * update the fair scheduling stats:
4586 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4588 struct cfs_rq *cfs_rq;
4589 struct sched_entity *se = &p->se;
4590 int task_sleep = flags & DEQUEUE_SLEEP;
4592 for_each_sched_entity(se) {
4593 cfs_rq = cfs_rq_of(se);
4594 dequeue_entity(cfs_rq, se, flags);
4597 * end evaluation on encountering a throttled cfs_rq
4599 * note: in the case of encountering a throttled cfs_rq we will
4600 * post the final h_nr_running decrement below.
4602 if (cfs_rq_throttled(cfs_rq))
4604 cfs_rq->h_nr_running--;
4606 /* Don't dequeue parent if it has other entities besides us */
4607 if (cfs_rq->load.weight) {
4608 /* Avoid re-evaluating load for this entity: */
4609 se = parent_entity(se);
4611 * Bias pick_next to pick a task from this cfs_rq, as
4612 * p is sleeping when it is within its sched_slice.
4614 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
4618 flags |= DEQUEUE_SLEEP;
4621 for_each_sched_entity(se) {
4622 cfs_rq = cfs_rq_of(se);
4623 cfs_rq->h_nr_running--;
4625 if (cfs_rq_throttled(cfs_rq))
4628 update_load_avg(se, 1);
4629 update_cfs_shares(cfs_rq);
4633 sub_nr_running(rq, 1);
4640 /* Working cpumask for: load_balance, load_balance_newidle. */
4641 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
4642 DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
4644 #ifdef CONFIG_NO_HZ_COMMON
4646 * per rq 'load' arrray crap; XXX kill this.
4650 * The exact cpuload calculated at every tick would be:
4652 * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
4654 * If a cpu misses updates for n ticks (as it was idle) and update gets
4655 * called on the n+1-th tick when cpu may be busy, then we have:
4657 * load_n = (1 - 1/2^i)^n * load_0
4658 * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
4660 * decay_load_missed() below does efficient calculation of
4662 * load' = (1 - 1/2^i)^n * load
4664 * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
4665 * This allows us to precompute the above in said factors, thereby allowing the
4666 * reduction of an arbitrary n in O(log_2 n) steps. (See also
4667 * fixed_power_int())
4669 * The calculation is approximated on a 128 point scale.
4671 #define DEGRADE_SHIFT 7
4673 static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
4674 static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
4675 { 0, 0, 0, 0, 0, 0, 0, 0 },
4676 { 64, 32, 8, 0, 0, 0, 0, 0 },
4677 { 96, 72, 40, 12, 1, 0, 0, 0 },
4678 { 112, 98, 75, 43, 15, 1, 0, 0 },
4679 { 120, 112, 98, 76, 45, 16, 2, 0 }
4683 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
4684 * would be when CPU is idle and so we just decay the old load without
4685 * adding any new load.
4687 static unsigned long
4688 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
4692 if (!missed_updates)
4695 if (missed_updates >= degrade_zero_ticks[idx])
4699 return load >> missed_updates;
4701 while (missed_updates) {
4702 if (missed_updates % 2)
4703 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
4705 missed_updates >>= 1;
4710 #endif /* CONFIG_NO_HZ_COMMON */
4713 * __cpu_load_update - update the rq->cpu_load[] statistics
4714 * @this_rq: The rq to update statistics for
4715 * @this_load: The current load
4716 * @pending_updates: The number of missed updates
4718 * Update rq->cpu_load[] statistics. This function is usually called every
4719 * scheduler tick (TICK_NSEC).
4721 * This function computes a decaying average:
4723 * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
4725 * Because of NOHZ it might not get called on every tick which gives need for
4726 * the @pending_updates argument.
4728 * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
4729 * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
4730 * = A * (A * load[i]_n-2 + B) + B
4731 * = A * (A * (A * load[i]_n-3 + B) + B) + B
4732 * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
4733 * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
4734 * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
4735 * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
4737 * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
4738 * any change in load would have resulted in the tick being turned back on.
4740 * For regular NOHZ, this reduces to:
4742 * load[i]_n = (1 - 1/2^i)^n * load[i]_0
4744 * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
4747 static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
4748 unsigned long pending_updates)
4750 unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
4753 this_rq->nr_load_updates++;
4755 /* Update our load: */
4756 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
4757 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
4758 unsigned long old_load, new_load;
4760 /* scale is effectively 1 << i now, and >> i divides by scale */
4762 old_load = this_rq->cpu_load[i];
4763 #ifdef CONFIG_NO_HZ_COMMON
4764 old_load = decay_load_missed(old_load, pending_updates - 1, i);
4765 if (tickless_load) {
4766 old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
4768 * old_load can never be a negative value because a
4769 * decayed tickless_load cannot be greater than the
4770 * original tickless_load.
4772 old_load += tickless_load;
4775 new_load = this_load;
4777 * Round up the averaging division if load is increasing. This
4778 * prevents us from getting stuck on 9 if the load is 10, for
4781 if (new_load > old_load)
4782 new_load += scale - 1;
4784 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
4787 sched_avg_update(this_rq);
4790 /* Used instead of source_load when we know the type == 0 */
4791 static unsigned long weighted_cpuload(const int cpu)
4793 return cfs_rq_runnable_load_avg(&cpu_rq(cpu)->cfs);
4796 #ifdef CONFIG_NO_HZ_COMMON
4798 * There is no sane way to deal with nohz on smp when using jiffies because the
4799 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
4800 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
4802 * Therefore we need to avoid the delta approach from the regular tick when
4803 * possible since that would seriously skew the load calculation. This is why we
4804 * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
4805 * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
4806 * loop exit, nohz_idle_balance, nohz full exit...)
4808 * This means we might still be one tick off for nohz periods.
4811 static void cpu_load_update_nohz(struct rq *this_rq,
4812 unsigned long curr_jiffies,
4815 unsigned long pending_updates;
4817 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
4818 if (pending_updates) {
4819 this_rq->last_load_update_tick = curr_jiffies;
4821 * In the regular NOHZ case, we were idle, this means load 0.
4822 * In the NOHZ_FULL case, we were non-idle, we should consider
4823 * its weighted load.
4825 cpu_load_update(this_rq, load, pending_updates);
4830 * Called from nohz_idle_balance() to update the load ratings before doing the
4833 static void cpu_load_update_idle(struct rq *this_rq)
4836 * bail if there's load or we're actually up-to-date.
4838 if (weighted_cpuload(cpu_of(this_rq)))
4841 cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
4845 * Record CPU load on nohz entry so we know the tickless load to account
4846 * on nohz exit. cpu_load[0] happens then to be updated more frequently
4847 * than other cpu_load[idx] but it should be fine as cpu_load readers
4848 * shouldn't rely into synchronized cpu_load[*] updates.
4850 void cpu_load_update_nohz_start(void)
4852 struct rq *this_rq = this_rq();
4855 * This is all lockless but should be fine. If weighted_cpuload changes
4856 * concurrently we'll exit nohz. And cpu_load write can race with
4857 * cpu_load_update_idle() but both updater would be writing the same.
4859 this_rq->cpu_load[0] = weighted_cpuload(cpu_of(this_rq));
4863 * Account the tickless load in the end of a nohz frame.
4865 void cpu_load_update_nohz_stop(void)
4867 unsigned long curr_jiffies = READ_ONCE(jiffies);
4868 struct rq *this_rq = this_rq();
4871 if (curr_jiffies == this_rq->last_load_update_tick)
4874 load = weighted_cpuload(cpu_of(this_rq));
4875 raw_spin_lock(&this_rq->lock);
4876 update_rq_clock(this_rq);
4877 cpu_load_update_nohz(this_rq, curr_jiffies, load);
4878 raw_spin_unlock(&this_rq->lock);
4880 #else /* !CONFIG_NO_HZ_COMMON */
4881 static inline void cpu_load_update_nohz(struct rq *this_rq,
4882 unsigned long curr_jiffies,
4883 unsigned long load) { }
4884 #endif /* CONFIG_NO_HZ_COMMON */
4886 static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
4888 #ifdef CONFIG_NO_HZ_COMMON
4889 /* See the mess around cpu_load_update_nohz(). */
4890 this_rq->last_load_update_tick = READ_ONCE(jiffies);
4892 cpu_load_update(this_rq, load, 1);
4896 * Called from scheduler_tick()
4898 void cpu_load_update_active(struct rq *this_rq)
4900 unsigned long load = weighted_cpuload(cpu_of(this_rq));
4902 if (tick_nohz_tick_stopped())
4903 cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
4905 cpu_load_update_periodic(this_rq, load);
4909 * Return a low guess at the load of a migration-source cpu weighted
4910 * according to the scheduling class and "nice" value.
4912 * We want to under-estimate the load of migration sources, to
4913 * balance conservatively.
4915 static unsigned long source_load(int cpu, int type)
4917 struct rq *rq = cpu_rq(cpu);
4918 unsigned long total = weighted_cpuload(cpu);
4920 if (type == 0 || !sched_feat(LB_BIAS))
4923 return min(rq->cpu_load[type-1], total);
4927 * Return a high guess at the load of a migration-target cpu weighted
4928 * according to the scheduling class and "nice" value.
4930 static unsigned long target_load(int cpu, int type)
4932 struct rq *rq = cpu_rq(cpu);
4933 unsigned long total = weighted_cpuload(cpu);
4935 if (type == 0 || !sched_feat(LB_BIAS))
4938 return max(rq->cpu_load[type-1], total);
4941 static unsigned long capacity_of(int cpu)
4943 return cpu_rq(cpu)->cpu_capacity;
4946 static unsigned long capacity_orig_of(int cpu)
4948 return cpu_rq(cpu)->cpu_capacity_orig;
4951 static unsigned long cpu_avg_load_per_task(int cpu)
4953 struct rq *rq = cpu_rq(cpu);
4954 unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
4955 unsigned long load_avg = weighted_cpuload(cpu);
4958 return load_avg / nr_running;
4963 #ifdef CONFIG_FAIR_GROUP_SCHED
4965 * effective_load() calculates the load change as seen from the root_task_group
4967 * Adding load to a group doesn't make a group heavier, but can cause movement
4968 * of group shares between cpus. Assuming the shares were perfectly aligned one
4969 * can calculate the shift in shares.
4971 * Calculate the effective load difference if @wl is added (subtracted) to @tg
4972 * on this @cpu and results in a total addition (subtraction) of @wg to the
4973 * total group weight.
4975 * Given a runqueue weight distribution (rw_i) we can compute a shares
4976 * distribution (s_i) using:
4978 * s_i = rw_i / \Sum rw_j (1)
4980 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
4981 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
4982 * shares distribution (s_i):
4984 * rw_i = { 2, 4, 1, 0 }
4985 * s_i = { 2/7, 4/7, 1/7, 0 }
4987 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
4988 * task used to run on and the CPU the waker is running on), we need to
4989 * compute the effect of waking a task on either CPU and, in case of a sync
4990 * wakeup, compute the effect of the current task going to sleep.
4992 * So for a change of @wl to the local @cpu with an overall group weight change
4993 * of @wl we can compute the new shares distribution (s'_i) using:
4995 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
4997 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
4998 * differences in waking a task to CPU 0. The additional task changes the
4999 * weight and shares distributions like:
5001 * rw'_i = { 3, 4, 1, 0 }
5002 * s'_i = { 3/8, 4/8, 1/8, 0 }
5004 * We can then compute the difference in effective weight by using:
5006 * dw_i = S * (s'_i - s_i) (3)
5008 * Where 'S' is the group weight as seen by its parent.
5010 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
5011 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
5012 * 4/7) times the weight of the group.
5014 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5016 struct sched_entity *se = tg->se[cpu];
5018 if (!tg->parent) /* the trivial, non-cgroup case */
5021 for_each_sched_entity(se) {
5022 struct cfs_rq *cfs_rq = se->my_q;
5023 long W, w = cfs_rq_load_avg(cfs_rq);
5028 * W = @wg + \Sum rw_j
5030 W = wg + atomic_long_read(&tg->load_avg);
5032 /* Ensure \Sum rw_j >= rw_i */
5033 W -= cfs_rq->tg_load_avg_contrib;
5042 * wl = S * s'_i; see (2)
5045 wl = (w * (long)scale_load_down(tg->shares)) / W;
5047 wl = scale_load_down(tg->shares);
5050 * Per the above, wl is the new se->load.weight value; since
5051 * those are clipped to [MIN_SHARES, ...) do so now. See
5052 * calc_cfs_shares().
5054 if (wl < MIN_SHARES)
5058 * wl = dw_i = S * (s'_i - s_i); see (3)
5060 wl -= se->avg.load_avg;
5063 * Recursively apply this logic to all parent groups to compute
5064 * the final effective load change on the root group. Since
5065 * only the @tg group gets extra weight, all parent groups can
5066 * only redistribute existing shares. @wl is the shift in shares
5067 * resulting from this level per the above.
5076 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
5083 static void record_wakee(struct task_struct *p)
5086 * Only decay a single time; tasks that have less then 1 wakeup per
5087 * jiffy will not have built up many flips.
5089 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5090 current->wakee_flips >>= 1;
5091 current->wakee_flip_decay_ts = jiffies;
5094 if (current->last_wakee != p) {
5095 current->last_wakee = p;
5096 current->wakee_flips++;
5101 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5103 * A waker of many should wake a different task than the one last awakened
5104 * at a frequency roughly N times higher than one of its wakees.
5106 * In order to determine whether we should let the load spread vs consolidating
5107 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5108 * partner, and a factor of lls_size higher frequency in the other.
5110 * With both conditions met, we can be relatively sure that the relationship is
5111 * non-monogamous, with partner count exceeding socket size.
5113 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5114 * whatever is irrelevant, spread criteria is apparent partner count exceeds
5117 static int wake_wide(struct task_struct *p)
5119 unsigned int master = current->wakee_flips;
5120 unsigned int slave = p->wakee_flips;
5121 int factor = this_cpu_read(sd_llc_size);
5124 swap(master, slave);
5125 if (slave < factor || master < slave * factor)
5130 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5131 int prev_cpu, int sync)
5133 s64 this_load, load;
5134 s64 this_eff_load, prev_eff_load;
5136 struct task_group *tg;
5137 unsigned long weight;
5141 this_cpu = smp_processor_id();
5142 load = source_load(prev_cpu, idx);
5143 this_load = target_load(this_cpu, idx);
5146 * If sync wakeup then subtract the (maximum possible)
5147 * effect of the currently running task from the load
5148 * of the current CPU:
5151 tg = task_group(current);
5152 weight = current->se.avg.load_avg;
5154 this_load += effective_load(tg, this_cpu, -weight, -weight);
5155 load += effective_load(tg, prev_cpu, 0, -weight);
5159 weight = p->se.avg.load_avg;
5162 * In low-load situations, where prev_cpu is idle and this_cpu is idle
5163 * due to the sync cause above having dropped this_load to 0, we'll
5164 * always have an imbalance, but there's really nothing you can do
5165 * about that, so that's good too.
5167 * Otherwise check if either cpus are near enough in load to allow this
5168 * task to be woken on this_cpu.
5170 this_eff_load = 100;
5171 this_eff_load *= capacity_of(prev_cpu);
5173 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
5174 prev_eff_load *= capacity_of(this_cpu);
5176 if (this_load > 0) {
5177 this_eff_load *= this_load +
5178 effective_load(tg, this_cpu, weight, weight);
5180 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
5183 balanced = this_eff_load <= prev_eff_load;
5185 schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
5190 schedstat_inc(sd->ttwu_move_affine);
5191 schedstat_inc(p->se.statistics.nr_wakeups_affine);
5197 * find_idlest_group finds and returns the least busy CPU group within the
5200 static struct sched_group *
5201 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
5202 int this_cpu, int sd_flag)
5204 struct sched_group *idlest = NULL, *group = sd->groups;
5205 unsigned long min_load = ULONG_MAX, this_load = 0;
5206 int load_idx = sd->forkexec_idx;
5207 int imbalance = 100 + (sd->imbalance_pct-100)/2;
5209 if (sd_flag & SD_BALANCE_WAKE)
5210 load_idx = sd->wake_idx;
5213 unsigned long load, avg_load;
5217 /* Skip over this group if it has no CPUs allowed */
5218 if (!cpumask_intersects(sched_group_cpus(group),
5219 tsk_cpus_allowed(p)))
5222 local_group = cpumask_test_cpu(this_cpu,
5223 sched_group_cpus(group));
5225 /* Tally up the load of all CPUs in the group */
5228 for_each_cpu(i, sched_group_cpus(group)) {
5229 /* Bias balancing toward cpus of our domain */
5231 load = source_load(i, load_idx);
5233 load = target_load(i, load_idx);
5238 /* Adjust by relative CPU capacity of the group */
5239 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
5242 this_load = avg_load;
5243 } else if (avg_load < min_load) {
5244 min_load = avg_load;
5247 } while (group = group->next, group != sd->groups);
5249 if (!idlest || 100*this_load < imbalance*min_load)
5255 * find_idlest_cpu - find the idlest cpu among the cpus in group.
5258 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
5260 unsigned long load, min_load = ULONG_MAX;
5261 unsigned int min_exit_latency = UINT_MAX;
5262 u64 latest_idle_timestamp = 0;
5263 int least_loaded_cpu = this_cpu;
5264 int shallowest_idle_cpu = -1;
5267 /* Check if we have any choice: */
5268 if (group->group_weight == 1)
5269 return cpumask_first(sched_group_cpus(group));
5271 /* Traverse only the allowed CPUs */
5272 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
5274 struct rq *rq = cpu_rq(i);
5275 struct cpuidle_state *idle = idle_get_state(rq);
5276 if (idle && idle->exit_latency < min_exit_latency) {
5278 * We give priority to a CPU whose idle state
5279 * has the smallest exit latency irrespective
5280 * of any idle timestamp.
5282 min_exit_latency = idle->exit_latency;
5283 latest_idle_timestamp = rq->idle_stamp;
5284 shallowest_idle_cpu = i;
5285 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
5286 rq->idle_stamp > latest_idle_timestamp) {
5288 * If equal or no active idle state, then
5289 * the most recently idled CPU might have
5292 latest_idle_timestamp = rq->idle_stamp;
5293 shallowest_idle_cpu = i;
5295 } else if (shallowest_idle_cpu == -1) {
5296 load = weighted_cpuload(i);
5297 if (load < min_load || (load == min_load && i == this_cpu)) {
5299 least_loaded_cpu = i;
5304 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
5308 * Implement a for_each_cpu() variant that starts the scan at a given cpu
5309 * (@start), and wraps around.
5311 * This is used to scan for idle CPUs; such that not all CPUs looking for an
5312 * idle CPU find the same CPU. The down-side is that tasks tend to cycle
5313 * through the LLC domain.
5315 * Especially tbench is found sensitive to this.
5318 static int cpumask_next_wrap(int n, const struct cpumask *mask, int start, int *wrapped)
5323 next = find_next_bit(cpumask_bits(mask), nr_cpumask_bits, n+1);
5327 return nr_cpumask_bits;
5329 if (next >= nr_cpumask_bits) {
5339 #define for_each_cpu_wrap(cpu, mask, start, wrap) \
5340 for ((wrap) = 0, (cpu) = (start)-1; \
5341 (cpu) = cpumask_next_wrap((cpu), (mask), (start), &(wrap)), \
5342 (cpu) < nr_cpumask_bits; )
5344 #ifdef CONFIG_SCHED_SMT
5346 static inline void set_idle_cores(int cpu, int val)
5348 struct sched_domain_shared *sds;
5350 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
5352 WRITE_ONCE(sds->has_idle_cores, val);
5355 static inline bool test_idle_cores(int cpu, bool def)
5357 struct sched_domain_shared *sds;
5359 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
5361 return READ_ONCE(sds->has_idle_cores);
5367 * Scans the local SMT mask to see if the entire core is idle, and records this
5368 * information in sd_llc_shared->has_idle_cores.
5370 * Since SMT siblings share all cache levels, inspecting this limited remote
5371 * state should be fairly cheap.
5373 void __update_idle_core(struct rq *rq)
5375 int core = cpu_of(rq);
5379 if (test_idle_cores(core, true))
5382 for_each_cpu(cpu, cpu_smt_mask(core)) {
5390 set_idle_cores(core, 1);
5396 * Scan the entire LLC domain for idle cores; this dynamically switches off if
5397 * there are no idle cores left in the system; tracked through
5398 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
5400 static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
5402 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
5403 int core, cpu, wrap;
5405 if (!static_branch_likely(&sched_smt_present))
5408 if (!test_idle_cores(target, false))
5411 cpumask_and(cpus, sched_domain_span(sd), tsk_cpus_allowed(p));
5413 for_each_cpu_wrap(core, cpus, target, wrap) {
5416 for_each_cpu(cpu, cpu_smt_mask(core)) {
5417 cpumask_clear_cpu(cpu, cpus);
5427 * Failed to find an idle core; stop looking for one.
5429 set_idle_cores(target, 0);
5435 * Scan the local SMT mask for idle CPUs.
5437 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
5441 if (!static_branch_likely(&sched_smt_present))
5444 for_each_cpu(cpu, cpu_smt_mask(target)) {
5445 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
5454 #else /* CONFIG_SCHED_SMT */
5456 static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
5461 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
5466 #endif /* CONFIG_SCHED_SMT */
5469 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
5470 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
5471 * average idle time for this rq (as found in rq->avg_idle).
5473 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
5475 struct sched_domain *this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
5476 u64 avg_idle = this_rq()->avg_idle;
5477 u64 avg_cost = this_sd->avg_scan_cost;
5483 * Due to large variance we need a large fuzz factor; hackbench in
5484 * particularly is sensitive here.
5486 if ((avg_idle / 512) < avg_cost)
5489 time = local_clock();
5491 for_each_cpu_wrap(cpu, sched_domain_span(sd), target, wrap) {
5492 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
5498 time = local_clock() - time;
5499 cost = this_sd->avg_scan_cost;
5500 delta = (s64)(time - cost) / 8;
5501 this_sd->avg_scan_cost += delta;
5507 * Try and locate an idle core/thread in the LLC cache domain.
5509 static int select_idle_sibling(struct task_struct *p, int prev, int target)
5511 struct sched_domain *sd;
5514 if (idle_cpu(target))
5518 * If the previous cpu is cache affine and idle, don't be stupid.
5520 if (prev != target && cpus_share_cache(prev, target) && idle_cpu(prev))
5523 sd = rcu_dereference(per_cpu(sd_llc, target));
5527 i = select_idle_core(p, sd, target);
5528 if ((unsigned)i < nr_cpumask_bits)
5531 i = select_idle_cpu(p, sd, target);
5532 if ((unsigned)i < nr_cpumask_bits)
5535 i = select_idle_smt(p, sd, target);
5536 if ((unsigned)i < nr_cpumask_bits)
5543 * cpu_util returns the amount of capacity of a CPU that is used by CFS
5544 * tasks. The unit of the return value must be the one of capacity so we can
5545 * compare the utilization with the capacity of the CPU that is available for
5546 * CFS task (ie cpu_capacity).
5548 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
5549 * recent utilization of currently non-runnable tasks on a CPU. It represents
5550 * the amount of utilization of a CPU in the range [0..capacity_orig] where
5551 * capacity_orig is the cpu_capacity available at the highest frequency
5552 * (arch_scale_freq_capacity()).
5553 * The utilization of a CPU converges towards a sum equal to or less than the
5554 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
5555 * the running time on this CPU scaled by capacity_curr.
5557 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
5558 * higher than capacity_orig because of unfortunate rounding in
5559 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
5560 * the average stabilizes with the new running time. We need to check that the
5561 * utilization stays within the range of [0..capacity_orig] and cap it if
5562 * necessary. Without utilization capping, a group could be seen as overloaded
5563 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
5564 * available capacity. We allow utilization to overshoot capacity_curr (but not
5565 * capacity_orig) as it useful for predicting the capacity required after task
5566 * migrations (scheduler-driven DVFS).
5568 static int cpu_util(int cpu)
5570 unsigned long util = cpu_rq(cpu)->cfs.avg.util_avg;
5571 unsigned long capacity = capacity_orig_of(cpu);
5573 return (util >= capacity) ? capacity : util;
5576 static inline int task_util(struct task_struct *p)
5578 return p->se.avg.util_avg;
5582 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
5583 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
5585 * In that case WAKE_AFFINE doesn't make sense and we'll let
5586 * BALANCE_WAKE sort things out.
5588 static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
5590 long min_cap, max_cap;
5592 min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
5593 max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
5595 /* Minimum capacity is close to max, no need to abort wake_affine */
5596 if (max_cap - min_cap < max_cap >> 3)
5599 return min_cap * 1024 < task_util(p) * capacity_margin;
5603 * select_task_rq_fair: Select target runqueue for the waking task in domains
5604 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
5605 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
5607 * Balances load by selecting the idlest cpu in the idlest group, or under
5608 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
5610 * Returns the target cpu number.
5612 * preempt must be disabled.
5615 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
5617 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
5618 int cpu = smp_processor_id();
5619 int new_cpu = prev_cpu;
5620 int want_affine = 0;
5621 int sync = wake_flags & WF_SYNC;
5623 if (sd_flag & SD_BALANCE_WAKE) {
5625 want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu)
5626 && cpumask_test_cpu(cpu, tsk_cpus_allowed(p));
5630 for_each_domain(cpu, tmp) {
5631 if (!(tmp->flags & SD_LOAD_BALANCE))
5635 * If both cpu and prev_cpu are part of this domain,
5636 * cpu is a valid SD_WAKE_AFFINE target.
5638 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
5639 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
5644 if (tmp->flags & sd_flag)
5646 else if (!want_affine)
5651 sd = NULL; /* Prefer wake_affine over balance flags */
5652 if (cpu != prev_cpu && wake_affine(affine_sd, p, prev_cpu, sync))
5657 if (sd_flag & SD_BALANCE_WAKE) /* XXX always ? */
5658 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
5661 struct sched_group *group;
5664 if (!(sd->flags & sd_flag)) {
5669 group = find_idlest_group(sd, p, cpu, sd_flag);
5675 new_cpu = find_idlest_cpu(group, p, cpu);
5676 if (new_cpu == -1 || new_cpu == cpu) {
5677 /* Now try balancing at a lower domain level of cpu */
5682 /* Now try balancing at a lower domain level of new_cpu */
5684 weight = sd->span_weight;
5686 for_each_domain(cpu, tmp) {
5687 if (weight <= tmp->span_weight)
5689 if (tmp->flags & sd_flag)
5692 /* while loop will break here if sd == NULL */
5700 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
5701 * cfs_rq_of(p) references at time of call are still valid and identify the
5702 * previous cpu. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
5704 static void migrate_task_rq_fair(struct task_struct *p)
5707 * As blocked tasks retain absolute vruntime the migration needs to
5708 * deal with this by subtracting the old and adding the new
5709 * min_vruntime -- the latter is done by enqueue_entity() when placing
5710 * the task on the new runqueue.
5712 if (p->state == TASK_WAKING) {
5713 struct sched_entity *se = &p->se;
5714 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5717 #ifndef CONFIG_64BIT
5718 u64 min_vruntime_copy;
5721 min_vruntime_copy = cfs_rq->min_vruntime_copy;
5723 min_vruntime = cfs_rq->min_vruntime;
5724 } while (min_vruntime != min_vruntime_copy);
5726 min_vruntime = cfs_rq->min_vruntime;
5729 se->vruntime -= min_vruntime;
5733 * We are supposed to update the task to "current" time, then its up to date
5734 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
5735 * what current time is, so simply throw away the out-of-date time. This
5736 * will result in the wakee task is less decayed, but giving the wakee more
5737 * load sounds not bad.
5739 remove_entity_load_avg(&p->se);
5741 /* Tell new CPU we are migrated */
5742 p->se.avg.last_update_time = 0;
5744 /* We have migrated, no longer consider this task hot */
5745 p->se.exec_start = 0;
5748 static void task_dead_fair(struct task_struct *p)
5750 remove_entity_load_avg(&p->se);
5752 #endif /* CONFIG_SMP */
5754 static unsigned long
5755 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
5757 unsigned long gran = sysctl_sched_wakeup_granularity;
5760 * Since its curr running now, convert the gran from real-time
5761 * to virtual-time in his units.
5763 * By using 'se' instead of 'curr' we penalize light tasks, so
5764 * they get preempted easier. That is, if 'se' < 'curr' then
5765 * the resulting gran will be larger, therefore penalizing the
5766 * lighter, if otoh 'se' > 'curr' then the resulting gran will
5767 * be smaller, again penalizing the lighter task.
5769 * This is especially important for buddies when the leftmost
5770 * task is higher priority than the buddy.
5772 return calc_delta_fair(gran, se);
5776 * Should 'se' preempt 'curr'.
5790 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
5792 s64 gran, vdiff = curr->vruntime - se->vruntime;
5797 gran = wakeup_gran(curr, se);
5804 static void set_last_buddy(struct sched_entity *se)
5806 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
5809 for_each_sched_entity(se)
5810 cfs_rq_of(se)->last = se;
5813 static void set_next_buddy(struct sched_entity *se)
5815 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
5818 for_each_sched_entity(se)
5819 cfs_rq_of(se)->next = se;
5822 static void set_skip_buddy(struct sched_entity *se)
5824 for_each_sched_entity(se)
5825 cfs_rq_of(se)->skip = se;
5829 * Preempt the current task with a newly woken task if needed:
5831 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
5833 struct task_struct *curr = rq->curr;
5834 struct sched_entity *se = &curr->se, *pse = &p->se;
5835 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
5836 int scale = cfs_rq->nr_running >= sched_nr_latency;
5837 int next_buddy_marked = 0;
5839 if (unlikely(se == pse))
5843 * This is possible from callers such as attach_tasks(), in which we
5844 * unconditionally check_prempt_curr() after an enqueue (which may have
5845 * lead to a throttle). This both saves work and prevents false
5846 * next-buddy nomination below.
5848 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
5851 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
5852 set_next_buddy(pse);
5853 next_buddy_marked = 1;
5857 * We can come here with TIF_NEED_RESCHED already set from new task
5860 * Note: this also catches the edge-case of curr being in a throttled
5861 * group (e.g. via set_curr_task), since update_curr() (in the
5862 * enqueue of curr) will have resulted in resched being set. This
5863 * prevents us from potentially nominating it as a false LAST_BUDDY
5866 if (test_tsk_need_resched(curr))
5869 /* Idle tasks are by definition preempted by non-idle tasks. */
5870 if (unlikely(curr->policy == SCHED_IDLE) &&
5871 likely(p->policy != SCHED_IDLE))
5875 * Batch and idle tasks do not preempt non-idle tasks (their preemption
5876 * is driven by the tick):
5878 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
5881 find_matching_se(&se, &pse);
5882 update_curr(cfs_rq_of(se));
5884 if (wakeup_preempt_entity(se, pse) == 1) {
5886 * Bias pick_next to pick the sched entity that is
5887 * triggering this preemption.
5889 if (!next_buddy_marked)
5890 set_next_buddy(pse);
5899 * Only set the backward buddy when the current task is still
5900 * on the rq. This can happen when a wakeup gets interleaved
5901 * with schedule on the ->pre_schedule() or idle_balance()
5902 * point, either of which can * drop the rq lock.
5904 * Also, during early boot the idle thread is in the fair class,
5905 * for obvious reasons its a bad idea to schedule back to it.
5907 if (unlikely(!se->on_rq || curr == rq->idle))
5910 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
5914 static struct task_struct *
5915 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
5917 struct cfs_rq *cfs_rq = &rq->cfs;
5918 struct sched_entity *se;
5919 struct task_struct *p;
5923 #ifdef CONFIG_FAIR_GROUP_SCHED
5924 if (!cfs_rq->nr_running)
5927 if (prev->sched_class != &fair_sched_class)
5931 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
5932 * likely that a next task is from the same cgroup as the current.
5934 * Therefore attempt to avoid putting and setting the entire cgroup
5935 * hierarchy, only change the part that actually changes.
5939 struct sched_entity *curr = cfs_rq->curr;
5942 * Since we got here without doing put_prev_entity() we also
5943 * have to consider cfs_rq->curr. If it is still a runnable
5944 * entity, update_curr() will update its vruntime, otherwise
5945 * forget we've ever seen it.
5949 update_curr(cfs_rq);
5954 * This call to check_cfs_rq_runtime() will do the
5955 * throttle and dequeue its entity in the parent(s).
5956 * Therefore the 'simple' nr_running test will indeed
5959 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
5963 se = pick_next_entity(cfs_rq, curr);
5964 cfs_rq = group_cfs_rq(se);
5970 * Since we haven't yet done put_prev_entity and if the selected task
5971 * is a different task than we started out with, try and touch the
5972 * least amount of cfs_rqs.
5975 struct sched_entity *pse = &prev->se;
5977 while (!(cfs_rq = is_same_group(se, pse))) {
5978 int se_depth = se->depth;
5979 int pse_depth = pse->depth;
5981 if (se_depth <= pse_depth) {
5982 put_prev_entity(cfs_rq_of(pse), pse);
5983 pse = parent_entity(pse);
5985 if (se_depth >= pse_depth) {
5986 set_next_entity(cfs_rq_of(se), se);
5987 se = parent_entity(se);
5991 put_prev_entity(cfs_rq, pse);
5992 set_next_entity(cfs_rq, se);
5995 if (hrtick_enabled(rq))
5996 hrtick_start_fair(rq, p);
6003 if (!cfs_rq->nr_running)
6006 put_prev_task(rq, prev);
6009 se = pick_next_entity(cfs_rq, NULL);
6010 set_next_entity(cfs_rq, se);
6011 cfs_rq = group_cfs_rq(se);
6016 if (hrtick_enabled(rq))
6017 hrtick_start_fair(rq, p);
6023 * This is OK, because current is on_cpu, which avoids it being picked
6024 * for load-balance and preemption/IRQs are still disabled avoiding
6025 * further scheduler activity on it and we're being very careful to
6026 * re-start the picking loop.
6028 lockdep_unpin_lock(&rq->lock, cookie);
6029 new_tasks = idle_balance(rq);
6030 lockdep_repin_lock(&rq->lock, cookie);
6032 * Because idle_balance() releases (and re-acquires) rq->lock, it is
6033 * possible for any higher priority task to appear. In that case we
6034 * must re-start the pick_next_entity() loop.
6046 * Account for a descheduled task:
6048 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
6050 struct sched_entity *se = &prev->se;
6051 struct cfs_rq *cfs_rq;
6053 for_each_sched_entity(se) {
6054 cfs_rq = cfs_rq_of(se);
6055 put_prev_entity(cfs_rq, se);
6060 * sched_yield() is very simple
6062 * The magic of dealing with the ->skip buddy is in pick_next_entity.
6064 static void yield_task_fair(struct rq *rq)
6066 struct task_struct *curr = rq->curr;
6067 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6068 struct sched_entity *se = &curr->se;
6071 * Are we the only task in the tree?
6073 if (unlikely(rq->nr_running == 1))
6076 clear_buddies(cfs_rq, se);
6078 if (curr->policy != SCHED_BATCH) {
6079 update_rq_clock(rq);
6081 * Update run-time statistics of the 'current'.
6083 update_curr(cfs_rq);
6085 * Tell update_rq_clock() that we've just updated,
6086 * so we don't do microscopic update in schedule()
6087 * and double the fastpath cost.
6089 rq_clock_skip_update(rq, true);
6095 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
6097 struct sched_entity *se = &p->se;
6099 /* throttled hierarchies are not runnable */
6100 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
6103 /* Tell the scheduler that we'd really like pse to run next. */
6106 yield_task_fair(rq);
6112 /**************************************************
6113 * Fair scheduling class load-balancing methods.
6117 * The purpose of load-balancing is to achieve the same basic fairness the
6118 * per-cpu scheduler provides, namely provide a proportional amount of compute
6119 * time to each task. This is expressed in the following equation:
6121 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
6123 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
6124 * W_i,0 is defined as:
6126 * W_i,0 = \Sum_j w_i,j (2)
6128 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
6129 * is derived from the nice value as per sched_prio_to_weight[].
6131 * The weight average is an exponential decay average of the instantaneous
6134 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
6136 * C_i is the compute capacity of cpu i, typically it is the
6137 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
6138 * can also include other factors [XXX].
6140 * To achieve this balance we define a measure of imbalance which follows
6141 * directly from (1):
6143 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
6145 * We them move tasks around to minimize the imbalance. In the continuous
6146 * function space it is obvious this converges, in the discrete case we get
6147 * a few fun cases generally called infeasible weight scenarios.
6150 * - infeasible weights;
6151 * - local vs global optima in the discrete case. ]
6156 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
6157 * for all i,j solution, we create a tree of cpus that follows the hardware
6158 * topology where each level pairs two lower groups (or better). This results
6159 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
6160 * tree to only the first of the previous level and we decrease the frequency
6161 * of load-balance at each level inv. proportional to the number of cpus in
6167 * \Sum { --- * --- * 2^i } = O(n) (5)
6169 * `- size of each group
6170 * | | `- number of cpus doing load-balance
6172 * `- sum over all levels
6174 * Coupled with a limit on how many tasks we can migrate every balance pass,
6175 * this makes (5) the runtime complexity of the balancer.
6177 * An important property here is that each CPU is still (indirectly) connected
6178 * to every other cpu in at most O(log n) steps:
6180 * The adjacency matrix of the resulting graph is given by:
6183 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
6186 * And you'll find that:
6188 * A^(log_2 n)_i,j != 0 for all i,j (7)
6190 * Showing there's indeed a path between every cpu in at most O(log n) steps.
6191 * The task movement gives a factor of O(m), giving a convergence complexity
6194 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
6199 * In order to avoid CPUs going idle while there's still work to do, new idle
6200 * balancing is more aggressive and has the newly idle cpu iterate up the domain
6201 * tree itself instead of relying on other CPUs to bring it work.
6203 * This adds some complexity to both (5) and (8) but it reduces the total idle
6211 * Cgroups make a horror show out of (2), instead of a simple sum we get:
6214 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
6219 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
6221 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
6223 * The big problem is S_k, its a global sum needed to compute a local (W_i)
6226 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
6227 * rewrite all of this once again.]
6230 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
6232 enum fbq_type { regular, remote, all };
6234 #define LBF_ALL_PINNED 0x01
6235 #define LBF_NEED_BREAK 0x02
6236 #define LBF_DST_PINNED 0x04
6237 #define LBF_SOME_PINNED 0x08
6240 struct sched_domain *sd;
6248 struct cpumask *dst_grpmask;
6250 enum cpu_idle_type idle;
6252 /* The set of CPUs under consideration for load-balancing */
6253 struct cpumask *cpus;
6258 unsigned int loop_break;
6259 unsigned int loop_max;
6261 enum fbq_type fbq_type;
6262 struct list_head tasks;
6266 * Is this task likely cache-hot:
6268 static int task_hot(struct task_struct *p, struct lb_env *env)
6272 lockdep_assert_held(&env->src_rq->lock);
6274 if (p->sched_class != &fair_sched_class)
6277 if (unlikely(p->policy == SCHED_IDLE))
6281 * Buddy candidates are cache hot:
6283 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
6284 (&p->se == cfs_rq_of(&p->se)->next ||
6285 &p->se == cfs_rq_of(&p->se)->last))
6288 if (sysctl_sched_migration_cost == -1)
6290 if (sysctl_sched_migration_cost == 0)
6293 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
6295 return delta < (s64)sysctl_sched_migration_cost;
6298 #ifdef CONFIG_NUMA_BALANCING
6300 * Returns 1, if task migration degrades locality
6301 * Returns 0, if task migration improves locality i.e migration preferred.
6302 * Returns -1, if task migration is not affected by locality.
6304 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
6306 struct numa_group *numa_group = rcu_dereference(p->numa_group);
6307 unsigned long src_faults, dst_faults;
6308 int src_nid, dst_nid;
6310 if (!static_branch_likely(&sched_numa_balancing))
6313 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
6316 src_nid = cpu_to_node(env->src_cpu);
6317 dst_nid = cpu_to_node(env->dst_cpu);
6319 if (src_nid == dst_nid)
6322 /* Migrating away from the preferred node is always bad. */
6323 if (src_nid == p->numa_preferred_nid) {
6324 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
6330 /* Encourage migration to the preferred node. */
6331 if (dst_nid == p->numa_preferred_nid)
6335 src_faults = group_faults(p, src_nid);
6336 dst_faults = group_faults(p, dst_nid);
6338 src_faults = task_faults(p, src_nid);
6339 dst_faults = task_faults(p, dst_nid);
6342 return dst_faults < src_faults;
6346 static inline int migrate_degrades_locality(struct task_struct *p,
6354 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
6357 int can_migrate_task(struct task_struct *p, struct lb_env *env)
6361 lockdep_assert_held(&env->src_rq->lock);
6364 * We do not migrate tasks that are:
6365 * 1) throttled_lb_pair, or
6366 * 2) cannot be migrated to this CPU due to cpus_allowed, or
6367 * 3) running (obviously), or
6368 * 4) are cache-hot on their current CPU.
6370 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
6373 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
6376 schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
6378 env->flags |= LBF_SOME_PINNED;
6381 * Remember if this task can be migrated to any other cpu in
6382 * our sched_group. We may want to revisit it if we couldn't
6383 * meet load balance goals by pulling other tasks on src_cpu.
6385 * Also avoid computing new_dst_cpu if we have already computed
6386 * one in current iteration.
6388 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
6391 /* Prevent to re-select dst_cpu via env's cpus */
6392 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
6393 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
6394 env->flags |= LBF_DST_PINNED;
6395 env->new_dst_cpu = cpu;
6403 /* Record that we found atleast one task that could run on dst_cpu */
6404 env->flags &= ~LBF_ALL_PINNED;
6406 if (task_running(env->src_rq, p)) {
6407 schedstat_inc(p->se.statistics.nr_failed_migrations_running);
6412 * Aggressive migration if:
6413 * 1) destination numa is preferred
6414 * 2) task is cache cold, or
6415 * 3) too many balance attempts have failed.
6417 tsk_cache_hot = migrate_degrades_locality(p, env);
6418 if (tsk_cache_hot == -1)
6419 tsk_cache_hot = task_hot(p, env);
6421 if (tsk_cache_hot <= 0 ||
6422 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
6423 if (tsk_cache_hot == 1) {
6424 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
6425 schedstat_inc(p->se.statistics.nr_forced_migrations);
6430 schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
6435 * detach_task() -- detach the task for the migration specified in env
6437 static void detach_task(struct task_struct *p, struct lb_env *env)
6439 lockdep_assert_held(&env->src_rq->lock);
6441 p->on_rq = TASK_ON_RQ_MIGRATING;
6442 deactivate_task(env->src_rq, p, 0);
6443 set_task_cpu(p, env->dst_cpu);
6447 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
6448 * part of active balancing operations within "domain".
6450 * Returns a task if successful and NULL otherwise.
6452 static struct task_struct *detach_one_task(struct lb_env *env)
6454 struct task_struct *p, *n;
6456 lockdep_assert_held(&env->src_rq->lock);
6458 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
6459 if (!can_migrate_task(p, env))
6462 detach_task(p, env);
6465 * Right now, this is only the second place where
6466 * lb_gained[env->idle] is updated (other is detach_tasks)
6467 * so we can safely collect stats here rather than
6468 * inside detach_tasks().
6470 schedstat_inc(env->sd->lb_gained[env->idle]);
6476 static const unsigned int sched_nr_migrate_break = 32;
6479 * detach_tasks() -- tries to detach up to imbalance weighted load from
6480 * busiest_rq, as part of a balancing operation within domain "sd".
6482 * Returns number of detached tasks if successful and 0 otherwise.
6484 static int detach_tasks(struct lb_env *env)
6486 struct list_head *tasks = &env->src_rq->cfs_tasks;
6487 struct task_struct *p;
6491 lockdep_assert_held(&env->src_rq->lock);
6493 if (env->imbalance <= 0)
6496 while (!list_empty(tasks)) {
6498 * We don't want to steal all, otherwise we may be treated likewise,
6499 * which could at worst lead to a livelock crash.
6501 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
6504 p = list_first_entry(tasks, struct task_struct, se.group_node);
6507 /* We've more or less seen every task there is, call it quits */
6508 if (env->loop > env->loop_max)
6511 /* take a breather every nr_migrate tasks */
6512 if (env->loop > env->loop_break) {
6513 env->loop_break += sched_nr_migrate_break;
6514 env->flags |= LBF_NEED_BREAK;
6518 if (!can_migrate_task(p, env))
6521 load = task_h_load(p);
6523 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
6526 if ((load / 2) > env->imbalance)
6529 detach_task(p, env);
6530 list_add(&p->se.group_node, &env->tasks);
6533 env->imbalance -= load;
6535 #ifdef CONFIG_PREEMPT
6537 * NEWIDLE balancing is a source of latency, so preemptible
6538 * kernels will stop after the first task is detached to minimize
6539 * the critical section.
6541 if (env->idle == CPU_NEWLY_IDLE)
6546 * We only want to steal up to the prescribed amount of
6549 if (env->imbalance <= 0)
6554 list_move_tail(&p->se.group_node, tasks);
6558 * Right now, this is one of only two places we collect this stat
6559 * so we can safely collect detach_one_task() stats here rather
6560 * than inside detach_one_task().
6562 schedstat_add(env->sd->lb_gained[env->idle], detached);
6568 * attach_task() -- attach the task detached by detach_task() to its new rq.
6570 static void attach_task(struct rq *rq, struct task_struct *p)
6572 lockdep_assert_held(&rq->lock);
6574 BUG_ON(task_rq(p) != rq);
6575 activate_task(rq, p, 0);
6576 p->on_rq = TASK_ON_RQ_QUEUED;
6577 check_preempt_curr(rq, p, 0);
6581 * attach_one_task() -- attaches the task returned from detach_one_task() to
6584 static void attach_one_task(struct rq *rq, struct task_struct *p)
6586 raw_spin_lock(&rq->lock);
6588 raw_spin_unlock(&rq->lock);
6592 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
6595 static void attach_tasks(struct lb_env *env)
6597 struct list_head *tasks = &env->tasks;
6598 struct task_struct *p;
6600 raw_spin_lock(&env->dst_rq->lock);
6602 while (!list_empty(tasks)) {
6603 p = list_first_entry(tasks, struct task_struct, se.group_node);
6604 list_del_init(&p->se.group_node);
6606 attach_task(env->dst_rq, p);
6609 raw_spin_unlock(&env->dst_rq->lock);
6612 #ifdef CONFIG_FAIR_GROUP_SCHED
6613 static void update_blocked_averages(int cpu)
6615 struct rq *rq = cpu_rq(cpu);
6616 struct cfs_rq *cfs_rq;
6617 unsigned long flags;
6619 raw_spin_lock_irqsave(&rq->lock, flags);
6620 update_rq_clock(rq);
6623 * Iterates the task_group tree in a bottom up fashion, see
6624 * list_add_leaf_cfs_rq() for details.
6626 for_each_leaf_cfs_rq(rq, cfs_rq) {
6627 /* throttled entities do not contribute to load */
6628 if (throttled_hierarchy(cfs_rq))
6631 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true))
6632 update_tg_load_avg(cfs_rq, 0);
6634 raw_spin_unlock_irqrestore(&rq->lock, flags);
6638 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
6639 * This needs to be done in a top-down fashion because the load of a child
6640 * group is a fraction of its parents load.
6642 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
6644 struct rq *rq = rq_of(cfs_rq);
6645 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
6646 unsigned long now = jiffies;
6649 if (cfs_rq->last_h_load_update == now)
6652 cfs_rq->h_load_next = NULL;
6653 for_each_sched_entity(se) {
6654 cfs_rq = cfs_rq_of(se);
6655 cfs_rq->h_load_next = se;
6656 if (cfs_rq->last_h_load_update == now)
6661 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
6662 cfs_rq->last_h_load_update = now;
6665 while ((se = cfs_rq->h_load_next) != NULL) {
6666 load = cfs_rq->h_load;
6667 load = div64_ul(load * se->avg.load_avg,
6668 cfs_rq_load_avg(cfs_rq) + 1);
6669 cfs_rq = group_cfs_rq(se);
6670 cfs_rq->h_load = load;
6671 cfs_rq->last_h_load_update = now;
6675 static unsigned long task_h_load(struct task_struct *p)
6677 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6679 update_cfs_rq_h_load(cfs_rq);
6680 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
6681 cfs_rq_load_avg(cfs_rq) + 1);
6684 static inline void update_blocked_averages(int cpu)
6686 struct rq *rq = cpu_rq(cpu);
6687 struct cfs_rq *cfs_rq = &rq->cfs;
6688 unsigned long flags;
6690 raw_spin_lock_irqsave(&rq->lock, flags);
6691 update_rq_clock(rq);
6692 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq, true);
6693 raw_spin_unlock_irqrestore(&rq->lock, flags);
6696 static unsigned long task_h_load(struct task_struct *p)
6698 return p->se.avg.load_avg;
6702 /********** Helpers for find_busiest_group ************************/
6711 * sg_lb_stats - stats of a sched_group required for load_balancing
6713 struct sg_lb_stats {
6714 unsigned long avg_load; /*Avg load across the CPUs of the group */
6715 unsigned long group_load; /* Total load over the CPUs of the group */
6716 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
6717 unsigned long load_per_task;
6718 unsigned long group_capacity;
6719 unsigned long group_util; /* Total utilization of the group */
6720 unsigned int sum_nr_running; /* Nr tasks running in the group */
6721 unsigned int idle_cpus;
6722 unsigned int group_weight;
6723 enum group_type group_type;
6724 int group_no_capacity;
6725 #ifdef CONFIG_NUMA_BALANCING
6726 unsigned int nr_numa_running;
6727 unsigned int nr_preferred_running;
6732 * sd_lb_stats - Structure to store the statistics of a sched_domain
6733 * during load balancing.
6735 struct sd_lb_stats {
6736 struct sched_group *busiest; /* Busiest group in this sd */
6737 struct sched_group *local; /* Local group in this sd */
6738 unsigned long total_load; /* Total load of all groups in sd */
6739 unsigned long total_capacity; /* Total capacity of all groups in sd */
6740 unsigned long avg_load; /* Average load across all groups in sd */
6742 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
6743 struct sg_lb_stats local_stat; /* Statistics of the local group */
6746 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
6749 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
6750 * local_stat because update_sg_lb_stats() does a full clear/assignment.
6751 * We must however clear busiest_stat::avg_load because
6752 * update_sd_pick_busiest() reads this before assignment.
6754 *sds = (struct sd_lb_stats){
6758 .total_capacity = 0UL,
6761 .sum_nr_running = 0,
6762 .group_type = group_other,
6768 * get_sd_load_idx - Obtain the load index for a given sched domain.
6769 * @sd: The sched_domain whose load_idx is to be obtained.
6770 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
6772 * Return: The load index.
6774 static inline int get_sd_load_idx(struct sched_domain *sd,
6775 enum cpu_idle_type idle)
6781 load_idx = sd->busy_idx;
6784 case CPU_NEWLY_IDLE:
6785 load_idx = sd->newidle_idx;
6788 load_idx = sd->idle_idx;
6795 static unsigned long scale_rt_capacity(int cpu)
6797 struct rq *rq = cpu_rq(cpu);
6798 u64 total, used, age_stamp, avg;
6802 * Since we're reading these variables without serialization make sure
6803 * we read them once before doing sanity checks on them.
6805 age_stamp = READ_ONCE(rq->age_stamp);
6806 avg = READ_ONCE(rq->rt_avg);
6807 delta = __rq_clock_broken(rq) - age_stamp;
6809 if (unlikely(delta < 0))
6812 total = sched_avg_period() + delta;
6814 used = div_u64(avg, total);
6816 if (likely(used < SCHED_CAPACITY_SCALE))
6817 return SCHED_CAPACITY_SCALE - used;
6822 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
6824 unsigned long capacity = arch_scale_cpu_capacity(sd, cpu);
6825 struct sched_group *sdg = sd->groups;
6827 cpu_rq(cpu)->cpu_capacity_orig = capacity;
6829 capacity *= scale_rt_capacity(cpu);
6830 capacity >>= SCHED_CAPACITY_SHIFT;
6835 cpu_rq(cpu)->cpu_capacity = capacity;
6836 sdg->sgc->capacity = capacity;
6839 void update_group_capacity(struct sched_domain *sd, int cpu)
6841 struct sched_domain *child = sd->child;
6842 struct sched_group *group, *sdg = sd->groups;
6843 unsigned long capacity;
6844 unsigned long interval;
6846 interval = msecs_to_jiffies(sd->balance_interval);
6847 interval = clamp(interval, 1UL, max_load_balance_interval);
6848 sdg->sgc->next_update = jiffies + interval;
6851 update_cpu_capacity(sd, cpu);
6857 if (child->flags & SD_OVERLAP) {
6859 * SD_OVERLAP domains cannot assume that child groups
6860 * span the current group.
6863 for_each_cpu(cpu, sched_group_cpus(sdg)) {
6864 struct sched_group_capacity *sgc;
6865 struct rq *rq = cpu_rq(cpu);
6868 * build_sched_domains() -> init_sched_groups_capacity()
6869 * gets here before we've attached the domains to the
6872 * Use capacity_of(), which is set irrespective of domains
6873 * in update_cpu_capacity().
6875 * This avoids capacity from being 0 and
6876 * causing divide-by-zero issues on boot.
6878 if (unlikely(!rq->sd)) {
6879 capacity += capacity_of(cpu);
6883 sgc = rq->sd->groups->sgc;
6884 capacity += sgc->capacity;
6888 * !SD_OVERLAP domains can assume that child groups
6889 * span the current group.
6892 group = child->groups;
6894 capacity += group->sgc->capacity;
6895 group = group->next;
6896 } while (group != child->groups);
6899 sdg->sgc->capacity = capacity;
6903 * Check whether the capacity of the rq has been noticeably reduced by side
6904 * activity. The imbalance_pct is used for the threshold.
6905 * Return true is the capacity is reduced
6908 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
6910 return ((rq->cpu_capacity * sd->imbalance_pct) <
6911 (rq->cpu_capacity_orig * 100));
6915 * Group imbalance indicates (and tries to solve) the problem where balancing
6916 * groups is inadequate due to tsk_cpus_allowed() constraints.
6918 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
6919 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
6922 * { 0 1 2 3 } { 4 5 6 7 }
6925 * If we were to balance group-wise we'd place two tasks in the first group and
6926 * two tasks in the second group. Clearly this is undesired as it will overload
6927 * cpu 3 and leave one of the cpus in the second group unused.
6929 * The current solution to this issue is detecting the skew in the first group
6930 * by noticing the lower domain failed to reach balance and had difficulty
6931 * moving tasks due to affinity constraints.
6933 * When this is so detected; this group becomes a candidate for busiest; see
6934 * update_sd_pick_busiest(). And calculate_imbalance() and
6935 * find_busiest_group() avoid some of the usual balance conditions to allow it
6936 * to create an effective group imbalance.
6938 * This is a somewhat tricky proposition since the next run might not find the
6939 * group imbalance and decide the groups need to be balanced again. A most
6940 * subtle and fragile situation.
6943 static inline int sg_imbalanced(struct sched_group *group)
6945 return group->sgc->imbalance;
6949 * group_has_capacity returns true if the group has spare capacity that could
6950 * be used by some tasks.
6951 * We consider that a group has spare capacity if the * number of task is
6952 * smaller than the number of CPUs or if the utilization is lower than the
6953 * available capacity for CFS tasks.
6954 * For the latter, we use a threshold to stabilize the state, to take into
6955 * account the variance of the tasks' load and to return true if the available
6956 * capacity in meaningful for the load balancer.
6957 * As an example, an available capacity of 1% can appear but it doesn't make
6958 * any benefit for the load balance.
6961 group_has_capacity(struct lb_env *env, struct sg_lb_stats *sgs)
6963 if (sgs->sum_nr_running < sgs->group_weight)
6966 if ((sgs->group_capacity * 100) >
6967 (sgs->group_util * env->sd->imbalance_pct))
6974 * group_is_overloaded returns true if the group has more tasks than it can
6976 * group_is_overloaded is not equals to !group_has_capacity because a group
6977 * with the exact right number of tasks, has no more spare capacity but is not
6978 * overloaded so both group_has_capacity and group_is_overloaded return
6982 group_is_overloaded(struct lb_env *env, struct sg_lb_stats *sgs)
6984 if (sgs->sum_nr_running <= sgs->group_weight)
6987 if ((sgs->group_capacity * 100) <
6988 (sgs->group_util * env->sd->imbalance_pct))
6995 group_type group_classify(struct sched_group *group,
6996 struct sg_lb_stats *sgs)
6998 if (sgs->group_no_capacity)
6999 return group_overloaded;
7001 if (sg_imbalanced(group))
7002 return group_imbalanced;
7008 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
7009 * @env: The load balancing environment.
7010 * @group: sched_group whose statistics are to be updated.
7011 * @load_idx: Load index of sched_domain of this_cpu for load calc.
7012 * @local_group: Does group contain this_cpu.
7013 * @sgs: variable to hold the statistics for this group.
7014 * @overload: Indicate more than one runnable task for any CPU.
7016 static inline void update_sg_lb_stats(struct lb_env *env,
7017 struct sched_group *group, int load_idx,
7018 int local_group, struct sg_lb_stats *sgs,
7024 memset(sgs, 0, sizeof(*sgs));
7026 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
7027 struct rq *rq = cpu_rq(i);
7029 /* Bias balancing toward cpus of our domain */
7031 load = target_load(i, load_idx);
7033 load = source_load(i, load_idx);
7035 sgs->group_load += load;
7036 sgs->group_util += cpu_util(i);
7037 sgs->sum_nr_running += rq->cfs.h_nr_running;
7039 nr_running = rq->nr_running;
7043 #ifdef CONFIG_NUMA_BALANCING
7044 sgs->nr_numa_running += rq->nr_numa_running;
7045 sgs->nr_preferred_running += rq->nr_preferred_running;
7047 sgs->sum_weighted_load += weighted_cpuload(i);
7049 * No need to call idle_cpu() if nr_running is not 0
7051 if (!nr_running && idle_cpu(i))
7055 /* Adjust by relative CPU capacity of the group */
7056 sgs->group_capacity = group->sgc->capacity;
7057 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
7059 if (sgs->sum_nr_running)
7060 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
7062 sgs->group_weight = group->group_weight;
7064 sgs->group_no_capacity = group_is_overloaded(env, sgs);
7065 sgs->group_type = group_classify(group, sgs);
7069 * update_sd_pick_busiest - return 1 on busiest group
7070 * @env: The load balancing environment.
7071 * @sds: sched_domain statistics
7072 * @sg: sched_group candidate to be checked for being the busiest
7073 * @sgs: sched_group statistics
7075 * Determine if @sg is a busier group than the previously selected
7078 * Return: %true if @sg is a busier group than the previously selected
7079 * busiest group. %false otherwise.
7081 static bool update_sd_pick_busiest(struct lb_env *env,
7082 struct sd_lb_stats *sds,
7083 struct sched_group *sg,
7084 struct sg_lb_stats *sgs)
7086 struct sg_lb_stats *busiest = &sds->busiest_stat;
7088 if (sgs->group_type > busiest->group_type)
7091 if (sgs->group_type < busiest->group_type)
7094 if (sgs->avg_load <= busiest->avg_load)
7097 /* This is the busiest node in its class. */
7098 if (!(env->sd->flags & SD_ASYM_PACKING))
7101 /* No ASYM_PACKING if target cpu is already busy */
7102 if (env->idle == CPU_NOT_IDLE)
7105 * ASYM_PACKING needs to move all the work to the lowest
7106 * numbered CPUs in the group, therefore mark all groups
7107 * higher than ourself as busy.
7109 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
7113 /* Prefer to move from highest possible cpu's work */
7114 if (group_first_cpu(sds->busiest) < group_first_cpu(sg))
7121 #ifdef CONFIG_NUMA_BALANCING
7122 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
7124 if (sgs->sum_nr_running > sgs->nr_numa_running)
7126 if (sgs->sum_nr_running > sgs->nr_preferred_running)
7131 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
7133 if (rq->nr_running > rq->nr_numa_running)
7135 if (rq->nr_running > rq->nr_preferred_running)
7140 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
7145 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
7149 #endif /* CONFIG_NUMA_BALANCING */
7152 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
7153 * @env: The load balancing environment.
7154 * @sds: variable to hold the statistics for this sched_domain.
7156 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
7158 struct sched_domain *child = env->sd->child;
7159 struct sched_group *sg = env->sd->groups;
7160 struct sg_lb_stats tmp_sgs;
7161 int load_idx, prefer_sibling = 0;
7162 bool overload = false;
7164 if (child && child->flags & SD_PREFER_SIBLING)
7167 load_idx = get_sd_load_idx(env->sd, env->idle);
7170 struct sg_lb_stats *sgs = &tmp_sgs;
7173 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
7176 sgs = &sds->local_stat;
7178 if (env->idle != CPU_NEWLY_IDLE ||
7179 time_after_eq(jiffies, sg->sgc->next_update))
7180 update_group_capacity(env->sd, env->dst_cpu);
7183 update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
7190 * In case the child domain prefers tasks go to siblings
7191 * first, lower the sg capacity so that we'll try
7192 * and move all the excess tasks away. We lower the capacity
7193 * of a group only if the local group has the capacity to fit
7194 * these excess tasks. The extra check prevents the case where
7195 * you always pull from the heaviest group when it is already
7196 * under-utilized (possible with a large weight task outweighs
7197 * the tasks on the system).
7199 if (prefer_sibling && sds->local &&
7200 group_has_capacity(env, &sds->local_stat) &&
7201 (sgs->sum_nr_running > 1)) {
7202 sgs->group_no_capacity = 1;
7203 sgs->group_type = group_classify(sg, sgs);
7206 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
7208 sds->busiest_stat = *sgs;
7212 /* Now, start updating sd_lb_stats */
7213 sds->total_load += sgs->group_load;
7214 sds->total_capacity += sgs->group_capacity;
7217 } while (sg != env->sd->groups);
7219 if (env->sd->flags & SD_NUMA)
7220 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
7222 if (!env->sd->parent) {
7223 /* update overload indicator if we are at root domain */
7224 if (env->dst_rq->rd->overload != overload)
7225 env->dst_rq->rd->overload = overload;
7231 * check_asym_packing - Check to see if the group is packed into the
7234 * This is primarily intended to used at the sibling level. Some
7235 * cores like POWER7 prefer to use lower numbered SMT threads. In the
7236 * case of POWER7, it can move to lower SMT modes only when higher
7237 * threads are idle. When in lower SMT modes, the threads will
7238 * perform better since they share less core resources. Hence when we
7239 * have idle threads, we want them to be the higher ones.
7241 * This packing function is run on idle threads. It checks to see if
7242 * the busiest CPU in this domain (core in the P7 case) has a higher
7243 * CPU number than the packing function is being run on. Here we are
7244 * assuming lower CPU number will be equivalent to lower a SMT thread
7247 * Return: 1 when packing is required and a task should be moved to
7248 * this CPU. The amount of the imbalance is returned in *imbalance.
7250 * @env: The load balancing environment.
7251 * @sds: Statistics of the sched_domain which is to be packed
7253 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
7257 if (!(env->sd->flags & SD_ASYM_PACKING))
7260 if (env->idle == CPU_NOT_IDLE)
7266 busiest_cpu = group_first_cpu(sds->busiest);
7267 if (env->dst_cpu > busiest_cpu)
7270 env->imbalance = DIV_ROUND_CLOSEST(
7271 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
7272 SCHED_CAPACITY_SCALE);
7278 * fix_small_imbalance - Calculate the minor imbalance that exists
7279 * amongst the groups of a sched_domain, during
7281 * @env: The load balancing environment.
7282 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
7285 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
7287 unsigned long tmp, capa_now = 0, capa_move = 0;
7288 unsigned int imbn = 2;
7289 unsigned long scaled_busy_load_per_task;
7290 struct sg_lb_stats *local, *busiest;
7292 local = &sds->local_stat;
7293 busiest = &sds->busiest_stat;
7295 if (!local->sum_nr_running)
7296 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
7297 else if (busiest->load_per_task > local->load_per_task)
7300 scaled_busy_load_per_task =
7301 (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
7302 busiest->group_capacity;
7304 if (busiest->avg_load + scaled_busy_load_per_task >=
7305 local->avg_load + (scaled_busy_load_per_task * imbn)) {
7306 env->imbalance = busiest->load_per_task;
7311 * OK, we don't have enough imbalance to justify moving tasks,
7312 * however we may be able to increase total CPU capacity used by
7316 capa_now += busiest->group_capacity *
7317 min(busiest->load_per_task, busiest->avg_load);
7318 capa_now += local->group_capacity *
7319 min(local->load_per_task, local->avg_load);
7320 capa_now /= SCHED_CAPACITY_SCALE;
7322 /* Amount of load we'd subtract */
7323 if (busiest->avg_load > scaled_busy_load_per_task) {
7324 capa_move += busiest->group_capacity *
7325 min(busiest->load_per_task,
7326 busiest->avg_load - scaled_busy_load_per_task);
7329 /* Amount of load we'd add */
7330 if (busiest->avg_load * busiest->group_capacity <
7331 busiest->load_per_task * SCHED_CAPACITY_SCALE) {
7332 tmp = (busiest->avg_load * busiest->group_capacity) /
7333 local->group_capacity;
7335 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
7336 local->group_capacity;
7338 capa_move += local->group_capacity *
7339 min(local->load_per_task, local->avg_load + tmp);
7340 capa_move /= SCHED_CAPACITY_SCALE;
7342 /* Move if we gain throughput */
7343 if (capa_move > capa_now)
7344 env->imbalance = busiest->load_per_task;
7348 * calculate_imbalance - Calculate the amount of imbalance present within the
7349 * groups of a given sched_domain during load balance.
7350 * @env: load balance environment
7351 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
7353 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
7355 unsigned long max_pull, load_above_capacity = ~0UL;
7356 struct sg_lb_stats *local, *busiest;
7358 local = &sds->local_stat;
7359 busiest = &sds->busiest_stat;
7361 if (busiest->group_type == group_imbalanced) {
7363 * In the group_imb case we cannot rely on group-wide averages
7364 * to ensure cpu-load equilibrium, look at wider averages. XXX
7366 busiest->load_per_task =
7367 min(busiest->load_per_task, sds->avg_load);
7371 * Avg load of busiest sg can be less and avg load of local sg can
7372 * be greater than avg load across all sgs of sd because avg load
7373 * factors in sg capacity and sgs with smaller group_type are
7374 * skipped when updating the busiest sg:
7376 if (busiest->avg_load <= sds->avg_load ||
7377 local->avg_load >= sds->avg_load) {
7379 return fix_small_imbalance(env, sds);
7383 * If there aren't any idle cpus, avoid creating some.
7385 if (busiest->group_type == group_overloaded &&
7386 local->group_type == group_overloaded) {
7387 load_above_capacity = busiest->sum_nr_running * SCHED_CAPACITY_SCALE;
7388 if (load_above_capacity > busiest->group_capacity) {
7389 load_above_capacity -= busiest->group_capacity;
7390 load_above_capacity *= scale_load_down(NICE_0_LOAD);
7391 load_above_capacity /= busiest->group_capacity;
7393 load_above_capacity = ~0UL;
7397 * We're trying to get all the cpus to the average_load, so we don't
7398 * want to push ourselves above the average load, nor do we wish to
7399 * reduce the max loaded cpu below the average load. At the same time,
7400 * we also don't want to reduce the group load below the group
7401 * capacity. Thus we look for the minimum possible imbalance.
7403 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
7405 /* How much load to actually move to equalise the imbalance */
7406 env->imbalance = min(
7407 max_pull * busiest->group_capacity,
7408 (sds->avg_load - local->avg_load) * local->group_capacity
7409 ) / SCHED_CAPACITY_SCALE;
7412 * if *imbalance is less than the average load per runnable task
7413 * there is no guarantee that any tasks will be moved so we'll have
7414 * a think about bumping its value to force at least one task to be
7417 if (env->imbalance < busiest->load_per_task)
7418 return fix_small_imbalance(env, sds);
7421 /******* find_busiest_group() helpers end here *********************/
7424 * find_busiest_group - Returns the busiest group within the sched_domain
7425 * if there is an imbalance.
7427 * Also calculates the amount of weighted load which should be moved
7428 * to restore balance.
7430 * @env: The load balancing environment.
7432 * Return: - The busiest group if imbalance exists.
7434 static struct sched_group *find_busiest_group(struct lb_env *env)
7436 struct sg_lb_stats *local, *busiest;
7437 struct sd_lb_stats sds;
7439 init_sd_lb_stats(&sds);
7442 * Compute the various statistics relavent for load balancing at
7445 update_sd_lb_stats(env, &sds);
7446 local = &sds.local_stat;
7447 busiest = &sds.busiest_stat;
7449 /* ASYM feature bypasses nice load balance check */
7450 if (check_asym_packing(env, &sds))
7453 /* There is no busy sibling group to pull tasks from */
7454 if (!sds.busiest || busiest->sum_nr_running == 0)
7457 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
7458 / sds.total_capacity;
7461 * If the busiest group is imbalanced the below checks don't
7462 * work because they assume all things are equal, which typically
7463 * isn't true due to cpus_allowed constraints and the like.
7465 if (busiest->group_type == group_imbalanced)
7468 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
7469 if (env->idle == CPU_NEWLY_IDLE && group_has_capacity(env, local) &&
7470 busiest->group_no_capacity)
7474 * If the local group is busier than the selected busiest group
7475 * don't try and pull any tasks.
7477 if (local->avg_load >= busiest->avg_load)
7481 * Don't pull any tasks if this group is already above the domain
7484 if (local->avg_load >= sds.avg_load)
7487 if (env->idle == CPU_IDLE) {
7489 * This cpu is idle. If the busiest group is not overloaded
7490 * and there is no imbalance between this and busiest group
7491 * wrt idle cpus, it is balanced. The imbalance becomes
7492 * significant if the diff is greater than 1 otherwise we
7493 * might end up to just move the imbalance on another group
7495 if ((busiest->group_type != group_overloaded) &&
7496 (local->idle_cpus <= (busiest->idle_cpus + 1)))
7500 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
7501 * imbalance_pct to be conservative.
7503 if (100 * busiest->avg_load <=
7504 env->sd->imbalance_pct * local->avg_load)
7509 /* Looks like there is an imbalance. Compute it */
7510 calculate_imbalance(env, &sds);
7519 * find_busiest_queue - find the busiest runqueue among the cpus in group.
7521 static struct rq *find_busiest_queue(struct lb_env *env,
7522 struct sched_group *group)
7524 struct rq *busiest = NULL, *rq;
7525 unsigned long busiest_load = 0, busiest_capacity = 1;
7528 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
7529 unsigned long capacity, wl;
7533 rt = fbq_classify_rq(rq);
7536 * We classify groups/runqueues into three groups:
7537 * - regular: there are !numa tasks
7538 * - remote: there are numa tasks that run on the 'wrong' node
7539 * - all: there is no distinction
7541 * In order to avoid migrating ideally placed numa tasks,
7542 * ignore those when there's better options.
7544 * If we ignore the actual busiest queue to migrate another
7545 * task, the next balance pass can still reduce the busiest
7546 * queue by moving tasks around inside the node.
7548 * If we cannot move enough load due to this classification
7549 * the next pass will adjust the group classification and
7550 * allow migration of more tasks.
7552 * Both cases only affect the total convergence complexity.
7554 if (rt > env->fbq_type)
7557 capacity = capacity_of(i);
7559 wl = weighted_cpuload(i);
7562 * When comparing with imbalance, use weighted_cpuload()
7563 * which is not scaled with the cpu capacity.
7566 if (rq->nr_running == 1 && wl > env->imbalance &&
7567 !check_cpu_capacity(rq, env->sd))
7571 * For the load comparisons with the other cpu's, consider
7572 * the weighted_cpuload() scaled with the cpu capacity, so
7573 * that the load can be moved away from the cpu that is
7574 * potentially running at a lower capacity.
7576 * Thus we're looking for max(wl_i / capacity_i), crosswise
7577 * multiplication to rid ourselves of the division works out
7578 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
7579 * our previous maximum.
7581 if (wl * busiest_capacity > busiest_load * capacity) {
7583 busiest_capacity = capacity;
7592 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
7593 * so long as it is large enough.
7595 #define MAX_PINNED_INTERVAL 512
7597 static int need_active_balance(struct lb_env *env)
7599 struct sched_domain *sd = env->sd;
7601 if (env->idle == CPU_NEWLY_IDLE) {
7604 * ASYM_PACKING needs to force migrate tasks from busy but
7605 * higher numbered CPUs in order to pack all tasks in the
7606 * lowest numbered CPUs.
7608 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
7613 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
7614 * It's worth migrating the task if the src_cpu's capacity is reduced
7615 * because of other sched_class or IRQs if more capacity stays
7616 * available on dst_cpu.
7618 if ((env->idle != CPU_NOT_IDLE) &&
7619 (env->src_rq->cfs.h_nr_running == 1)) {
7620 if ((check_cpu_capacity(env->src_rq, sd)) &&
7621 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
7625 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
7628 static int active_load_balance_cpu_stop(void *data);
7630 static int should_we_balance(struct lb_env *env)
7632 struct sched_group *sg = env->sd->groups;
7633 struct cpumask *sg_cpus, *sg_mask;
7634 int cpu, balance_cpu = -1;
7637 * In the newly idle case, we will allow all the cpu's
7638 * to do the newly idle load balance.
7640 if (env->idle == CPU_NEWLY_IDLE)
7643 sg_cpus = sched_group_cpus(sg);
7644 sg_mask = sched_group_mask(sg);
7645 /* Try to find first idle cpu */
7646 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
7647 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
7654 if (balance_cpu == -1)
7655 balance_cpu = group_balance_cpu(sg);
7658 * First idle cpu or the first cpu(busiest) in this sched group
7659 * is eligible for doing load balancing at this and above domains.
7661 return balance_cpu == env->dst_cpu;
7665 * Check this_cpu to ensure it is balanced within domain. Attempt to move
7666 * tasks if there is an imbalance.
7668 static int load_balance(int this_cpu, struct rq *this_rq,
7669 struct sched_domain *sd, enum cpu_idle_type idle,
7670 int *continue_balancing)
7672 int ld_moved, cur_ld_moved, active_balance = 0;
7673 struct sched_domain *sd_parent = sd->parent;
7674 struct sched_group *group;
7676 unsigned long flags;
7677 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
7679 struct lb_env env = {
7681 .dst_cpu = this_cpu,
7683 .dst_grpmask = sched_group_cpus(sd->groups),
7685 .loop_break = sched_nr_migrate_break,
7688 .tasks = LIST_HEAD_INIT(env.tasks),
7692 * For NEWLY_IDLE load_balancing, we don't need to consider
7693 * other cpus in our group
7695 if (idle == CPU_NEWLY_IDLE)
7696 env.dst_grpmask = NULL;
7698 cpumask_copy(cpus, cpu_active_mask);
7700 schedstat_inc(sd->lb_count[idle]);
7703 if (!should_we_balance(&env)) {
7704 *continue_balancing = 0;
7708 group = find_busiest_group(&env);
7710 schedstat_inc(sd->lb_nobusyg[idle]);
7714 busiest = find_busiest_queue(&env, group);
7716 schedstat_inc(sd->lb_nobusyq[idle]);
7720 BUG_ON(busiest == env.dst_rq);
7722 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
7724 env.src_cpu = busiest->cpu;
7725 env.src_rq = busiest;
7728 if (busiest->nr_running > 1) {
7730 * Attempt to move tasks. If find_busiest_group has found
7731 * an imbalance but busiest->nr_running <= 1, the group is
7732 * still unbalanced. ld_moved simply stays zero, so it is
7733 * correctly treated as an imbalance.
7735 env.flags |= LBF_ALL_PINNED;
7736 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
7739 raw_spin_lock_irqsave(&busiest->lock, flags);
7742 * cur_ld_moved - load moved in current iteration
7743 * ld_moved - cumulative load moved across iterations
7745 cur_ld_moved = detach_tasks(&env);
7748 * We've detached some tasks from busiest_rq. Every
7749 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
7750 * unlock busiest->lock, and we are able to be sure
7751 * that nobody can manipulate the tasks in parallel.
7752 * See task_rq_lock() family for the details.
7755 raw_spin_unlock(&busiest->lock);
7759 ld_moved += cur_ld_moved;
7762 local_irq_restore(flags);
7764 if (env.flags & LBF_NEED_BREAK) {
7765 env.flags &= ~LBF_NEED_BREAK;
7770 * Revisit (affine) tasks on src_cpu that couldn't be moved to
7771 * us and move them to an alternate dst_cpu in our sched_group
7772 * where they can run. The upper limit on how many times we
7773 * iterate on same src_cpu is dependent on number of cpus in our
7776 * This changes load balance semantics a bit on who can move
7777 * load to a given_cpu. In addition to the given_cpu itself
7778 * (or a ilb_cpu acting on its behalf where given_cpu is
7779 * nohz-idle), we now have balance_cpu in a position to move
7780 * load to given_cpu. In rare situations, this may cause
7781 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
7782 * _independently_ and at _same_ time to move some load to
7783 * given_cpu) causing exceess load to be moved to given_cpu.
7784 * This however should not happen so much in practice and
7785 * moreover subsequent load balance cycles should correct the
7786 * excess load moved.
7788 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
7790 /* Prevent to re-select dst_cpu via env's cpus */
7791 cpumask_clear_cpu(env.dst_cpu, env.cpus);
7793 env.dst_rq = cpu_rq(env.new_dst_cpu);
7794 env.dst_cpu = env.new_dst_cpu;
7795 env.flags &= ~LBF_DST_PINNED;
7797 env.loop_break = sched_nr_migrate_break;
7800 * Go back to "more_balance" rather than "redo" since we
7801 * need to continue with same src_cpu.
7807 * We failed to reach balance because of affinity.
7810 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
7812 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
7813 *group_imbalance = 1;
7816 /* All tasks on this runqueue were pinned by CPU affinity */
7817 if (unlikely(env.flags & LBF_ALL_PINNED)) {
7818 cpumask_clear_cpu(cpu_of(busiest), cpus);
7819 if (!cpumask_empty(cpus)) {
7821 env.loop_break = sched_nr_migrate_break;
7824 goto out_all_pinned;
7829 schedstat_inc(sd->lb_failed[idle]);
7831 * Increment the failure counter only on periodic balance.
7832 * We do not want newidle balance, which can be very
7833 * frequent, pollute the failure counter causing
7834 * excessive cache_hot migrations and active balances.
7836 if (idle != CPU_NEWLY_IDLE)
7837 sd->nr_balance_failed++;
7839 if (need_active_balance(&env)) {
7840 raw_spin_lock_irqsave(&busiest->lock, flags);
7842 /* don't kick the active_load_balance_cpu_stop,
7843 * if the curr task on busiest cpu can't be
7846 if (!cpumask_test_cpu(this_cpu,
7847 tsk_cpus_allowed(busiest->curr))) {
7848 raw_spin_unlock_irqrestore(&busiest->lock,
7850 env.flags |= LBF_ALL_PINNED;
7851 goto out_one_pinned;
7855 * ->active_balance synchronizes accesses to
7856 * ->active_balance_work. Once set, it's cleared
7857 * only after active load balance is finished.
7859 if (!busiest->active_balance) {
7860 busiest->active_balance = 1;
7861 busiest->push_cpu = this_cpu;
7864 raw_spin_unlock_irqrestore(&busiest->lock, flags);
7866 if (active_balance) {
7867 stop_one_cpu_nowait(cpu_of(busiest),
7868 active_load_balance_cpu_stop, busiest,
7869 &busiest->active_balance_work);
7872 /* We've kicked active balancing, force task migration. */
7873 sd->nr_balance_failed = sd->cache_nice_tries+1;
7876 sd->nr_balance_failed = 0;
7878 if (likely(!active_balance)) {
7879 /* We were unbalanced, so reset the balancing interval */
7880 sd->balance_interval = sd->min_interval;
7883 * If we've begun active balancing, start to back off. This
7884 * case may not be covered by the all_pinned logic if there
7885 * is only 1 task on the busy runqueue (because we don't call
7888 if (sd->balance_interval < sd->max_interval)
7889 sd->balance_interval *= 2;
7896 * We reach balance although we may have faced some affinity
7897 * constraints. Clear the imbalance flag if it was set.
7900 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
7902 if (*group_imbalance)
7903 *group_imbalance = 0;
7908 * We reach balance because all tasks are pinned at this level so
7909 * we can't migrate them. Let the imbalance flag set so parent level
7910 * can try to migrate them.
7912 schedstat_inc(sd->lb_balanced[idle]);
7914 sd->nr_balance_failed = 0;
7917 /* tune up the balancing interval */
7918 if (((env.flags & LBF_ALL_PINNED) &&
7919 sd->balance_interval < MAX_PINNED_INTERVAL) ||
7920 (sd->balance_interval < sd->max_interval))
7921 sd->balance_interval *= 2;
7928 static inline unsigned long
7929 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
7931 unsigned long interval = sd->balance_interval;
7934 interval *= sd->busy_factor;
7936 /* scale ms to jiffies */
7937 interval = msecs_to_jiffies(interval);
7938 interval = clamp(interval, 1UL, max_load_balance_interval);
7944 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
7946 unsigned long interval, next;
7948 /* used by idle balance, so cpu_busy = 0 */
7949 interval = get_sd_balance_interval(sd, 0);
7950 next = sd->last_balance + interval;
7952 if (time_after(*next_balance, next))
7953 *next_balance = next;
7957 * idle_balance is called by schedule() if this_cpu is about to become
7958 * idle. Attempts to pull tasks from other CPUs.
7960 static int idle_balance(struct rq *this_rq)
7962 unsigned long next_balance = jiffies + HZ;
7963 int this_cpu = this_rq->cpu;
7964 struct sched_domain *sd;
7965 int pulled_task = 0;
7969 * We must set idle_stamp _before_ calling idle_balance(), such that we
7970 * measure the duration of idle_balance() as idle time.
7972 this_rq->idle_stamp = rq_clock(this_rq);
7974 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
7975 !this_rq->rd->overload) {
7977 sd = rcu_dereference_check_sched_domain(this_rq->sd);
7979 update_next_balance(sd, &next_balance);
7985 raw_spin_unlock(&this_rq->lock);
7987 update_blocked_averages(this_cpu);
7989 for_each_domain(this_cpu, sd) {
7990 int continue_balancing = 1;
7991 u64 t0, domain_cost;
7993 if (!(sd->flags & SD_LOAD_BALANCE))
7996 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
7997 update_next_balance(sd, &next_balance);
8001 if (sd->flags & SD_BALANCE_NEWIDLE) {
8002 t0 = sched_clock_cpu(this_cpu);
8004 pulled_task = load_balance(this_cpu, this_rq,
8006 &continue_balancing);
8008 domain_cost = sched_clock_cpu(this_cpu) - t0;
8009 if (domain_cost > sd->max_newidle_lb_cost)
8010 sd->max_newidle_lb_cost = domain_cost;
8012 curr_cost += domain_cost;
8015 update_next_balance(sd, &next_balance);
8018 * Stop searching for tasks to pull if there are
8019 * now runnable tasks on this rq.
8021 if (pulled_task || this_rq->nr_running > 0)
8026 raw_spin_lock(&this_rq->lock);
8028 if (curr_cost > this_rq->max_idle_balance_cost)
8029 this_rq->max_idle_balance_cost = curr_cost;
8032 * While browsing the domains, we released the rq lock, a task could
8033 * have been enqueued in the meantime. Since we're not going idle,
8034 * pretend we pulled a task.
8036 if (this_rq->cfs.h_nr_running && !pulled_task)
8040 /* Move the next balance forward */
8041 if (time_after(this_rq->next_balance, next_balance))
8042 this_rq->next_balance = next_balance;
8044 /* Is there a task of a high priority class? */
8045 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
8049 this_rq->idle_stamp = 0;
8055 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
8056 * running tasks off the busiest CPU onto idle CPUs. It requires at
8057 * least 1 task to be running on each physical CPU where possible, and
8058 * avoids physical / logical imbalances.
8060 static int active_load_balance_cpu_stop(void *data)
8062 struct rq *busiest_rq = data;
8063 int busiest_cpu = cpu_of(busiest_rq);
8064 int target_cpu = busiest_rq->push_cpu;
8065 struct rq *target_rq = cpu_rq(target_cpu);
8066 struct sched_domain *sd;
8067 struct task_struct *p = NULL;
8069 raw_spin_lock_irq(&busiest_rq->lock);
8071 /* make sure the requested cpu hasn't gone down in the meantime */
8072 if (unlikely(busiest_cpu != smp_processor_id() ||
8073 !busiest_rq->active_balance))
8076 /* Is there any task to move? */
8077 if (busiest_rq->nr_running <= 1)
8081 * This condition is "impossible", if it occurs
8082 * we need to fix it. Originally reported by
8083 * Bjorn Helgaas on a 128-cpu setup.
8085 BUG_ON(busiest_rq == target_rq);
8087 /* Search for an sd spanning us and the target CPU. */
8089 for_each_domain(target_cpu, sd) {
8090 if ((sd->flags & SD_LOAD_BALANCE) &&
8091 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
8096 struct lb_env env = {
8098 .dst_cpu = target_cpu,
8099 .dst_rq = target_rq,
8100 .src_cpu = busiest_rq->cpu,
8101 .src_rq = busiest_rq,
8105 schedstat_inc(sd->alb_count);
8107 p = detach_one_task(&env);
8109 schedstat_inc(sd->alb_pushed);
8110 /* Active balancing done, reset the failure counter. */
8111 sd->nr_balance_failed = 0;
8113 schedstat_inc(sd->alb_failed);
8118 busiest_rq->active_balance = 0;
8119 raw_spin_unlock(&busiest_rq->lock);
8122 attach_one_task(target_rq, p);
8129 static inline int on_null_domain(struct rq *rq)
8131 return unlikely(!rcu_dereference_sched(rq->sd));
8134 #ifdef CONFIG_NO_HZ_COMMON
8136 * idle load balancing details
8137 * - When one of the busy CPUs notice that there may be an idle rebalancing
8138 * needed, they will kick the idle load balancer, which then does idle
8139 * load balancing for all the idle CPUs.
8142 cpumask_var_t idle_cpus_mask;
8144 unsigned long next_balance; /* in jiffy units */
8145 } nohz ____cacheline_aligned;
8147 static inline int find_new_ilb(void)
8149 int ilb = cpumask_first(nohz.idle_cpus_mask);
8151 if (ilb < nr_cpu_ids && idle_cpu(ilb))
8158 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
8159 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
8160 * CPU (if there is one).
8162 static void nohz_balancer_kick(void)
8166 nohz.next_balance++;
8168 ilb_cpu = find_new_ilb();
8170 if (ilb_cpu >= nr_cpu_ids)
8173 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
8176 * Use smp_send_reschedule() instead of resched_cpu().
8177 * This way we generate a sched IPI on the target cpu which
8178 * is idle. And the softirq performing nohz idle load balance
8179 * will be run before returning from the IPI.
8181 smp_send_reschedule(ilb_cpu);
8185 void nohz_balance_exit_idle(unsigned int cpu)
8187 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
8189 * Completely isolated CPUs don't ever set, so we must test.
8191 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
8192 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
8193 atomic_dec(&nohz.nr_cpus);
8195 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
8199 static inline void set_cpu_sd_state_busy(void)
8201 struct sched_domain *sd;
8202 int cpu = smp_processor_id();
8205 sd = rcu_dereference(per_cpu(sd_llc, cpu));
8207 if (!sd || !sd->nohz_idle)
8211 atomic_inc(&sd->shared->nr_busy_cpus);
8216 void set_cpu_sd_state_idle(void)
8218 struct sched_domain *sd;
8219 int cpu = smp_processor_id();
8222 sd = rcu_dereference(per_cpu(sd_llc, cpu));
8224 if (!sd || sd->nohz_idle)
8228 atomic_dec(&sd->shared->nr_busy_cpus);
8234 * This routine will record that the cpu is going idle with tick stopped.
8235 * This info will be used in performing idle load balancing in the future.
8237 void nohz_balance_enter_idle(int cpu)
8240 * If this cpu is going down, then nothing needs to be done.
8242 if (!cpu_active(cpu))
8245 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
8249 * If we're a completely isolated CPU, we don't play.
8251 if (on_null_domain(cpu_rq(cpu)))
8254 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
8255 atomic_inc(&nohz.nr_cpus);
8256 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
8260 static DEFINE_SPINLOCK(balancing);
8263 * Scale the max load_balance interval with the number of CPUs in the system.
8264 * This trades load-balance latency on larger machines for less cross talk.
8266 void update_max_interval(void)
8268 max_load_balance_interval = HZ*num_online_cpus()/10;
8272 * It checks each scheduling domain to see if it is due to be balanced,
8273 * and initiates a balancing operation if so.
8275 * Balancing parameters are set up in init_sched_domains.
8277 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
8279 int continue_balancing = 1;
8281 unsigned long interval;
8282 struct sched_domain *sd;
8283 /* Earliest time when we have to do rebalance again */
8284 unsigned long next_balance = jiffies + 60*HZ;
8285 int update_next_balance = 0;
8286 int need_serialize, need_decay = 0;
8289 update_blocked_averages(cpu);
8292 for_each_domain(cpu, sd) {
8294 * Decay the newidle max times here because this is a regular
8295 * visit to all the domains. Decay ~1% per second.
8297 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
8298 sd->max_newidle_lb_cost =
8299 (sd->max_newidle_lb_cost * 253) / 256;
8300 sd->next_decay_max_lb_cost = jiffies + HZ;
8303 max_cost += sd->max_newidle_lb_cost;
8305 if (!(sd->flags & SD_LOAD_BALANCE))
8309 * Stop the load balance at this level. There is another
8310 * CPU in our sched group which is doing load balancing more
8313 if (!continue_balancing) {
8319 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
8321 need_serialize = sd->flags & SD_SERIALIZE;
8322 if (need_serialize) {
8323 if (!spin_trylock(&balancing))
8327 if (time_after_eq(jiffies, sd->last_balance + interval)) {
8328 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
8330 * The LBF_DST_PINNED logic could have changed
8331 * env->dst_cpu, so we can't know our idle
8332 * state even if we migrated tasks. Update it.
8334 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
8336 sd->last_balance = jiffies;
8337 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
8340 spin_unlock(&balancing);
8342 if (time_after(next_balance, sd->last_balance + interval)) {
8343 next_balance = sd->last_balance + interval;
8344 update_next_balance = 1;
8349 * Ensure the rq-wide value also decays but keep it at a
8350 * reasonable floor to avoid funnies with rq->avg_idle.
8352 rq->max_idle_balance_cost =
8353 max((u64)sysctl_sched_migration_cost, max_cost);
8358 * next_balance will be updated only when there is a need.
8359 * When the cpu is attached to null domain for ex, it will not be
8362 if (likely(update_next_balance)) {
8363 rq->next_balance = next_balance;
8365 #ifdef CONFIG_NO_HZ_COMMON
8367 * If this CPU has been elected to perform the nohz idle
8368 * balance. Other idle CPUs have already rebalanced with
8369 * nohz_idle_balance() and nohz.next_balance has been
8370 * updated accordingly. This CPU is now running the idle load
8371 * balance for itself and we need to update the
8372 * nohz.next_balance accordingly.
8374 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
8375 nohz.next_balance = rq->next_balance;
8380 #ifdef CONFIG_NO_HZ_COMMON
8382 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
8383 * rebalancing for all the cpus for whom scheduler ticks are stopped.
8385 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
8387 int this_cpu = this_rq->cpu;
8390 /* Earliest time when we have to do rebalance again */
8391 unsigned long next_balance = jiffies + 60*HZ;
8392 int update_next_balance = 0;
8394 if (idle != CPU_IDLE ||
8395 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
8398 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
8399 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
8403 * If this cpu gets work to do, stop the load balancing
8404 * work being done for other cpus. Next load
8405 * balancing owner will pick it up.
8410 rq = cpu_rq(balance_cpu);
8413 * If time for next balance is due,
8416 if (time_after_eq(jiffies, rq->next_balance)) {
8417 raw_spin_lock_irq(&rq->lock);
8418 update_rq_clock(rq);
8419 cpu_load_update_idle(rq);
8420 raw_spin_unlock_irq(&rq->lock);
8421 rebalance_domains(rq, CPU_IDLE);
8424 if (time_after(next_balance, rq->next_balance)) {
8425 next_balance = rq->next_balance;
8426 update_next_balance = 1;
8431 * next_balance will be updated only when there is a need.
8432 * When the CPU is attached to null domain for ex, it will not be
8435 if (likely(update_next_balance))
8436 nohz.next_balance = next_balance;
8438 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
8442 * Current heuristic for kicking the idle load balancer in the presence
8443 * of an idle cpu in the system.
8444 * - This rq has more than one task.
8445 * - This rq has at least one CFS task and the capacity of the CPU is
8446 * significantly reduced because of RT tasks or IRQs.
8447 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
8448 * multiple busy cpu.
8449 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
8450 * domain span are idle.
8452 static inline bool nohz_kick_needed(struct rq *rq)
8454 unsigned long now = jiffies;
8455 struct sched_domain_shared *sds;
8456 struct sched_domain *sd;
8457 int nr_busy, cpu = rq->cpu;
8460 if (unlikely(rq->idle_balance))
8464 * We may be recently in ticked or tickless idle mode. At the first
8465 * busy tick after returning from idle, we will update the busy stats.
8467 set_cpu_sd_state_busy();
8468 nohz_balance_exit_idle(cpu);
8471 * None are in tickless mode and hence no need for NOHZ idle load
8474 if (likely(!atomic_read(&nohz.nr_cpus)))
8477 if (time_before(now, nohz.next_balance))
8480 if (rq->nr_running >= 2)
8484 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
8487 * XXX: write a coherent comment on why we do this.
8488 * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
8490 nr_busy = atomic_read(&sds->nr_busy_cpus);
8498 sd = rcu_dereference(rq->sd);
8500 if ((rq->cfs.h_nr_running >= 1) &&
8501 check_cpu_capacity(rq, sd)) {
8507 sd = rcu_dereference(per_cpu(sd_asym, cpu));
8508 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
8509 sched_domain_span(sd)) < cpu)) {
8519 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
8523 * run_rebalance_domains is triggered when needed from the scheduler tick.
8524 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
8526 static void run_rebalance_domains(struct softirq_action *h)
8528 struct rq *this_rq = this_rq();
8529 enum cpu_idle_type idle = this_rq->idle_balance ?
8530 CPU_IDLE : CPU_NOT_IDLE;
8533 * If this cpu has a pending nohz_balance_kick, then do the
8534 * balancing on behalf of the other idle cpus whose ticks are
8535 * stopped. Do nohz_idle_balance *before* rebalance_domains to
8536 * give the idle cpus a chance to load balance. Else we may
8537 * load balance only within the local sched_domain hierarchy
8538 * and abort nohz_idle_balance altogether if we pull some load.
8540 nohz_idle_balance(this_rq, idle);
8541 rebalance_domains(this_rq, idle);
8545 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
8547 void trigger_load_balance(struct rq *rq)
8549 /* Don't need to rebalance while attached to NULL domain */
8550 if (unlikely(on_null_domain(rq)))
8553 if (time_after_eq(jiffies, rq->next_balance))
8554 raise_softirq(SCHED_SOFTIRQ);
8555 #ifdef CONFIG_NO_HZ_COMMON
8556 if (nohz_kick_needed(rq))
8557 nohz_balancer_kick();
8561 static void rq_online_fair(struct rq *rq)
8565 update_runtime_enabled(rq);
8568 static void rq_offline_fair(struct rq *rq)
8572 /* Ensure any throttled groups are reachable by pick_next_task */
8573 unthrottle_offline_cfs_rqs(rq);
8576 #endif /* CONFIG_SMP */
8579 * scheduler tick hitting a task of our scheduling class:
8581 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
8583 struct cfs_rq *cfs_rq;
8584 struct sched_entity *se = &curr->se;
8586 for_each_sched_entity(se) {
8587 cfs_rq = cfs_rq_of(se);
8588 entity_tick(cfs_rq, se, queued);
8591 if (static_branch_unlikely(&sched_numa_balancing))
8592 task_tick_numa(rq, curr);
8596 * called on fork with the child task as argument from the parent's context
8597 * - child not yet on the tasklist
8598 * - preemption disabled
8600 static void task_fork_fair(struct task_struct *p)
8602 struct cfs_rq *cfs_rq;
8603 struct sched_entity *se = &p->se, *curr;
8604 struct rq *rq = this_rq();
8606 raw_spin_lock(&rq->lock);
8607 update_rq_clock(rq);
8609 cfs_rq = task_cfs_rq(current);
8610 curr = cfs_rq->curr;
8612 update_curr(cfs_rq);
8613 se->vruntime = curr->vruntime;
8615 place_entity(cfs_rq, se, 1);
8617 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
8619 * Upon rescheduling, sched_class::put_prev_task() will place
8620 * 'current' within the tree based on its new key value.
8622 swap(curr->vruntime, se->vruntime);
8626 se->vruntime -= cfs_rq->min_vruntime;
8627 raw_spin_unlock(&rq->lock);
8631 * Priority of the task has changed. Check to see if we preempt
8635 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
8637 if (!task_on_rq_queued(p))
8641 * Reschedule if we are currently running on this runqueue and
8642 * our priority decreased, or if we are not currently running on
8643 * this runqueue and our priority is higher than the current's
8645 if (rq->curr == p) {
8646 if (p->prio > oldprio)
8649 check_preempt_curr(rq, p, 0);
8652 static inline bool vruntime_normalized(struct task_struct *p)
8654 struct sched_entity *se = &p->se;
8657 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
8658 * the dequeue_entity(.flags=0) will already have normalized the
8665 * When !on_rq, vruntime of the task has usually NOT been normalized.
8666 * But there are some cases where it has already been normalized:
8668 * - A forked child which is waiting for being woken up by
8669 * wake_up_new_task().
8670 * - A task which has been woken up by try_to_wake_up() and
8671 * waiting for actually being woken up by sched_ttwu_pending().
8673 if (!se->sum_exec_runtime || p->state == TASK_WAKING)
8679 static void detach_task_cfs_rq(struct task_struct *p)
8681 struct sched_entity *se = &p->se;
8682 struct cfs_rq *cfs_rq = cfs_rq_of(se);
8683 u64 now = cfs_rq_clock_task(cfs_rq);
8685 if (!vruntime_normalized(p)) {
8687 * Fix up our vruntime so that the current sleep doesn't
8688 * cause 'unlimited' sleep bonus.
8690 place_entity(cfs_rq, se, 0);
8691 se->vruntime -= cfs_rq->min_vruntime;
8694 /* Catch up with the cfs_rq and remove our load when we leave */
8695 update_cfs_rq_load_avg(now, cfs_rq, false);
8696 detach_entity_load_avg(cfs_rq, se);
8697 update_tg_load_avg(cfs_rq, false);
8700 static void attach_task_cfs_rq(struct task_struct *p)
8702 struct sched_entity *se = &p->se;
8703 struct cfs_rq *cfs_rq = cfs_rq_of(se);
8704 u64 now = cfs_rq_clock_task(cfs_rq);
8706 #ifdef CONFIG_FAIR_GROUP_SCHED
8708 * Since the real-depth could have been changed (only FAIR
8709 * class maintain depth value), reset depth properly.
8711 se->depth = se->parent ? se->parent->depth + 1 : 0;
8714 /* Synchronize task with its cfs_rq */
8715 update_cfs_rq_load_avg(now, cfs_rq, false);
8716 attach_entity_load_avg(cfs_rq, se);
8717 update_tg_load_avg(cfs_rq, false);
8719 if (!vruntime_normalized(p))
8720 se->vruntime += cfs_rq->min_vruntime;
8723 static void switched_from_fair(struct rq *rq, struct task_struct *p)
8725 detach_task_cfs_rq(p);
8728 static void switched_to_fair(struct rq *rq, struct task_struct *p)
8730 attach_task_cfs_rq(p);
8732 if (task_on_rq_queued(p)) {
8734 * We were most likely switched from sched_rt, so
8735 * kick off the schedule if running, otherwise just see
8736 * if we can still preempt the current task.
8741 check_preempt_curr(rq, p, 0);
8745 /* Account for a task changing its policy or group.
8747 * This routine is mostly called to set cfs_rq->curr field when a task
8748 * migrates between groups/classes.
8750 static void set_curr_task_fair(struct rq *rq)
8752 struct sched_entity *se = &rq->curr->se;
8754 for_each_sched_entity(se) {
8755 struct cfs_rq *cfs_rq = cfs_rq_of(se);
8757 set_next_entity(cfs_rq, se);
8758 /* ensure bandwidth has been allocated on our new cfs_rq */
8759 account_cfs_rq_runtime(cfs_rq, 0);
8763 void init_cfs_rq(struct cfs_rq *cfs_rq)
8765 cfs_rq->tasks_timeline = RB_ROOT;
8766 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8767 #ifndef CONFIG_64BIT
8768 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
8771 atomic_long_set(&cfs_rq->removed_load_avg, 0);
8772 atomic_long_set(&cfs_rq->removed_util_avg, 0);
8776 #ifdef CONFIG_FAIR_GROUP_SCHED
8777 static void task_set_group_fair(struct task_struct *p)
8779 struct sched_entity *se = &p->se;
8781 set_task_rq(p, task_cpu(p));
8782 se->depth = se->parent ? se->parent->depth + 1 : 0;
8785 static void task_move_group_fair(struct task_struct *p)
8787 detach_task_cfs_rq(p);
8788 set_task_rq(p, task_cpu(p));
8791 /* Tell se's cfs_rq has been changed -- migrated */
8792 p->se.avg.last_update_time = 0;
8794 attach_task_cfs_rq(p);
8797 static void task_change_group_fair(struct task_struct *p, int type)
8800 case TASK_SET_GROUP:
8801 task_set_group_fair(p);
8804 case TASK_MOVE_GROUP:
8805 task_move_group_fair(p);
8810 void free_fair_sched_group(struct task_group *tg)
8814 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
8816 for_each_possible_cpu(i) {
8818 kfree(tg->cfs_rq[i]);
8827 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8829 struct sched_entity *se;
8830 struct cfs_rq *cfs_rq;
8834 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8837 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8841 tg->shares = NICE_0_LOAD;
8843 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
8845 for_each_possible_cpu(i) {
8848 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8849 GFP_KERNEL, cpu_to_node(i));
8853 se = kzalloc_node(sizeof(struct sched_entity),
8854 GFP_KERNEL, cpu_to_node(i));
8858 init_cfs_rq(cfs_rq);
8859 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8860 init_entity_runnable_average(se);
8871 void online_fair_sched_group(struct task_group *tg)
8873 struct sched_entity *se;
8877 for_each_possible_cpu(i) {
8881 raw_spin_lock_irq(&rq->lock);
8882 post_init_entity_util_avg(se);
8883 sync_throttle(tg, i);
8884 raw_spin_unlock_irq(&rq->lock);
8888 void unregister_fair_sched_group(struct task_group *tg)
8890 unsigned long flags;
8894 for_each_possible_cpu(cpu) {
8896 remove_entity_load_avg(tg->se[cpu]);
8899 * Only empty task groups can be destroyed; so we can speculatively
8900 * check on_list without danger of it being re-added.
8902 if (!tg->cfs_rq[cpu]->on_list)
8907 raw_spin_lock_irqsave(&rq->lock, flags);
8908 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8909 raw_spin_unlock_irqrestore(&rq->lock, flags);
8913 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8914 struct sched_entity *se, int cpu,
8915 struct sched_entity *parent)
8917 struct rq *rq = cpu_rq(cpu);
8921 init_cfs_rq_runtime(cfs_rq);
8923 tg->cfs_rq[cpu] = cfs_rq;
8926 /* se could be NULL for root_task_group */
8931 se->cfs_rq = &rq->cfs;
8934 se->cfs_rq = parent->my_q;
8935 se->depth = parent->depth + 1;
8939 /* guarantee group entities always have weight */
8940 update_load_set(&se->load, NICE_0_LOAD);
8941 se->parent = parent;
8944 static DEFINE_MUTEX(shares_mutex);
8946 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8949 unsigned long flags;
8952 * We can't change the weight of the root cgroup.
8957 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
8959 mutex_lock(&shares_mutex);
8960 if (tg->shares == shares)
8963 tg->shares = shares;
8964 for_each_possible_cpu(i) {
8965 struct rq *rq = cpu_rq(i);
8966 struct sched_entity *se;
8969 /* Propagate contribution to hierarchy */
8970 raw_spin_lock_irqsave(&rq->lock, flags);
8972 /* Possible calls to update_curr() need rq clock */
8973 update_rq_clock(rq);
8974 for_each_sched_entity(se)
8975 update_cfs_shares(group_cfs_rq(se));
8976 raw_spin_unlock_irqrestore(&rq->lock, flags);
8980 mutex_unlock(&shares_mutex);
8983 #else /* CONFIG_FAIR_GROUP_SCHED */
8985 void free_fair_sched_group(struct task_group *tg) { }
8987 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8992 void online_fair_sched_group(struct task_group *tg) { }
8994 void unregister_fair_sched_group(struct task_group *tg) { }
8996 #endif /* CONFIG_FAIR_GROUP_SCHED */
8999 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
9001 struct sched_entity *se = &task->se;
9002 unsigned int rr_interval = 0;
9005 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
9008 if (rq->cfs.load.weight)
9009 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
9015 * All the scheduling class methods:
9017 const struct sched_class fair_sched_class = {
9018 .next = &idle_sched_class,
9019 .enqueue_task = enqueue_task_fair,
9020 .dequeue_task = dequeue_task_fair,
9021 .yield_task = yield_task_fair,
9022 .yield_to_task = yield_to_task_fair,
9024 .check_preempt_curr = check_preempt_wakeup,
9026 .pick_next_task = pick_next_task_fair,
9027 .put_prev_task = put_prev_task_fair,
9030 .select_task_rq = select_task_rq_fair,
9031 .migrate_task_rq = migrate_task_rq_fair,
9033 .rq_online = rq_online_fair,
9034 .rq_offline = rq_offline_fair,
9036 .task_dead = task_dead_fair,
9037 .set_cpus_allowed = set_cpus_allowed_common,
9040 .set_curr_task = set_curr_task_fair,
9041 .task_tick = task_tick_fair,
9042 .task_fork = task_fork_fair,
9044 .prio_changed = prio_changed_fair,
9045 .switched_from = switched_from_fair,
9046 .switched_to = switched_to_fair,
9048 .get_rr_interval = get_rr_interval_fair,
9050 .update_curr = update_curr_fair,
9052 #ifdef CONFIG_FAIR_GROUP_SCHED
9053 .task_change_group = task_change_group_fair,
9057 #ifdef CONFIG_SCHED_DEBUG
9058 void print_cfs_stats(struct seq_file *m, int cpu)
9060 struct cfs_rq *cfs_rq;
9063 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
9064 print_cfs_rq(m, cpu, cfs_rq);
9068 #ifdef CONFIG_NUMA_BALANCING
9069 void show_numa_stats(struct task_struct *p, struct seq_file *m)
9072 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
9074 for_each_online_node(node) {
9075 if (p->numa_faults) {
9076 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
9077 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
9079 if (p->numa_group) {
9080 gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
9081 gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
9083 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
9086 #endif /* CONFIG_NUMA_BALANCING */
9087 #endif /* CONFIG_SCHED_DEBUG */
9089 __init void init_sched_fair_class(void)
9092 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9094 #ifdef CONFIG_NO_HZ_COMMON
9095 nohz.next_balance = jiffies;
9096 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);