1 // SPDX-License-Identifier: GPL-2.0
3 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
5 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
7 * Interactivity improvements by Mike Galbraith
8 * (C) 2007 Mike Galbraith <efault@gmx.de>
10 * Various enhancements by Dmitry Adamushko.
11 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
13 * Group scheduling enhancements by Srivatsa Vaddagiri
14 * Copyright IBM Corporation, 2007
15 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
17 * Scaled math optimizations by Thomas Gleixner
18 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
24 #include <linux/sched/mm.h>
25 #include <linux/sched/topology.h>
27 #include <linux/latencytop.h>
28 #include <linux/cpumask.h>
29 #include <linux/cpuidle.h>
30 #include <linux/slab.h>
31 #include <linux/profile.h>
32 #include <linux/interrupt.h>
33 #include <linux/mempolicy.h>
34 #include <linux/migrate.h>
35 #include <linux/task_work.h>
37 #include <trace/events/sched.h>
44 * Targeted preemption latency for CPU-bound tasks:
46 * NOTE: this latency value is not the same as the concept of
47 * 'timeslice length' - timeslices in CFS are of variable length
48 * and have no persistent notion like in traditional, time-slice
49 * based scheduling concepts.
51 * (to see the precise effective timeslice length of your workload,
52 * run vmstat and monitor the context-switches (cs) field)
54 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
56 unsigned int sysctl_sched_latency
= 6000000ULL;
57 unsigned int normalized_sysctl_sched_latency
= 6000000ULL;
60 * Enable/disable honoring sync flag in energy-aware wakeups.
62 unsigned int sysctl_sched_sync_hint_enable
= 1;
64 * Enable/disable using cstate knowledge in idle sibling selection
66 unsigned int sysctl_sched_cstate_aware
= 1;
69 * The initial- and re-scaling of tunables is configurable
73 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
74 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
75 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
77 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
79 enum sched_tunable_scaling sysctl_sched_tunable_scaling
= SCHED_TUNABLESCALING_LOG
;
82 * Minimal preemption granularity for CPU-bound tasks:
84 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
86 unsigned int sysctl_sched_min_granularity
= 750000ULL;
87 unsigned int normalized_sysctl_sched_min_granularity
= 750000ULL;
90 * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
92 static unsigned int sched_nr_latency
= 8;
95 * After fork, child runs first. If set to 0 (default) then
96 * parent will (try to) run first.
98 unsigned int sysctl_sched_child_runs_first __read_mostly
;
101 * SCHED_OTHER wake-up granularity.
103 * This option delays the preemption effects of decoupled workloads
104 * and reduces their over-scheduling. Synchronous workloads will still
105 * have immediate wakeup/sleep latencies.
107 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
109 unsigned int sysctl_sched_wakeup_granularity
= 1000000UL;
110 unsigned int normalized_sysctl_sched_wakeup_granularity
= 1000000UL;
112 const_debug
unsigned int sysctl_sched_migration_cost
= 500000UL;
114 #ifdef CONFIG_SCHED_WALT
115 unsigned int sysctl_sched_use_walt_cpu_util
= 1;
116 unsigned int sysctl_sched_use_walt_task_util
= 1;
117 __read_mostly
unsigned int sysctl_sched_walt_cpu_high_irqload
=
118 (10 * NSEC_PER_MSEC
);
123 * For asym packing, by default the lower numbered cpu has higher priority.
125 int __weak
arch_asym_cpu_priority(int cpu
)
131 #ifdef CONFIG_CFS_BANDWIDTH
133 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
134 * each time a cfs_rq requests quota.
136 * Note: in the case that the slice exceeds the runtime remaining (either due
137 * to consumption or the quota being specified to be smaller than the slice)
138 * we will always only issue the remaining available time.
140 * (default: 5 msec, units: microseconds)
142 unsigned int sysctl_sched_cfs_bandwidth_slice
= 5000UL;
146 * The margin used when comparing utilization with CPU capacity:
147 * util * margin < capacity * 1024
151 unsigned int capacity_margin
= 1280;
153 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
159 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
165 static inline void update_load_set(struct load_weight
*lw
, unsigned long w
)
172 * Increase the granularity value when there are more CPUs,
173 * because with more CPUs the 'effective latency' as visible
174 * to users decreases. But the relationship is not linear,
175 * so pick a second-best guess by going with the log2 of the
178 * This idea comes from the SD scheduler of Con Kolivas:
180 static unsigned int get_update_sysctl_factor(void)
182 unsigned int cpus
= min_t(unsigned int, num_online_cpus(), 8);
185 switch (sysctl_sched_tunable_scaling
) {
186 case SCHED_TUNABLESCALING_NONE
:
189 case SCHED_TUNABLESCALING_LINEAR
:
192 case SCHED_TUNABLESCALING_LOG
:
194 factor
= 1 + ilog2(cpus
);
201 static void update_sysctl(void)
203 unsigned int factor
= get_update_sysctl_factor();
205 #define SET_SYSCTL(name) \
206 (sysctl_##name = (factor) * normalized_sysctl_##name)
207 SET_SYSCTL(sched_min_granularity
);
208 SET_SYSCTL(sched_latency
);
209 SET_SYSCTL(sched_wakeup_granularity
);
213 void sched_init_granularity(void)
218 #define WMULT_CONST (~0U)
219 #define WMULT_SHIFT 32
221 static void __update_inv_weight(struct load_weight
*lw
)
225 if (likely(lw
->inv_weight
))
228 w
= scale_load_down(lw
->weight
);
230 if (BITS_PER_LONG
> 32 && unlikely(w
>= WMULT_CONST
))
232 else if (unlikely(!w
))
233 lw
->inv_weight
= WMULT_CONST
;
235 lw
->inv_weight
= WMULT_CONST
/ w
;
239 * delta_exec * weight / lw.weight
241 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
243 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
244 * we're guaranteed shift stays positive because inv_weight is guaranteed to
245 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
247 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
248 * weight/lw.weight <= 1, and therefore our shift will also be positive.
250 static u64
__calc_delta(u64 delta_exec
, unsigned long weight
, struct load_weight
*lw
)
252 u64 fact
= scale_load_down(weight
);
253 int shift
= WMULT_SHIFT
;
255 __update_inv_weight(lw
);
257 if (unlikely(fact
>> 32)) {
264 /* hint to use a 32x32->64 mul */
265 fact
= (u64
)(u32
)fact
* lw
->inv_weight
;
272 return mul_u64_u32_shr(delta_exec
, fact
, shift
);
276 const struct sched_class fair_sched_class
;
278 /**************************************************************
279 * CFS operations on generic schedulable entities:
282 #ifdef CONFIG_FAIR_GROUP_SCHED
284 /* cpu runqueue to which this cfs_rq is attached */
285 static inline struct rq
*rq_of(struct cfs_rq
*cfs_rq
)
290 /* An entity is a task if it doesn't "own" a runqueue */
291 #define entity_is_task(se) (!se->my_q)
293 static inline struct task_struct
*task_of(struct sched_entity
*se
)
295 SCHED_WARN_ON(!entity_is_task(se
));
296 return container_of(se
, struct task_struct
, se
);
299 /* Walk up scheduling entities hierarchy */
300 #define for_each_sched_entity(se) \
301 for (; se; se = se->parent)
303 static inline struct cfs_rq
*task_cfs_rq(struct task_struct
*p
)
308 /* runqueue on which this entity is (to be) queued */
309 static inline struct cfs_rq
*cfs_rq_of(struct sched_entity
*se
)
314 /* runqueue "owned" by this group */
315 static inline struct cfs_rq
*group_cfs_rq(struct sched_entity
*grp
)
320 static inline void list_add_leaf_cfs_rq(struct cfs_rq
*cfs_rq
)
322 if (!cfs_rq
->on_list
) {
323 struct rq
*rq
= rq_of(cfs_rq
);
324 int cpu
= cpu_of(rq
);
326 * Ensure we either appear before our parent (if already
327 * enqueued) or force our parent to appear after us when it is
328 * enqueued. The fact that we always enqueue bottom-up
329 * reduces this to two cases and a special case for the root
330 * cfs_rq. Furthermore, it also means that we will always reset
331 * tmp_alone_branch either when the branch is connected
332 * to a tree or when we reach the beg of the tree
334 if (cfs_rq
->tg
->parent
&&
335 cfs_rq
->tg
->parent
->cfs_rq
[cpu
]->on_list
) {
337 * If parent is already on the list, we add the child
338 * just before. Thanks to circular linked property of
339 * the list, this means to put the child at the tail
340 * of the list that starts by parent.
342 list_add_tail_rcu(&cfs_rq
->leaf_cfs_rq_list
,
343 &(cfs_rq
->tg
->parent
->cfs_rq
[cpu
]->leaf_cfs_rq_list
));
345 * The branch is now connected to its tree so we can
346 * reset tmp_alone_branch to the beginning of the
349 rq
->tmp_alone_branch
= &rq
->leaf_cfs_rq_list
;
350 } else if (!cfs_rq
->tg
->parent
) {
352 * cfs rq without parent should be put
353 * at the tail of the list.
355 list_add_tail_rcu(&cfs_rq
->leaf_cfs_rq_list
,
356 &rq
->leaf_cfs_rq_list
);
358 * We have reach the beg of a tree so we can reset
359 * tmp_alone_branch to the beginning of the list.
361 rq
->tmp_alone_branch
= &rq
->leaf_cfs_rq_list
;
364 * The parent has not already been added so we want to
365 * make sure that it will be put after us.
366 * tmp_alone_branch points to the beg of the branch
367 * where we will add parent.
369 list_add_rcu(&cfs_rq
->leaf_cfs_rq_list
,
370 rq
->tmp_alone_branch
);
372 * update tmp_alone_branch to points to the new beg
375 rq
->tmp_alone_branch
= &cfs_rq
->leaf_cfs_rq_list
;
382 static inline void list_del_leaf_cfs_rq(struct cfs_rq
*cfs_rq
)
384 if (cfs_rq
->on_list
) {
385 list_del_rcu(&cfs_rq
->leaf_cfs_rq_list
);
390 /* Iterate thr' all leaf cfs_rq's on a runqueue */
391 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
392 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
395 /* Do the two (enqueued) entities belong to the same group ? */
396 static inline struct cfs_rq
*
397 is_same_group(struct sched_entity
*se
, struct sched_entity
*pse
)
399 if (se
->cfs_rq
== pse
->cfs_rq
)
405 static inline struct sched_entity
*parent_entity(struct sched_entity
*se
)
411 find_matching_se(struct sched_entity
**se
, struct sched_entity
**pse
)
413 int se_depth
, pse_depth
;
416 * preemption test can be made between sibling entities who are in the
417 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
418 * both tasks until we find their ancestors who are siblings of common
422 /* First walk up until both entities are at same depth */
423 se_depth
= (*se
)->depth
;
424 pse_depth
= (*pse
)->depth
;
426 while (se_depth
> pse_depth
) {
428 *se
= parent_entity(*se
);
431 while (pse_depth
> se_depth
) {
433 *pse
= parent_entity(*pse
);
436 while (!is_same_group(*se
, *pse
)) {
437 *se
= parent_entity(*se
);
438 *pse
= parent_entity(*pse
);
442 #else /* !CONFIG_FAIR_GROUP_SCHED */
444 static inline struct task_struct
*task_of(struct sched_entity
*se
)
446 return container_of(se
, struct task_struct
, se
);
449 static inline struct rq
*rq_of(struct cfs_rq
*cfs_rq
)
451 return container_of(cfs_rq
, struct rq
, cfs
);
454 #define entity_is_task(se) 1
456 #define for_each_sched_entity(se) \
457 for (; se; se = NULL)
459 static inline struct cfs_rq
*task_cfs_rq(struct task_struct
*p
)
461 return &task_rq(p
)->cfs
;
464 static inline struct cfs_rq
*cfs_rq_of(struct sched_entity
*se
)
466 struct task_struct
*p
= task_of(se
);
467 struct rq
*rq
= task_rq(p
);
472 /* runqueue "owned" by this group */
473 static inline struct cfs_rq
*group_cfs_rq(struct sched_entity
*grp
)
478 static inline void list_add_leaf_cfs_rq(struct cfs_rq
*cfs_rq
)
482 static inline void list_del_leaf_cfs_rq(struct cfs_rq
*cfs_rq
)
486 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
487 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
489 static inline struct sched_entity
*parent_entity(struct sched_entity
*se
)
495 find_matching_se(struct sched_entity
**se
, struct sched_entity
**pse
)
499 #endif /* CONFIG_FAIR_GROUP_SCHED */
501 static __always_inline
502 void account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
);
504 /**************************************************************
505 * Scheduling class tree data structure manipulation methods:
508 static inline u64
max_vruntime(u64 max_vruntime
, u64 vruntime
)
510 s64 delta
= (s64
)(vruntime
- max_vruntime
);
512 max_vruntime
= vruntime
;
517 static inline u64
min_vruntime(u64 min_vruntime
, u64 vruntime
)
519 s64 delta
= (s64
)(vruntime
- min_vruntime
);
521 min_vruntime
= vruntime
;
526 static inline int entity_before(struct sched_entity
*a
,
527 struct sched_entity
*b
)
529 return (s64
)(a
->vruntime
- b
->vruntime
) < 0;
532 static void update_min_vruntime(struct cfs_rq
*cfs_rq
)
534 struct sched_entity
*curr
= cfs_rq
->curr
;
535 struct rb_node
*leftmost
= rb_first_cached(&cfs_rq
->tasks_timeline
);
537 u64 vruntime
= cfs_rq
->min_vruntime
;
541 vruntime
= curr
->vruntime
;
546 if (leftmost
) { /* non-empty tree */
547 struct sched_entity
*se
;
548 se
= rb_entry(leftmost
, struct sched_entity
, run_node
);
551 vruntime
= se
->vruntime
;
553 vruntime
= min_vruntime(vruntime
, se
->vruntime
);
556 /* ensure we never gain time by being placed backwards. */
557 cfs_rq
->min_vruntime
= max_vruntime(cfs_rq
->min_vruntime
, vruntime
);
560 cfs_rq
->min_vruntime_copy
= cfs_rq
->min_vruntime
;
565 * Enqueue an entity into the rb-tree:
567 static void __enqueue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
569 struct rb_node
**link
= &cfs_rq
->tasks_timeline
.rb_root
.rb_node
;
570 struct rb_node
*parent
= NULL
;
571 struct sched_entity
*entry
;
572 bool leftmost
= true;
575 * Find the right place in the rbtree:
579 entry
= rb_entry(parent
, struct sched_entity
, run_node
);
581 * We dont care about collisions. Nodes with
582 * the same key stay together.
584 if (entity_before(se
, entry
)) {
585 link
= &parent
->rb_left
;
587 link
= &parent
->rb_right
;
592 rb_link_node(&se
->run_node
, parent
, link
);
593 rb_insert_color_cached(&se
->run_node
,
594 &cfs_rq
->tasks_timeline
, leftmost
);
597 static void __dequeue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
599 rb_erase_cached(&se
->run_node
, &cfs_rq
->tasks_timeline
);
602 struct sched_entity
*__pick_first_entity(struct cfs_rq
*cfs_rq
)
604 struct rb_node
*left
= rb_first_cached(&cfs_rq
->tasks_timeline
);
609 return rb_entry(left
, struct sched_entity
, run_node
);
612 static struct sched_entity
*__pick_next_entity(struct sched_entity
*se
)
614 struct rb_node
*next
= rb_next(&se
->run_node
);
619 return rb_entry(next
, struct sched_entity
, run_node
);
622 #ifdef CONFIG_SCHED_DEBUG
623 struct sched_entity
*__pick_last_entity(struct cfs_rq
*cfs_rq
)
625 struct rb_node
*last
= rb_last(&cfs_rq
->tasks_timeline
.rb_root
);
630 return rb_entry(last
, struct sched_entity
, run_node
);
633 /**************************************************************
634 * Scheduling class statistics methods:
637 int sched_proc_update_handler(struct ctl_table
*table
, int write
,
638 void __user
*buffer
, size_t *lenp
,
641 int ret
= proc_dointvec_minmax(table
, write
, buffer
, lenp
, ppos
);
642 unsigned int factor
= get_update_sysctl_factor();
647 sched_nr_latency
= DIV_ROUND_UP(sysctl_sched_latency
,
648 sysctl_sched_min_granularity
);
650 #define WRT_SYSCTL(name) \
651 (normalized_sysctl_##name = sysctl_##name / (factor))
652 WRT_SYSCTL(sched_min_granularity
);
653 WRT_SYSCTL(sched_latency
);
654 WRT_SYSCTL(sched_wakeup_granularity
);
664 static inline u64
calc_delta_fair(u64 delta
, struct sched_entity
*se
)
666 if (unlikely(se
->load
.weight
!= NICE_0_LOAD
))
667 delta
= __calc_delta(delta
, NICE_0_LOAD
, &se
->load
);
673 * The idea is to set a period in which each task runs once.
675 * When there are too many tasks (sched_nr_latency) we have to stretch
676 * this period because otherwise the slices get too small.
678 * p = (nr <= nl) ? l : l*nr/nl
680 static u64
__sched_period(unsigned long nr_running
)
682 if (unlikely(nr_running
> sched_nr_latency
))
683 return nr_running
* sysctl_sched_min_granularity
;
685 return sysctl_sched_latency
;
689 * We calculate the wall-time slice from the period by taking a part
690 * proportional to the weight.
694 static u64
sched_slice(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
696 u64 slice
= __sched_period(cfs_rq
->nr_running
+ !se
->on_rq
);
698 for_each_sched_entity(se
) {
699 struct load_weight
*load
;
700 struct load_weight lw
;
702 cfs_rq
= cfs_rq_of(se
);
703 load
= &cfs_rq
->load
;
705 if (unlikely(!se
->on_rq
)) {
708 update_load_add(&lw
, se
->load
.weight
);
711 slice
= __calc_delta(slice
, se
->load
.weight
, load
);
717 * We calculate the vruntime slice of a to-be-inserted task.
721 static u64
sched_vslice(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
723 return calc_delta_fair(sched_slice(cfs_rq
, se
), se
);
728 #include "sched-pelt.h"
730 static int select_idle_sibling(struct task_struct
*p
, int prev_cpu
, int cpu
);
731 static unsigned long task_h_load(struct task_struct
*p
);
732 static unsigned long capacity_of(int cpu
);
734 /* Give new sched_entity start runnable values to heavy its load in infant time */
735 void init_entity_runnable_average(struct sched_entity
*se
)
737 struct sched_avg
*sa
= &se
->avg
;
739 sa
->last_update_time
= 0;
741 * sched_avg's period_contrib should be strictly less then 1024, so
742 * we give it 1023 to make sure it is almost a period (1024us), and
743 * will definitely be update (after enqueue).
745 sa
->period_contrib
= 1023;
747 * Tasks are intialized with full load to be seen as heavy tasks until
748 * they get a chance to stabilize to their real load level.
749 * Group entities are intialized with zero load to reflect the fact that
750 * nothing has been attached to the task group yet.
752 if (entity_is_task(se
))
753 sa
->load_avg
= scale_load_down(se
->load
.weight
);
754 sa
->load_sum
= sa
->load_avg
* LOAD_AVG_MAX
;
756 * At this point, util_avg won't be used in select_task_rq_fair anyway
760 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
763 static inline u64
cfs_rq_clock_task(struct cfs_rq
*cfs_rq
);
764 static void attach_entity_cfs_rq(struct sched_entity
*se
);
767 * With new tasks being created, their initial util_avgs are extrapolated
768 * based on the cfs_rq's current util_avg:
770 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
772 * However, in many cases, the above util_avg does not give a desired
773 * value. Moreover, the sum of the util_avgs may be divergent, such
774 * as when the series is a harmonic series.
776 * To solve this problem, we also cap the util_avg of successive tasks to
777 * only 1/2 of the left utilization budget:
779 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
781 * where n denotes the nth task and cpu_scale the CPU capacity.
783 * For example, for a CPU with 1024 of capacity, a simplest series from
784 * the beginning would be like:
786 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
787 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
789 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
790 * if util_avg > util_avg_cap.
792 void post_init_entity_util_avg(struct sched_entity
*se
)
794 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
795 struct sched_avg
*sa
= &se
->avg
;
796 long cpu_scale
= arch_scale_cpu_capacity(NULL
, cpu_of(rq_of(cfs_rq
)));
797 long cap
= (long)(cpu_scale
- cfs_rq
->avg
.util_avg
) / 2;
800 if (cfs_rq
->avg
.util_avg
!= 0) {
801 sa
->util_avg
= cfs_rq
->avg
.util_avg
* se
->load
.weight
;
802 sa
->util_avg
/= (cfs_rq
->avg
.load_avg
+ 1);
804 if (sa
->util_avg
> cap
)
809 sa
->util_sum
= sa
->util_avg
* LOAD_AVG_MAX
;
812 if (entity_is_task(se
)) {
813 struct task_struct
*p
= task_of(se
);
814 if (p
->sched_class
!= &fair_sched_class
) {
816 * For !fair tasks do:
818 update_cfs_rq_load_avg(now, cfs_rq);
819 attach_entity_load_avg(cfs_rq, se);
820 switched_from_fair(rq, p);
822 * such that the next switched_to_fair() has the
825 se
->avg
.last_update_time
= cfs_rq_clock_task(cfs_rq
);
830 attach_entity_cfs_rq(se
);
833 #else /* !CONFIG_SMP */
834 void init_entity_runnable_average(struct sched_entity
*se
)
837 void post_init_entity_util_avg(struct sched_entity
*se
)
840 static void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
)
843 #endif /* CONFIG_SMP */
846 * Update the current task's runtime statistics.
848 static void update_curr(struct cfs_rq
*cfs_rq
)
850 struct sched_entity
*curr
= cfs_rq
->curr
;
851 u64 now
= rq_clock_task(rq_of(cfs_rq
));
857 delta_exec
= now
- curr
->exec_start
;
858 if (unlikely((s64
)delta_exec
<= 0))
861 curr
->exec_start
= now
;
863 schedstat_set(curr
->statistics
.exec_max
,
864 max(delta_exec
, curr
->statistics
.exec_max
));
866 curr
->sum_exec_runtime
+= delta_exec
;
867 schedstat_add(cfs_rq
->exec_clock
, delta_exec
);
869 curr
->vruntime
+= calc_delta_fair(delta_exec
, curr
);
870 update_min_vruntime(cfs_rq
);
872 if (entity_is_task(curr
)) {
873 struct task_struct
*curtask
= task_of(curr
);
875 trace_sched_stat_runtime(curtask
, delta_exec
, curr
->vruntime
);
876 cpuacct_charge(curtask
, delta_exec
);
877 account_group_exec_runtime(curtask
, delta_exec
);
880 account_cfs_rq_runtime(cfs_rq
, delta_exec
);
883 static void update_curr_fair(struct rq
*rq
)
885 update_curr(cfs_rq_of(&rq
->curr
->se
));
889 update_stats_wait_start(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
891 u64 wait_start
, prev_wait_start
;
893 if (!schedstat_enabled())
896 wait_start
= rq_clock(rq_of(cfs_rq
));
897 prev_wait_start
= schedstat_val(se
->statistics
.wait_start
);
899 if (entity_is_task(se
) && task_on_rq_migrating(task_of(se
)) &&
900 likely(wait_start
> prev_wait_start
))
901 wait_start
-= prev_wait_start
;
903 schedstat_set(se
->statistics
.wait_start
, wait_start
);
907 update_stats_wait_end(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
909 struct task_struct
*p
;
912 if (!schedstat_enabled())
915 delta
= rq_clock(rq_of(cfs_rq
)) - schedstat_val(se
->statistics
.wait_start
);
917 if (entity_is_task(se
)) {
919 if (task_on_rq_migrating(p
)) {
921 * Preserve migrating task's wait time so wait_start
922 * time stamp can be adjusted to accumulate wait time
923 * prior to migration.
925 schedstat_set(se
->statistics
.wait_start
, delta
);
928 trace_sched_stat_wait(p
, delta
);
931 schedstat_set(se
->statistics
.wait_max
,
932 max(schedstat_val(se
->statistics
.wait_max
), delta
));
933 schedstat_inc(se
->statistics
.wait_count
);
934 schedstat_add(se
->statistics
.wait_sum
, delta
);
935 schedstat_set(se
->statistics
.wait_start
, 0);
939 update_stats_enqueue_sleeper(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
941 struct task_struct
*tsk
= NULL
;
942 u64 sleep_start
, block_start
;
944 if (!schedstat_enabled())
947 sleep_start
= schedstat_val(se
->statistics
.sleep_start
);
948 block_start
= schedstat_val(se
->statistics
.block_start
);
950 if (entity_is_task(se
))
954 u64 delta
= rq_clock(rq_of(cfs_rq
)) - sleep_start
;
959 if (unlikely(delta
> schedstat_val(se
->statistics
.sleep_max
)))
960 schedstat_set(se
->statistics
.sleep_max
, delta
);
962 schedstat_set(se
->statistics
.sleep_start
, 0);
963 schedstat_add(se
->statistics
.sum_sleep_runtime
, delta
);
966 account_scheduler_latency(tsk
, delta
>> 10, 1);
967 trace_sched_stat_sleep(tsk
, delta
);
971 u64 delta
= rq_clock(rq_of(cfs_rq
)) - block_start
;
976 if (unlikely(delta
> schedstat_val(se
->statistics
.block_max
)))
977 schedstat_set(se
->statistics
.block_max
, delta
);
979 schedstat_set(se
->statistics
.block_start
, 0);
980 schedstat_add(se
->statistics
.sum_sleep_runtime
, delta
);
983 if (tsk
->in_iowait
) {
984 schedstat_add(se
->statistics
.iowait_sum
, delta
);
985 schedstat_inc(se
->statistics
.iowait_count
);
986 trace_sched_stat_iowait(tsk
, delta
);
989 trace_sched_stat_blocked(tsk
, delta
);
990 trace_sched_blocked_reason(tsk
);
993 * Blocking time is in units of nanosecs, so shift by
994 * 20 to get a milliseconds-range estimation of the
995 * amount of time that the task spent sleeping:
997 if (unlikely(prof_on
== SLEEP_PROFILING
)) {
998 profile_hits(SLEEP_PROFILING
,
999 (void *)get_wchan(tsk
),
1002 account_scheduler_latency(tsk
, delta
>> 10, 0);
1008 * Task is being enqueued - update stats:
1011 update_stats_enqueue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
1013 if (!schedstat_enabled())
1017 * Are we enqueueing a waiting task? (for current tasks
1018 * a dequeue/enqueue event is a NOP)
1020 if (se
!= cfs_rq
->curr
)
1021 update_stats_wait_start(cfs_rq
, se
);
1023 if (flags
& ENQUEUE_WAKEUP
)
1024 update_stats_enqueue_sleeper(cfs_rq
, se
);
1028 update_stats_dequeue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
1031 if (!schedstat_enabled())
1035 * Mark the end of the wait period if dequeueing a
1038 if (se
!= cfs_rq
->curr
)
1039 update_stats_wait_end(cfs_rq
, se
);
1041 if ((flags
& DEQUEUE_SLEEP
) && entity_is_task(se
)) {
1042 struct task_struct
*tsk
= task_of(se
);
1044 if (tsk
->state
& TASK_INTERRUPTIBLE
)
1045 schedstat_set(se
->statistics
.sleep_start
,
1046 rq_clock(rq_of(cfs_rq
)));
1047 if (tsk
->state
& TASK_UNINTERRUPTIBLE
)
1048 schedstat_set(se
->statistics
.block_start
,
1049 rq_clock(rq_of(cfs_rq
)));
1054 * We are picking a new current task - update its stats:
1057 update_stats_curr_start(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
1060 * We are starting a new run period:
1062 se
->exec_start
= rq_clock_task(rq_of(cfs_rq
));
1065 /**************************************************
1066 * Scheduling class queueing methods:
1069 #ifdef CONFIG_NUMA_BALANCING
1071 * Approximate time to scan a full NUMA task in ms. The task scan period is
1072 * calculated based on the tasks virtual memory size and
1073 * numa_balancing_scan_size.
1075 unsigned int sysctl_numa_balancing_scan_period_min
= 1000;
1076 unsigned int sysctl_numa_balancing_scan_period_max
= 60000;
1078 /* Portion of address space to scan in MB */
1079 unsigned int sysctl_numa_balancing_scan_size
= 256;
1081 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1082 unsigned int sysctl_numa_balancing_scan_delay
= 1000;
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 static inline unsigned long group_faults_priv(struct numa_group
*ng
);
1105 static inline unsigned long group_faults_shared(struct numa_group
*ng
);
1107 static unsigned int task_nr_scan_windows(struct task_struct
*p
)
1109 unsigned long rss
= 0;
1110 unsigned long nr_scan_pages
;
1113 * Calculations based on RSS as non-present and empty pages are skipped
1114 * by the PTE scanner and NUMA hinting faults should be trapped based
1117 nr_scan_pages
= sysctl_numa_balancing_scan_size
<< (20 - PAGE_SHIFT
);
1118 rss
= get_mm_rss(p
->mm
);
1120 rss
= nr_scan_pages
;
1122 rss
= round_up(rss
, nr_scan_pages
);
1123 return rss
/ nr_scan_pages
;
1126 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1127 #define MAX_SCAN_WINDOW 2560
1129 static unsigned int task_scan_min(struct task_struct
*p
)
1131 unsigned int scan_size
= READ_ONCE(sysctl_numa_balancing_scan_size
);
1132 unsigned int scan
, floor
;
1133 unsigned int windows
= 1;
1135 if (scan_size
< MAX_SCAN_WINDOW
)
1136 windows
= MAX_SCAN_WINDOW
/ scan_size
;
1137 floor
= 1000 / windows
;
1139 scan
= sysctl_numa_balancing_scan_period_min
/ task_nr_scan_windows(p
);
1140 return max_t(unsigned int, floor
, scan
);
1143 static unsigned int task_scan_start(struct task_struct
*p
)
1145 unsigned long smin
= task_scan_min(p
);
1146 unsigned long period
= smin
;
1148 /* Scale the maximum scan period with the amount of shared memory. */
1149 if (p
->numa_group
) {
1150 struct numa_group
*ng
= p
->numa_group
;
1151 unsigned long shared
= group_faults_shared(ng
);
1152 unsigned long private = group_faults_priv(ng
);
1154 period
*= atomic_read(&ng
->refcount
);
1155 period
*= shared
+ 1;
1156 period
/= private + shared
+ 1;
1159 return max(smin
, period
);
1162 static unsigned int task_scan_max(struct task_struct
*p
)
1164 unsigned long smin
= task_scan_min(p
);
1167 /* Watch for min being lower than max due to floor calculations */
1168 smax
= sysctl_numa_balancing_scan_period_max
/ task_nr_scan_windows(p
);
1170 /* Scale the maximum scan period with the amount of shared memory. */
1171 if (p
->numa_group
) {
1172 struct numa_group
*ng
= p
->numa_group
;
1173 unsigned long shared
= group_faults_shared(ng
);
1174 unsigned long private = group_faults_priv(ng
);
1175 unsigned long period
= smax
;
1177 period
*= atomic_read(&ng
->refcount
);
1178 period
*= shared
+ 1;
1179 period
/= private + shared
+ 1;
1181 smax
= max(smax
, period
);
1184 return max(smin
, smax
);
1187 static void account_numa_enqueue(struct rq
*rq
, struct task_struct
*p
)
1189 rq
->nr_numa_running
+= (p
->numa_preferred_nid
!= -1);
1190 rq
->nr_preferred_running
+= (p
->numa_preferred_nid
== task_node(p
));
1193 static void account_numa_dequeue(struct rq
*rq
, struct task_struct
*p
)
1195 rq
->nr_numa_running
-= (p
->numa_preferred_nid
!= -1);
1196 rq
->nr_preferred_running
-= (p
->numa_preferred_nid
== task_node(p
));
1199 /* Shared or private faults. */
1200 #define NR_NUMA_HINT_FAULT_TYPES 2
1202 /* Memory and CPU locality */
1203 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1205 /* Averaged statistics, and temporary buffers. */
1206 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1208 pid_t
task_numa_group_id(struct task_struct
*p
)
1210 return p
->numa_group
? p
->numa_group
->gid
: 0;
1214 * The averaged statistics, shared & private, memory & cpu,
1215 * occupy the first half of the array. The second half of the
1216 * array is for current counters, which are averaged into the
1217 * first set by task_numa_placement.
1219 static inline int task_faults_idx(enum numa_faults_stats s
, int nid
, int priv
)
1221 return NR_NUMA_HINT_FAULT_TYPES
* (s
* nr_node_ids
+ nid
) + priv
;
1224 static inline unsigned long task_faults(struct task_struct
*p
, int nid
)
1226 if (!p
->numa_faults
)
1229 return p
->numa_faults
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1230 p
->numa_faults
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1233 static inline unsigned long group_faults(struct task_struct
*p
, int nid
)
1238 return p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1239 p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1242 static inline unsigned long group_faults_cpu(struct numa_group
*group
, int nid
)
1244 return group
->faults_cpu
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1245 group
->faults_cpu
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1248 static inline unsigned long group_faults_priv(struct numa_group
*ng
)
1250 unsigned long faults
= 0;
1253 for_each_online_node(node
) {
1254 faults
+= ng
->faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
1260 static inline unsigned long group_faults_shared(struct numa_group
*ng
)
1262 unsigned long faults
= 0;
1265 for_each_online_node(node
) {
1266 faults
+= ng
->faults
[task_faults_idx(NUMA_MEM
, node
, 0)];
1273 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1274 * considered part of a numa group's pseudo-interleaving set. Migrations
1275 * between these nodes are slowed down, to allow things to settle down.
1277 #define ACTIVE_NODE_FRACTION 3
1279 static bool numa_is_active_node(int nid
, struct numa_group
*ng
)
1281 return group_faults_cpu(ng
, nid
) * ACTIVE_NODE_FRACTION
> ng
->max_faults_cpu
;
1284 /* Handle placement on systems where not all nodes are directly connected. */
1285 static unsigned long score_nearby_nodes(struct task_struct
*p
, int nid
,
1286 int maxdist
, bool task
)
1288 unsigned long score
= 0;
1292 * All nodes are directly connected, and the same distance
1293 * from each other. No need for fancy placement algorithms.
1295 if (sched_numa_topology_type
== NUMA_DIRECT
)
1299 * This code is called for each node, introducing N^2 complexity,
1300 * which should be ok given the number of nodes rarely exceeds 8.
1302 for_each_online_node(node
) {
1303 unsigned long faults
;
1304 int dist
= node_distance(nid
, node
);
1307 * The furthest away nodes in the system are not interesting
1308 * for placement; nid was already counted.
1310 if (dist
== sched_max_numa_distance
|| node
== nid
)
1314 * On systems with a backplane NUMA topology, compare groups
1315 * of nodes, and move tasks towards the group with the most
1316 * memory accesses. When comparing two nodes at distance
1317 * "hoplimit", only nodes closer by than "hoplimit" are part
1318 * of each group. Skip other nodes.
1320 if (sched_numa_topology_type
== NUMA_BACKPLANE
&&
1324 /* Add up the faults from nearby nodes. */
1326 faults
= task_faults(p
, node
);
1328 faults
= group_faults(p
, node
);
1331 * On systems with a glueless mesh NUMA topology, there are
1332 * no fixed "groups of nodes". Instead, nodes that are not
1333 * directly connected bounce traffic through intermediate
1334 * nodes; a numa_group can occupy any set of nodes.
1335 * The further away a node is, the less the faults count.
1336 * This seems to result in good task placement.
1338 if (sched_numa_topology_type
== NUMA_GLUELESS_MESH
) {
1339 faults
*= (sched_max_numa_distance
- dist
);
1340 faults
/= (sched_max_numa_distance
- LOCAL_DISTANCE
);
1350 * These return the fraction of accesses done by a particular task, or
1351 * task group, on a particular numa node. The group weight is given a
1352 * larger multiplier, in order to group tasks together that are almost
1353 * evenly spread out between numa nodes.
1355 static inline unsigned long task_weight(struct task_struct
*p
, int nid
,
1358 unsigned long faults
, total_faults
;
1360 if (!p
->numa_faults
)
1363 total_faults
= p
->total_numa_faults
;
1368 faults
= task_faults(p
, nid
);
1369 faults
+= score_nearby_nodes(p
, nid
, dist
, true);
1371 return 1000 * faults
/ total_faults
;
1374 static inline unsigned long group_weight(struct task_struct
*p
, int nid
,
1377 unsigned long faults
, total_faults
;
1382 total_faults
= p
->numa_group
->total_faults
;
1387 faults
= group_faults(p
, nid
);
1388 faults
+= score_nearby_nodes(p
, nid
, dist
, false);
1390 return 1000 * faults
/ total_faults
;
1393 bool should_numa_migrate_memory(struct task_struct
*p
, struct page
* page
,
1394 int src_nid
, int dst_cpu
)
1396 struct numa_group
*ng
= p
->numa_group
;
1397 int dst_nid
= cpu_to_node(dst_cpu
);
1398 int last_cpupid
, this_cpupid
;
1400 this_cpupid
= cpu_pid_to_cpupid(dst_cpu
, current
->pid
);
1403 * Multi-stage node selection is used in conjunction with a periodic
1404 * migration fault to build a temporal task<->page relation. By using
1405 * a two-stage filter we remove short/unlikely relations.
1407 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1408 * a task's usage of a particular page (n_p) per total usage of this
1409 * page (n_t) (in a given time-span) to a probability.
1411 * Our periodic faults will sample this probability and getting the
1412 * same result twice in a row, given these samples are fully
1413 * independent, is then given by P(n)^2, provided our sample period
1414 * is sufficiently short compared to the usage pattern.
1416 * This quadric squishes small probabilities, making it less likely we
1417 * act on an unlikely task<->page relation.
1419 last_cpupid
= page_cpupid_xchg_last(page
, this_cpupid
);
1420 if (!cpupid_pid_unset(last_cpupid
) &&
1421 cpupid_to_nid(last_cpupid
) != dst_nid
)
1424 /* Always allow migrate on private faults */
1425 if (cpupid_match_pid(p
, last_cpupid
))
1428 /* A shared fault, but p->numa_group has not been set up yet. */
1433 * Destination node is much more heavily used than the source
1434 * node? Allow migration.
1436 if (group_faults_cpu(ng
, dst_nid
) > group_faults_cpu(ng
, src_nid
) *
1437 ACTIVE_NODE_FRACTION
)
1441 * Distribute memory according to CPU & memory use on each node,
1442 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1444 * faults_cpu(dst) 3 faults_cpu(src)
1445 * --------------- * - > ---------------
1446 * faults_mem(dst) 4 faults_mem(src)
1448 return group_faults_cpu(ng
, dst_nid
) * group_faults(p
, src_nid
) * 3 >
1449 group_faults_cpu(ng
, src_nid
) * group_faults(p
, dst_nid
) * 4;
1452 static unsigned long weighted_cpuload(struct rq
*rq
);
1453 static unsigned long source_load(int cpu
, int type
);
1454 static unsigned long target_load(int cpu
, int type
);
1456 /* Cached statistics for all CPUs within a node */
1458 unsigned long nr_running
;
1461 /* Total compute capacity of CPUs on a node */
1462 unsigned long compute_capacity
;
1464 /* Approximate capacity in terms of runnable tasks on a node */
1465 unsigned long task_capacity
;
1466 int has_free_capacity
;
1470 * XXX borrowed from update_sg_lb_stats
1472 static void update_numa_stats(struct numa_stats
*ns
, int nid
)
1474 int smt
, cpu
, cpus
= 0;
1475 unsigned long capacity
;
1477 memset(ns
, 0, sizeof(*ns
));
1478 for_each_cpu(cpu
, cpumask_of_node(nid
)) {
1479 struct rq
*rq
= cpu_rq(cpu
);
1481 ns
->nr_running
+= rq
->nr_running
;
1482 ns
->load
+= weighted_cpuload(rq
);
1483 ns
->compute_capacity
+= capacity_of(cpu
);
1489 * If we raced with hotplug and there are no CPUs left in our mask
1490 * the @ns structure is NULL'ed and task_numa_compare() will
1491 * not find this node attractive.
1493 * We'll either bail at !has_free_capacity, or we'll detect a huge
1494 * imbalance and bail there.
1499 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1500 smt
= DIV_ROUND_UP(SCHED_CAPACITY_SCALE
* cpus
, ns
->compute_capacity
);
1501 capacity
= cpus
/ smt
; /* cores */
1503 ns
->task_capacity
= min_t(unsigned, capacity
,
1504 DIV_ROUND_CLOSEST(ns
->compute_capacity
, SCHED_CAPACITY_SCALE
));
1505 ns
->has_free_capacity
= (ns
->nr_running
< ns
->task_capacity
);
1508 struct task_numa_env
{
1509 struct task_struct
*p
;
1511 int src_cpu
, src_nid
;
1512 int dst_cpu
, dst_nid
;
1514 struct numa_stats src_stats
, dst_stats
;
1519 struct task_struct
*best_task
;
1524 static void task_numa_assign(struct task_numa_env
*env
,
1525 struct task_struct
*p
, long imp
)
1528 put_task_struct(env
->best_task
);
1533 env
->best_imp
= imp
;
1534 env
->best_cpu
= env
->dst_cpu
;
1537 static bool load_too_imbalanced(long src_load
, long dst_load
,
1538 struct task_numa_env
*env
)
1541 long orig_src_load
, orig_dst_load
;
1542 long src_capacity
, dst_capacity
;
1545 * The load is corrected for the CPU capacity available on each node.
1548 * ------------ vs ---------
1549 * src_capacity dst_capacity
1551 src_capacity
= env
->src_stats
.compute_capacity
;
1552 dst_capacity
= env
->dst_stats
.compute_capacity
;
1554 /* We care about the slope of the imbalance, not the direction. */
1555 if (dst_load
< src_load
)
1556 swap(dst_load
, src_load
);
1558 /* Is the difference below the threshold? */
1559 imb
= dst_load
* src_capacity
* 100 -
1560 src_load
* dst_capacity
* env
->imbalance_pct
;
1565 * The imbalance is above the allowed threshold.
1566 * Compare it with the old imbalance.
1568 orig_src_load
= env
->src_stats
.load
;
1569 orig_dst_load
= env
->dst_stats
.load
;
1571 if (orig_dst_load
< orig_src_load
)
1572 swap(orig_dst_load
, orig_src_load
);
1574 old_imb
= orig_dst_load
* src_capacity
* 100 -
1575 orig_src_load
* dst_capacity
* env
->imbalance_pct
;
1577 /* Would this change make things worse? */
1578 return (imb
> old_imb
);
1582 * This checks if the overall compute and NUMA accesses of the system would
1583 * be improved if the source tasks was migrated to the target dst_cpu taking
1584 * into account that it might be best if task running on the dst_cpu should
1585 * be exchanged with the source task
1587 static void task_numa_compare(struct task_numa_env
*env
,
1588 long taskimp
, long groupimp
)
1590 struct rq
*src_rq
= cpu_rq(env
->src_cpu
);
1591 struct rq
*dst_rq
= cpu_rq(env
->dst_cpu
);
1592 struct task_struct
*cur
;
1593 long src_load
, dst_load
;
1595 long imp
= env
->p
->numa_group
? groupimp
: taskimp
;
1597 int dist
= env
->dist
;
1600 cur
= task_rcu_dereference(&dst_rq
->curr
);
1601 if (cur
&& ((cur
->flags
& PF_EXITING
) || is_idle_task(cur
)))
1605 * Because we have preemption enabled we can get migrated around and
1606 * end try selecting ourselves (current == env->p) as a swap candidate.
1612 * "imp" is the fault differential for the source task between the
1613 * source and destination node. Calculate the total differential for
1614 * the source task and potential destination task. The more negative
1615 * the value is, the more rmeote accesses that would be expected to
1616 * be incurred if the tasks were swapped.
1619 /* Skip this swap candidate if cannot move to the source cpu */
1620 if (!cpumask_test_cpu(env
->src_cpu
, &cur
->cpus_allowed
))
1624 * If dst and source tasks are in the same NUMA group, or not
1625 * in any group then look only at task weights.
1627 if (cur
->numa_group
== env
->p
->numa_group
) {
1628 imp
= taskimp
+ task_weight(cur
, env
->src_nid
, dist
) -
1629 task_weight(cur
, env
->dst_nid
, dist
);
1631 * Add some hysteresis to prevent swapping the
1632 * tasks within a group over tiny differences.
1634 if (cur
->numa_group
)
1638 * Compare the group weights. If a task is all by
1639 * itself (not part of a group), use the task weight
1642 if (cur
->numa_group
)
1643 imp
+= group_weight(cur
, env
->src_nid
, dist
) -
1644 group_weight(cur
, env
->dst_nid
, dist
);
1646 imp
+= task_weight(cur
, env
->src_nid
, dist
) -
1647 task_weight(cur
, env
->dst_nid
, dist
);
1651 if (imp
<= env
->best_imp
&& moveimp
<= env
->best_imp
)
1655 /* Is there capacity at our destination? */
1656 if (env
->src_stats
.nr_running
<= env
->src_stats
.task_capacity
&&
1657 !env
->dst_stats
.has_free_capacity
)
1663 /* Balance doesn't matter much if we're running a task per cpu */
1664 if (imp
> env
->best_imp
&& src_rq
->nr_running
== 1 &&
1665 dst_rq
->nr_running
== 1)
1669 * In the overloaded case, try and keep the load balanced.
1672 load
= task_h_load(env
->p
);
1673 dst_load
= env
->dst_stats
.load
+ load
;
1674 src_load
= env
->src_stats
.load
- load
;
1676 if (moveimp
> imp
&& moveimp
> env
->best_imp
) {
1678 * If the improvement from just moving env->p direction is
1679 * better than swapping tasks around, check if a move is
1680 * possible. Store a slightly smaller score than moveimp,
1681 * so an actually idle CPU will win.
1683 if (!load_too_imbalanced(src_load
, dst_load
, env
)) {
1690 if (imp
<= env
->best_imp
)
1694 load
= task_h_load(cur
);
1699 if (load_too_imbalanced(src_load
, dst_load
, env
))
1703 * One idle CPU per node is evaluated for a task numa move.
1704 * Call select_idle_sibling to maybe find a better one.
1708 * select_idle_siblings() uses an per-cpu cpumask that
1709 * can be used from IRQ context.
1711 local_irq_disable();
1712 env
->dst_cpu
= select_idle_sibling(env
->p
, env
->src_cpu
,
1718 task_numa_assign(env
, cur
, imp
);
1723 static void task_numa_find_cpu(struct task_numa_env
*env
,
1724 long taskimp
, long groupimp
)
1728 for_each_cpu(cpu
, cpumask_of_node(env
->dst_nid
)) {
1729 /* Skip this CPU if the source task cannot migrate */
1730 if (!cpumask_test_cpu(cpu
, &env
->p
->cpus_allowed
))
1734 task_numa_compare(env
, taskimp
, groupimp
);
1738 /* Only move tasks to a NUMA node less busy than the current node. */
1739 static bool numa_has_capacity(struct task_numa_env
*env
)
1741 struct numa_stats
*src
= &env
->src_stats
;
1742 struct numa_stats
*dst
= &env
->dst_stats
;
1744 if (src
->has_free_capacity
&& !dst
->has_free_capacity
)
1748 * Only consider a task move if the source has a higher load
1749 * than the destination, corrected for CPU capacity on each node.
1751 * src->load dst->load
1752 * --------------------- vs ---------------------
1753 * src->compute_capacity dst->compute_capacity
1755 if (src
->load
* dst
->compute_capacity
* env
->imbalance_pct
>
1757 dst
->load
* src
->compute_capacity
* 100)
1763 static int task_numa_migrate(struct task_struct
*p
)
1765 struct task_numa_env env
= {
1768 .src_cpu
= task_cpu(p
),
1769 .src_nid
= task_node(p
),
1771 .imbalance_pct
= 112,
1777 struct sched_domain
*sd
;
1778 unsigned long taskweight
, groupweight
;
1780 long taskimp
, groupimp
;
1783 * Pick the lowest SD_NUMA domain, as that would have the smallest
1784 * imbalance and would be the first to start moving tasks about.
1786 * And we want to avoid any moving of tasks about, as that would create
1787 * random movement of tasks -- counter the numa conditions we're trying
1791 sd
= rcu_dereference(per_cpu(sd_numa
, env
.src_cpu
));
1793 env
.imbalance_pct
= 100 + (sd
->imbalance_pct
- 100) / 2;
1797 * Cpusets can break the scheduler domain tree into smaller
1798 * balance domains, some of which do not cross NUMA boundaries.
1799 * Tasks that are "trapped" in such domains cannot be migrated
1800 * elsewhere, so there is no point in (re)trying.
1802 if (unlikely(!sd
)) {
1803 p
->numa_preferred_nid
= task_node(p
);
1807 env
.dst_nid
= p
->numa_preferred_nid
;
1808 dist
= env
.dist
= node_distance(env
.src_nid
, env
.dst_nid
);
1809 taskweight
= task_weight(p
, env
.src_nid
, dist
);
1810 groupweight
= group_weight(p
, env
.src_nid
, dist
);
1811 update_numa_stats(&env
.src_stats
, env
.src_nid
);
1812 taskimp
= task_weight(p
, env
.dst_nid
, dist
) - taskweight
;
1813 groupimp
= group_weight(p
, env
.dst_nid
, dist
) - groupweight
;
1814 update_numa_stats(&env
.dst_stats
, env
.dst_nid
);
1816 /* Try to find a spot on the preferred nid. */
1817 if (numa_has_capacity(&env
))
1818 task_numa_find_cpu(&env
, taskimp
, groupimp
);
1821 * Look at other nodes in these cases:
1822 * - there is no space available on the preferred_nid
1823 * - the task is part of a numa_group that is interleaved across
1824 * multiple NUMA nodes; in order to better consolidate the group,
1825 * we need to check other locations.
1827 if (env
.best_cpu
== -1 || (p
->numa_group
&& p
->numa_group
->active_nodes
> 1)) {
1828 for_each_online_node(nid
) {
1829 if (nid
== env
.src_nid
|| nid
== p
->numa_preferred_nid
)
1832 dist
= node_distance(env
.src_nid
, env
.dst_nid
);
1833 if (sched_numa_topology_type
== NUMA_BACKPLANE
&&
1835 taskweight
= task_weight(p
, env
.src_nid
, dist
);
1836 groupweight
= group_weight(p
, env
.src_nid
, dist
);
1839 /* Only consider nodes where both task and groups benefit */
1840 taskimp
= task_weight(p
, nid
, dist
) - taskweight
;
1841 groupimp
= group_weight(p
, nid
, dist
) - groupweight
;
1842 if (taskimp
< 0 && groupimp
< 0)
1847 update_numa_stats(&env
.dst_stats
, env
.dst_nid
);
1848 if (numa_has_capacity(&env
))
1849 task_numa_find_cpu(&env
, taskimp
, groupimp
);
1854 * If the task is part of a workload that spans multiple NUMA nodes,
1855 * and is migrating into one of the workload's active nodes, remember
1856 * this node as the task's preferred numa node, so the workload can
1858 * A task that migrated to a second choice node will be better off
1859 * trying for a better one later. Do not set the preferred node here.
1861 if (p
->numa_group
) {
1862 struct numa_group
*ng
= p
->numa_group
;
1864 if (env
.best_cpu
== -1)
1869 if (ng
->active_nodes
> 1 && numa_is_active_node(env
.dst_nid
, ng
))
1870 sched_setnuma(p
, env
.dst_nid
);
1873 /* No better CPU than the current one was found. */
1874 if (env
.best_cpu
== -1)
1878 * Reset the scan period if the task is being rescheduled on an
1879 * alternative node to recheck if the tasks is now properly placed.
1881 p
->numa_scan_period
= task_scan_start(p
);
1883 if (env
.best_task
== NULL
) {
1884 ret
= migrate_task_to(p
, env
.best_cpu
);
1886 trace_sched_stick_numa(p
, env
.src_cpu
, env
.best_cpu
);
1890 ret
= migrate_swap(p
, env
.best_task
);
1892 trace_sched_stick_numa(p
, env
.src_cpu
, task_cpu(env
.best_task
));
1893 put_task_struct(env
.best_task
);
1897 /* Attempt to migrate a task to a CPU on the preferred node. */
1898 static void numa_migrate_preferred(struct task_struct
*p
)
1900 unsigned long interval
= HZ
;
1902 /* This task has no NUMA fault statistics yet */
1903 if (unlikely(p
->numa_preferred_nid
== -1 || !p
->numa_faults
))
1906 /* Periodically retry migrating the task to the preferred node */
1907 interval
= min(interval
, msecs_to_jiffies(p
->numa_scan_period
) / 16);
1908 p
->numa_migrate_retry
= jiffies
+ interval
;
1910 /* Success if task is already running on preferred CPU */
1911 if (task_node(p
) == p
->numa_preferred_nid
)
1914 /* Otherwise, try migrate to a CPU on the preferred node */
1915 task_numa_migrate(p
);
1919 * Find out how many nodes on the workload is actively running on. Do this by
1920 * tracking the nodes from which NUMA hinting faults are triggered. This can
1921 * be different from the set of nodes where the workload's memory is currently
1924 static void numa_group_count_active_nodes(struct numa_group
*numa_group
)
1926 unsigned long faults
, max_faults
= 0;
1927 int nid
, active_nodes
= 0;
1929 for_each_online_node(nid
) {
1930 faults
= group_faults_cpu(numa_group
, nid
);
1931 if (faults
> max_faults
)
1932 max_faults
= faults
;
1935 for_each_online_node(nid
) {
1936 faults
= group_faults_cpu(numa_group
, nid
);
1937 if (faults
* ACTIVE_NODE_FRACTION
> max_faults
)
1941 numa_group
->max_faults_cpu
= max_faults
;
1942 numa_group
->active_nodes
= active_nodes
;
1946 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1947 * increments. The more local the fault statistics are, the higher the scan
1948 * period will be for the next scan window. If local/(local+remote) ratio is
1949 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1950 * the scan period will decrease. Aim for 70% local accesses.
1952 #define NUMA_PERIOD_SLOTS 10
1953 #define NUMA_PERIOD_THRESHOLD 7
1956 * Increase the scan period (slow down scanning) if the majority of
1957 * our memory is already on our local node, or if the majority of
1958 * the page accesses are shared with other processes.
1959 * Otherwise, decrease the scan period.
1961 static void update_task_scan_period(struct task_struct
*p
,
1962 unsigned long shared
, unsigned long private)
1964 unsigned int period_slot
;
1965 int lr_ratio
, ps_ratio
;
1968 unsigned long remote
= p
->numa_faults_locality
[0];
1969 unsigned long local
= p
->numa_faults_locality
[1];
1972 * If there were no record hinting faults then either the task is
1973 * completely idle or all activity is areas that are not of interest
1974 * to automatic numa balancing. Related to that, if there were failed
1975 * migration then it implies we are migrating too quickly or the local
1976 * node is overloaded. In either case, scan slower
1978 if (local
+ shared
== 0 || p
->numa_faults_locality
[2]) {
1979 p
->numa_scan_period
= min(p
->numa_scan_period_max
,
1980 p
->numa_scan_period
<< 1);
1982 p
->mm
->numa_next_scan
= jiffies
+
1983 msecs_to_jiffies(p
->numa_scan_period
);
1989 * Prepare to scale scan period relative to the current period.
1990 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1991 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1992 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1994 period_slot
= DIV_ROUND_UP(p
->numa_scan_period
, NUMA_PERIOD_SLOTS
);
1995 lr_ratio
= (local
* NUMA_PERIOD_SLOTS
) / (local
+ remote
);
1996 ps_ratio
= (private * NUMA_PERIOD_SLOTS
) / (private + shared
);
1998 if (ps_ratio
>= NUMA_PERIOD_THRESHOLD
) {
2000 * Most memory accesses are local. There is no need to
2001 * do fast NUMA scanning, since memory is already local.
2003 int slot
= ps_ratio
- NUMA_PERIOD_THRESHOLD
;
2006 diff
= slot
* period_slot
;
2007 } else if (lr_ratio
>= NUMA_PERIOD_THRESHOLD
) {
2009 * Most memory accesses are shared with other tasks.
2010 * There is no point in continuing fast NUMA scanning,
2011 * since other tasks may just move the memory elsewhere.
2013 int slot
= lr_ratio
- NUMA_PERIOD_THRESHOLD
;
2016 diff
= slot
* period_slot
;
2019 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2020 * yet they are not on the local NUMA node. Speed up
2021 * NUMA scanning to get the memory moved over.
2023 int ratio
= max(lr_ratio
, ps_ratio
);
2024 diff
= -(NUMA_PERIOD_THRESHOLD
- ratio
) * period_slot
;
2027 p
->numa_scan_period
= clamp(p
->numa_scan_period
+ diff
,
2028 task_scan_min(p
), task_scan_max(p
));
2029 memset(p
->numa_faults_locality
, 0, sizeof(p
->numa_faults_locality
));
2033 * Get the fraction of time the task has been running since the last
2034 * NUMA placement cycle. The scheduler keeps similar statistics, but
2035 * decays those on a 32ms period, which is orders of magnitude off
2036 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2037 * stats only if the task is so new there are no NUMA statistics yet.
2039 static u64
numa_get_avg_runtime(struct task_struct
*p
, u64
*period
)
2041 u64 runtime
, delta
, now
;
2042 /* Use the start of this time slice to avoid calculations. */
2043 now
= p
->se
.exec_start
;
2044 runtime
= p
->se
.sum_exec_runtime
;
2046 if (p
->last_task_numa_placement
) {
2047 delta
= runtime
- p
->last_sum_exec_runtime
;
2048 *period
= now
- p
->last_task_numa_placement
;
2050 delta
= p
->se
.avg
.load_sum
/ p
->se
.load
.weight
;
2051 *period
= LOAD_AVG_MAX
;
2054 p
->last_sum_exec_runtime
= runtime
;
2055 p
->last_task_numa_placement
= now
;
2061 * Determine the preferred nid for a task in a numa_group. This needs to
2062 * be done in a way that produces consistent results with group_weight,
2063 * otherwise workloads might not converge.
2065 static int preferred_group_nid(struct task_struct
*p
, int nid
)
2070 /* Direct connections between all NUMA nodes. */
2071 if (sched_numa_topology_type
== NUMA_DIRECT
)
2075 * On a system with glueless mesh NUMA topology, group_weight
2076 * scores nodes according to the number of NUMA hinting faults on
2077 * both the node itself, and on nearby nodes.
2079 if (sched_numa_topology_type
== NUMA_GLUELESS_MESH
) {
2080 unsigned long score
, max_score
= 0;
2081 int node
, max_node
= nid
;
2083 dist
= sched_max_numa_distance
;
2085 for_each_online_node(node
) {
2086 score
= group_weight(p
, node
, dist
);
2087 if (score
> max_score
) {
2096 * Finding the preferred nid in a system with NUMA backplane
2097 * interconnect topology is more involved. The goal is to locate
2098 * tasks from numa_groups near each other in the system, and
2099 * untangle workloads from different sides of the system. This requires
2100 * searching down the hierarchy of node groups, recursively searching
2101 * inside the highest scoring group of nodes. The nodemask tricks
2102 * keep the complexity of the search down.
2104 nodes
= node_online_map
;
2105 for (dist
= sched_max_numa_distance
; dist
> LOCAL_DISTANCE
; dist
--) {
2106 unsigned long max_faults
= 0;
2107 nodemask_t max_group
= NODE_MASK_NONE
;
2110 /* Are there nodes at this distance from each other? */
2111 if (!find_numa_distance(dist
))
2114 for_each_node_mask(a
, nodes
) {
2115 unsigned long faults
= 0;
2116 nodemask_t this_group
;
2117 nodes_clear(this_group
);
2119 /* Sum group's NUMA faults; includes a==b case. */
2120 for_each_node_mask(b
, nodes
) {
2121 if (node_distance(a
, b
) < dist
) {
2122 faults
+= group_faults(p
, b
);
2123 node_set(b
, this_group
);
2124 node_clear(b
, nodes
);
2128 /* Remember the top group. */
2129 if (faults
> max_faults
) {
2130 max_faults
= faults
;
2131 max_group
= this_group
;
2133 * subtle: at the smallest distance there is
2134 * just one node left in each "group", the
2135 * winner is the preferred nid.
2140 /* Next round, evaluate the nodes within max_group. */
2148 static void task_numa_placement(struct task_struct
*p
)
2150 int seq
, nid
, max_nid
= -1, max_group_nid
= -1;
2151 unsigned long max_faults
= 0, max_group_faults
= 0;
2152 unsigned long fault_types
[2] = { 0, 0 };
2153 unsigned long total_faults
;
2154 u64 runtime
, period
;
2155 spinlock_t
*group_lock
= NULL
;
2158 * The p->mm->numa_scan_seq field gets updated without
2159 * exclusive access. Use READ_ONCE() here to ensure
2160 * that the field is read in a single access:
2162 seq
= READ_ONCE(p
->mm
->numa_scan_seq
);
2163 if (p
->numa_scan_seq
== seq
)
2165 p
->numa_scan_seq
= seq
;
2166 p
->numa_scan_period_max
= task_scan_max(p
);
2168 total_faults
= p
->numa_faults_locality
[0] +
2169 p
->numa_faults_locality
[1];
2170 runtime
= numa_get_avg_runtime(p
, &period
);
2172 /* If the task is part of a group prevent parallel updates to group stats */
2173 if (p
->numa_group
) {
2174 group_lock
= &p
->numa_group
->lock
;
2175 spin_lock_irq(group_lock
);
2178 /* Find the node with the highest number of faults */
2179 for_each_online_node(nid
) {
2180 /* Keep track of the offsets in numa_faults array */
2181 int mem_idx
, membuf_idx
, cpu_idx
, cpubuf_idx
;
2182 unsigned long faults
= 0, group_faults
= 0;
2185 for (priv
= 0; priv
< NR_NUMA_HINT_FAULT_TYPES
; priv
++) {
2186 long diff
, f_diff
, f_weight
;
2188 mem_idx
= task_faults_idx(NUMA_MEM
, nid
, priv
);
2189 membuf_idx
= task_faults_idx(NUMA_MEMBUF
, nid
, priv
);
2190 cpu_idx
= task_faults_idx(NUMA_CPU
, nid
, priv
);
2191 cpubuf_idx
= task_faults_idx(NUMA_CPUBUF
, nid
, priv
);
2193 /* Decay existing window, copy faults since last scan */
2194 diff
= p
->numa_faults
[membuf_idx
] - p
->numa_faults
[mem_idx
] / 2;
2195 fault_types
[priv
] += p
->numa_faults
[membuf_idx
];
2196 p
->numa_faults
[membuf_idx
] = 0;
2199 * Normalize the faults_from, so all tasks in a group
2200 * count according to CPU use, instead of by the raw
2201 * number of faults. Tasks with little runtime have
2202 * little over-all impact on throughput, and thus their
2203 * faults are less important.
2205 f_weight
= div64_u64(runtime
<< 16, period
+ 1);
2206 f_weight
= (f_weight
* p
->numa_faults
[cpubuf_idx
]) /
2208 f_diff
= f_weight
- p
->numa_faults
[cpu_idx
] / 2;
2209 p
->numa_faults
[cpubuf_idx
] = 0;
2211 p
->numa_faults
[mem_idx
] += diff
;
2212 p
->numa_faults
[cpu_idx
] += f_diff
;
2213 faults
+= p
->numa_faults
[mem_idx
];
2214 p
->total_numa_faults
+= diff
;
2215 if (p
->numa_group
) {
2217 * safe because we can only change our own group
2219 * mem_idx represents the offset for a given
2220 * nid and priv in a specific region because it
2221 * is at the beginning of the numa_faults array.
2223 p
->numa_group
->faults
[mem_idx
] += diff
;
2224 p
->numa_group
->faults_cpu
[mem_idx
] += f_diff
;
2225 p
->numa_group
->total_faults
+= diff
;
2226 group_faults
+= p
->numa_group
->faults
[mem_idx
];
2230 if (faults
> max_faults
) {
2231 max_faults
= faults
;
2235 if (group_faults
> max_group_faults
) {
2236 max_group_faults
= group_faults
;
2237 max_group_nid
= nid
;
2241 update_task_scan_period(p
, fault_types
[0], fault_types
[1]);
2243 if (p
->numa_group
) {
2244 numa_group_count_active_nodes(p
->numa_group
);
2245 spin_unlock_irq(group_lock
);
2246 max_nid
= preferred_group_nid(p
, max_group_nid
);
2250 /* Set the new preferred node */
2251 if (max_nid
!= p
->numa_preferred_nid
)
2252 sched_setnuma(p
, max_nid
);
2254 if (task_node(p
) != p
->numa_preferred_nid
)
2255 numa_migrate_preferred(p
);
2259 static inline int get_numa_group(struct numa_group
*grp
)
2261 return atomic_inc_not_zero(&grp
->refcount
);
2264 static inline void put_numa_group(struct numa_group
*grp
)
2266 if (atomic_dec_and_test(&grp
->refcount
))
2267 kfree_rcu(grp
, rcu
);
2270 static void task_numa_group(struct task_struct
*p
, int cpupid
, int flags
,
2273 struct numa_group
*grp
, *my_grp
;
2274 struct task_struct
*tsk
;
2276 int cpu
= cpupid_to_cpu(cpupid
);
2279 if (unlikely(!p
->numa_group
)) {
2280 unsigned int size
= sizeof(struct numa_group
) +
2281 4*nr_node_ids
*sizeof(unsigned long);
2283 grp
= kzalloc(size
, GFP_KERNEL
| __GFP_NOWARN
);
2287 atomic_set(&grp
->refcount
, 1);
2288 grp
->active_nodes
= 1;
2289 grp
->max_faults_cpu
= 0;
2290 spin_lock_init(&grp
->lock
);
2292 /* Second half of the array tracks nids where faults happen */
2293 grp
->faults_cpu
= grp
->faults
+ NR_NUMA_HINT_FAULT_TYPES
*
2296 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++)
2297 grp
->faults
[i
] = p
->numa_faults
[i
];
2299 grp
->total_faults
= p
->total_numa_faults
;
2302 rcu_assign_pointer(p
->numa_group
, grp
);
2306 tsk
= READ_ONCE(cpu_rq(cpu
)->curr
);
2308 if (!cpupid_match_pid(tsk
, cpupid
))
2311 grp
= rcu_dereference(tsk
->numa_group
);
2315 my_grp
= p
->numa_group
;
2320 * Only join the other group if its bigger; if we're the bigger group,
2321 * the other task will join us.
2323 if (my_grp
->nr_tasks
> grp
->nr_tasks
)
2327 * Tie-break on the grp address.
2329 if (my_grp
->nr_tasks
== grp
->nr_tasks
&& my_grp
> grp
)
2332 /* Always join threads in the same process. */
2333 if (tsk
->mm
== current
->mm
)
2336 /* Simple filter to avoid false positives due to PID collisions */
2337 if (flags
& TNF_SHARED
)
2340 /* Update priv based on whether false sharing was detected */
2343 if (join
&& !get_numa_group(grp
))
2351 BUG_ON(irqs_disabled());
2352 double_lock_irq(&my_grp
->lock
, &grp
->lock
);
2354 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++) {
2355 my_grp
->faults
[i
] -= p
->numa_faults
[i
];
2356 grp
->faults
[i
] += p
->numa_faults
[i
];
2358 my_grp
->total_faults
-= p
->total_numa_faults
;
2359 grp
->total_faults
+= p
->total_numa_faults
;
2364 spin_unlock(&my_grp
->lock
);
2365 spin_unlock_irq(&grp
->lock
);
2367 rcu_assign_pointer(p
->numa_group
, grp
);
2369 put_numa_group(my_grp
);
2377 void task_numa_free(struct task_struct
*p
)
2379 struct numa_group
*grp
= p
->numa_group
;
2380 void *numa_faults
= p
->numa_faults
;
2381 unsigned long flags
;
2385 spin_lock_irqsave(&grp
->lock
, flags
);
2386 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++)
2387 grp
->faults
[i
] -= p
->numa_faults
[i
];
2388 grp
->total_faults
-= p
->total_numa_faults
;
2391 spin_unlock_irqrestore(&grp
->lock
, flags
);
2392 RCU_INIT_POINTER(p
->numa_group
, NULL
);
2393 put_numa_group(grp
);
2396 p
->numa_faults
= NULL
;
2401 * Got a PROT_NONE fault for a page on @node.
2403 void task_numa_fault(int last_cpupid
, int mem_node
, int pages
, int flags
)
2405 struct task_struct
*p
= current
;
2406 bool migrated
= flags
& TNF_MIGRATED
;
2407 int cpu_node
= task_node(current
);
2408 int local
= !!(flags
& TNF_FAULT_LOCAL
);
2409 struct numa_group
*ng
;
2412 if (!static_branch_likely(&sched_numa_balancing
))
2415 /* for example, ksmd faulting in a user's mm */
2419 /* Allocate buffer to track faults on a per-node basis */
2420 if (unlikely(!p
->numa_faults
)) {
2421 int size
= sizeof(*p
->numa_faults
) *
2422 NR_NUMA_HINT_FAULT_BUCKETS
* nr_node_ids
;
2424 p
->numa_faults
= kzalloc(size
, GFP_KERNEL
|__GFP_NOWARN
);
2425 if (!p
->numa_faults
)
2428 p
->total_numa_faults
= 0;
2429 memset(p
->numa_faults_locality
, 0, sizeof(p
->numa_faults_locality
));
2433 * First accesses are treated as private, otherwise consider accesses
2434 * to be private if the accessing pid has not changed
2436 if (unlikely(last_cpupid
== (-1 & LAST_CPUPID_MASK
))) {
2439 priv
= cpupid_match_pid(p
, last_cpupid
);
2440 if (!priv
&& !(flags
& TNF_NO_GROUP
))
2441 task_numa_group(p
, last_cpupid
, flags
, &priv
);
2445 * If a workload spans multiple NUMA nodes, a shared fault that
2446 * occurs wholly within the set of nodes that the workload is
2447 * actively using should be counted as local. This allows the
2448 * scan rate to slow down when a workload has settled down.
2451 if (!priv
&& !local
&& ng
&& ng
->active_nodes
> 1 &&
2452 numa_is_active_node(cpu_node
, ng
) &&
2453 numa_is_active_node(mem_node
, ng
))
2456 task_numa_placement(p
);
2459 * Retry task to preferred node migration periodically, in case it
2460 * case it previously failed, or the scheduler moved us.
2462 if (time_after(jiffies
, p
->numa_migrate_retry
))
2463 numa_migrate_preferred(p
);
2466 p
->numa_pages_migrated
+= pages
;
2467 if (flags
& TNF_MIGRATE_FAIL
)
2468 p
->numa_faults_locality
[2] += pages
;
2470 p
->numa_faults
[task_faults_idx(NUMA_MEMBUF
, mem_node
, priv
)] += pages
;
2471 p
->numa_faults
[task_faults_idx(NUMA_CPUBUF
, cpu_node
, priv
)] += pages
;
2472 p
->numa_faults_locality
[local
] += pages
;
2475 static void reset_ptenuma_scan(struct task_struct
*p
)
2478 * We only did a read acquisition of the mmap sem, so
2479 * p->mm->numa_scan_seq is written to without exclusive access
2480 * and the update is not guaranteed to be atomic. That's not
2481 * much of an issue though, since this is just used for
2482 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2483 * expensive, to avoid any form of compiler optimizations:
2485 WRITE_ONCE(p
->mm
->numa_scan_seq
, READ_ONCE(p
->mm
->numa_scan_seq
) + 1);
2486 p
->mm
->numa_scan_offset
= 0;
2490 * The expensive part of numa migration is done from task_work context.
2491 * Triggered from task_tick_numa().
2493 void task_numa_work(struct callback_head
*work
)
2495 unsigned long migrate
, next_scan
, now
= jiffies
;
2496 struct task_struct
*p
= current
;
2497 struct mm_struct
*mm
= p
->mm
;
2498 u64 runtime
= p
->se
.sum_exec_runtime
;
2499 struct vm_area_struct
*vma
;
2500 unsigned long start
, end
;
2501 unsigned long nr_pte_updates
= 0;
2502 long pages
, virtpages
;
2504 SCHED_WARN_ON(p
!= container_of(work
, struct task_struct
, numa_work
));
2506 work
->next
= work
; /* protect against double add */
2508 * Who cares about NUMA placement when they're dying.
2510 * NOTE: make sure not to dereference p->mm before this check,
2511 * exit_task_work() happens _after_ exit_mm() so we could be called
2512 * without p->mm even though we still had it when we enqueued this
2515 if (p
->flags
& PF_EXITING
)
2518 if (!mm
->numa_next_scan
) {
2519 mm
->numa_next_scan
= now
+
2520 msecs_to_jiffies(sysctl_numa_balancing_scan_delay
);
2524 * Enforce maximal scan/migration frequency..
2526 migrate
= mm
->numa_next_scan
;
2527 if (time_before(now
, migrate
))
2530 if (p
->numa_scan_period
== 0) {
2531 p
->numa_scan_period_max
= task_scan_max(p
);
2532 p
->numa_scan_period
= task_scan_start(p
);
2535 next_scan
= now
+ msecs_to_jiffies(p
->numa_scan_period
);
2536 if (cmpxchg(&mm
->numa_next_scan
, migrate
, next_scan
) != migrate
)
2540 * Delay this task enough that another task of this mm will likely win
2541 * the next time around.
2543 p
->node_stamp
+= 2 * TICK_NSEC
;
2545 start
= mm
->numa_scan_offset
;
2546 pages
= sysctl_numa_balancing_scan_size
;
2547 pages
<<= 20 - PAGE_SHIFT
; /* MB in pages */
2548 virtpages
= pages
* 8; /* Scan up to this much virtual space */
2553 if (!down_read_trylock(&mm
->mmap_sem
))
2555 vma
= find_vma(mm
, start
);
2557 reset_ptenuma_scan(p
);
2561 for (; vma
; vma
= vma
->vm_next
) {
2562 if (!vma_migratable(vma
) || !vma_policy_mof(vma
) ||
2563 is_vm_hugetlb_page(vma
) || (vma
->vm_flags
& VM_MIXEDMAP
)) {
2568 * Shared library pages mapped by multiple processes are not
2569 * migrated as it is expected they are cache replicated. Avoid
2570 * hinting faults in read-only file-backed mappings or the vdso
2571 * as migrating the pages will be of marginal benefit.
2574 (vma
->vm_file
&& (vma
->vm_flags
& (VM_READ
|VM_WRITE
)) == (VM_READ
)))
2578 * Skip inaccessible VMAs to avoid any confusion between
2579 * PROT_NONE and NUMA hinting ptes
2581 if (!(vma
->vm_flags
& (VM_READ
| VM_EXEC
| VM_WRITE
)))
2585 start
= max(start
, vma
->vm_start
);
2586 end
= ALIGN(start
+ (pages
<< PAGE_SHIFT
), HPAGE_SIZE
);
2587 end
= min(end
, vma
->vm_end
);
2588 nr_pte_updates
= change_prot_numa(vma
, start
, end
);
2591 * Try to scan sysctl_numa_balancing_size worth of
2592 * hpages that have at least one present PTE that
2593 * is not already pte-numa. If the VMA contains
2594 * areas that are unused or already full of prot_numa
2595 * PTEs, scan up to virtpages, to skip through those
2599 pages
-= (end
- start
) >> PAGE_SHIFT
;
2600 virtpages
-= (end
- start
) >> PAGE_SHIFT
;
2603 if (pages
<= 0 || virtpages
<= 0)
2607 } while (end
!= vma
->vm_end
);
2612 * It is possible to reach the end of the VMA list but the last few
2613 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2614 * would find the !migratable VMA on the next scan but not reset the
2615 * scanner to the start so check it now.
2618 mm
->numa_scan_offset
= start
;
2620 reset_ptenuma_scan(p
);
2621 up_read(&mm
->mmap_sem
);
2624 * Make sure tasks use at least 32x as much time to run other code
2625 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2626 * Usually update_task_scan_period slows down scanning enough; on an
2627 * overloaded system we need to limit overhead on a per task basis.
2629 if (unlikely(p
->se
.sum_exec_runtime
!= runtime
)) {
2630 u64 diff
= p
->se
.sum_exec_runtime
- runtime
;
2631 p
->node_stamp
+= 32 * diff
;
2636 * Drive the periodic memory faults..
2638 void task_tick_numa(struct rq
*rq
, struct task_struct
*curr
)
2640 struct callback_head
*work
= &curr
->numa_work
;
2644 * We don't care about NUMA placement if we don't have memory.
2646 if (!curr
->mm
|| (curr
->flags
& PF_EXITING
) || work
->next
!= work
)
2650 * Using runtime rather than walltime has the dual advantage that
2651 * we (mostly) drive the selection from busy threads and that the
2652 * task needs to have done some actual work before we bother with
2655 now
= curr
->se
.sum_exec_runtime
;
2656 period
= (u64
)curr
->numa_scan_period
* NSEC_PER_MSEC
;
2658 if (now
> curr
->node_stamp
+ period
) {
2659 if (!curr
->node_stamp
)
2660 curr
->numa_scan_period
= task_scan_start(curr
);
2661 curr
->node_stamp
+= period
;
2663 if (!time_before(jiffies
, curr
->mm
->numa_next_scan
)) {
2664 init_task_work(work
, task_numa_work
); /* TODO: move this into sched_fork() */
2665 task_work_add(curr
, work
, true);
2671 static void task_tick_numa(struct rq
*rq
, struct task_struct
*curr
)
2675 static inline void account_numa_enqueue(struct rq
*rq
, struct task_struct
*p
)
2679 static inline void account_numa_dequeue(struct rq
*rq
, struct task_struct
*p
)
2683 #endif /* CONFIG_NUMA_BALANCING */
2686 account_entity_enqueue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
2688 update_load_add(&cfs_rq
->load
, se
->load
.weight
);
2689 if (!parent_entity(se
))
2690 update_load_add(&rq_of(cfs_rq
)->load
, se
->load
.weight
);
2692 if (entity_is_task(se
)) {
2693 struct rq
*rq
= rq_of(cfs_rq
);
2695 account_numa_enqueue(rq
, task_of(se
));
2696 list_add(&se
->group_node
, &rq
->cfs_tasks
);
2699 cfs_rq
->nr_running
++;
2703 account_entity_dequeue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
2705 update_load_sub(&cfs_rq
->load
, se
->load
.weight
);
2706 if (!parent_entity(se
))
2707 update_load_sub(&rq_of(cfs_rq
)->load
, se
->load
.weight
);
2709 if (entity_is_task(se
)) {
2710 account_numa_dequeue(rq_of(cfs_rq
), task_of(se
));
2711 list_del_init(&se
->group_node
);
2714 cfs_rq
->nr_running
--;
2717 #ifdef CONFIG_FAIR_GROUP_SCHED
2719 static long calc_cfs_shares(struct cfs_rq
*cfs_rq
, struct task_group
*tg
)
2721 long tg_weight
, load
, shares
;
2724 * This really should be: cfs_rq->avg.load_avg, but instead we use
2725 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2726 * the shares for small weight interactive tasks.
2728 load
= scale_load_down(cfs_rq
->load
.weight
);
2730 tg_weight
= atomic_long_read(&tg
->load_avg
);
2732 /* Ensure tg_weight >= load */
2733 tg_weight
-= cfs_rq
->tg_load_avg_contrib
;
2736 shares
= (tg
->shares
* load
);
2738 shares
/= tg_weight
;
2741 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
2742 * of a group with small tg->shares value. It is a floor value which is
2743 * assigned as a minimum load.weight to the sched_entity representing
2744 * the group on a CPU.
2746 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
2747 * on an 8-core system with 8 tasks each runnable on one CPU shares has
2748 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
2749 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
2752 if (shares
< MIN_SHARES
)
2753 shares
= MIN_SHARES
;
2754 if (shares
> tg
->shares
)
2755 shares
= tg
->shares
;
2759 # else /* CONFIG_SMP */
2760 static inline long calc_cfs_shares(struct cfs_rq
*cfs_rq
, struct task_group
*tg
)
2764 # endif /* CONFIG_SMP */
2766 static void reweight_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
2767 unsigned long weight
)
2770 /* commit outstanding execution time */
2771 if (cfs_rq
->curr
== se
)
2772 update_curr(cfs_rq
);
2773 account_entity_dequeue(cfs_rq
, se
);
2776 update_load_set(&se
->load
, weight
);
2779 account_entity_enqueue(cfs_rq
, se
);
2782 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
);
2784 static void update_cfs_shares(struct sched_entity
*se
)
2786 struct cfs_rq
*cfs_rq
= group_cfs_rq(se
);
2787 struct task_group
*tg
;
2793 if (throttled_hierarchy(cfs_rq
))
2799 if (likely(se
->load
.weight
== tg
->shares
))
2802 shares
= calc_cfs_shares(cfs_rq
, tg
);
2804 reweight_entity(cfs_rq_of(se
), se
, shares
);
2807 #else /* CONFIG_FAIR_GROUP_SCHED */
2808 static inline void update_cfs_shares(struct sched_entity
*se
)
2811 #endif /* CONFIG_FAIR_GROUP_SCHED */
2813 static inline void cfs_rq_util_change(struct cfs_rq
*cfs_rq
)
2815 struct rq
*rq
= rq_of(cfs_rq
);
2817 if (&rq
->cfs
== cfs_rq
) {
2819 * There are a few boundary cases this might miss but it should
2820 * get called often enough that that should (hopefully) not be
2821 * a real problem -- added to that it only calls on the local
2822 * CPU, so if we enqueue remotely we'll miss an update, but
2823 * the next tick/schedule should update.
2825 * It will not get called when we go idle, because the idle
2826 * thread is a different class (!fair), nor will the utilization
2827 * number include things like RT tasks.
2829 * As is, the util number is not freq-invariant (we'd have to
2830 * implement arch_scale_freq_capacity() for that).
2834 cpufreq_update_util(rq
, 0);
2841 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2843 static u64
decay_load(u64 val
, u64 n
)
2845 unsigned int local_n
;
2847 if (unlikely(n
> LOAD_AVG_PERIOD
* 63))
2850 /* after bounds checking we can collapse to 32-bit */
2854 * As y^PERIOD = 1/2, we can combine
2855 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2856 * With a look-up table which covers y^n (n<PERIOD)
2858 * To achieve constant time decay_load.
2860 if (unlikely(local_n
>= LOAD_AVG_PERIOD
)) {
2861 val
>>= local_n
/ LOAD_AVG_PERIOD
;
2862 local_n
%= LOAD_AVG_PERIOD
;
2865 val
= mul_u64_u32_shr(val
, runnable_avg_yN_inv
[local_n
], 32);
2869 static u32
__accumulate_pelt_segments(u64 periods
, u32 d1
, u32 d3
)
2871 u32 c1
, c2
, c3
= d3
; /* y^0 == 1 */
2876 c1
= decay_load((u64
)d1
, periods
);
2880 * c2 = 1024 \Sum y^n
2884 * = 1024 ( \Sum y^n - \Sum y^n - y^0 )
2887 c2
= LOAD_AVG_MAX
- decay_load(LOAD_AVG_MAX
, periods
) - 1024;
2889 return c1
+ c2
+ c3
;
2892 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
2895 * Accumulate the three separate parts of the sum; d1 the remainder
2896 * of the last (incomplete) period, d2 the span of full periods and d3
2897 * the remainder of the (incomplete) current period.
2902 * |<->|<----------------->|<--->|
2903 * ... |---x---|------| ... |------|-----x (now)
2906 * u' = (u + d1) y^p + 1024 \Sum y^n + d3 y^0
2909 * = u y^p + (Step 1)
2912 * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2)
2915 static __always_inline u32
2916 accumulate_sum(u64 delta
, int cpu
, struct sched_avg
*sa
,
2917 unsigned long weight
, int running
, struct cfs_rq
*cfs_rq
)
2919 unsigned long scale_freq
, scale_cpu
;
2920 u32 contrib
= (u32
)delta
; /* p == 0 -> delta < 1024 */
2923 scale_freq
= arch_scale_freq_capacity(NULL
, cpu
);
2924 scale_cpu
= arch_scale_cpu_capacity(NULL
, cpu
);
2926 delta
+= sa
->period_contrib
;
2927 periods
= delta
/ 1024; /* A period is 1024us (~1ms) */
2930 * Step 1: decay old *_sum if we crossed period boundaries.
2933 sa
->load_sum
= decay_load(sa
->load_sum
, periods
);
2935 cfs_rq
->runnable_load_sum
=
2936 decay_load(cfs_rq
->runnable_load_sum
, periods
);
2938 sa
->util_sum
= decay_load((u64
)(sa
->util_sum
), periods
);
2944 contrib
= __accumulate_pelt_segments(periods
,
2945 1024 - sa
->period_contrib
, delta
);
2947 sa
->period_contrib
= delta
;
2949 contrib
= cap_scale(contrib
, scale_freq
);
2951 sa
->load_sum
+= weight
* contrib
;
2953 cfs_rq
->runnable_load_sum
+= weight
* contrib
;
2956 sa
->util_sum
+= contrib
* scale_cpu
;
2962 * We can represent the historical contribution to runnable average as the
2963 * coefficients of a geometric series. To do this we sub-divide our runnable
2964 * history into segments of approximately 1ms (1024us); label the segment that
2965 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2967 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2969 * (now) (~1ms ago) (~2ms ago)
2971 * Let u_i denote the fraction of p_i that the entity was runnable.
2973 * We then designate the fractions u_i as our co-efficients, yielding the
2974 * following representation of historical load:
2975 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2977 * We choose y based on the with of a reasonably scheduling period, fixing:
2980 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2981 * approximately half as much as the contribution to load within the last ms
2984 * When a period "rolls over" and we have new u_0`, multiplying the previous
2985 * sum again by y is sufficient to update:
2986 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2987 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2989 static __always_inline
int
2990 ___update_load_avg(u64 now
, int cpu
, struct sched_avg
*sa
,
2991 unsigned long weight
, int running
, struct cfs_rq
*cfs_rq
,
2992 struct rt_rq
*rt_rq
)
2996 delta
= now
- sa
->last_update_time
;
2998 * This should only happen when time goes backwards, which it
2999 * unfortunately does during sched clock init when we swap over to TSC.
3001 if ((s64
)delta
< 0) {
3002 sa
->last_update_time
= now
;
3007 * Use 1024ns as the unit of measurement since it's a reasonable
3008 * approximation of 1us and fast to compute.
3014 sa
->last_update_time
+= delta
<< 10;
3017 * running is a subset of runnable (weight) so running can't be set if
3018 * runnable is clear. But there are some corner cases where the current
3019 * se has been already dequeued but cfs_rq->curr still points to it.
3020 * This means that weight will be 0 but not running for a sched_entity
3021 * but also for a cfs_rq if the latter becomes idle. As an example,
3022 * this happens during idle_balance() which calls
3023 * update_blocked_averages()
3029 * Now we know we crossed measurement unit boundaries. The *_avg
3030 * accrues by two steps:
3032 * Step 1: accumulate *_sum since last_update_time. If we haven't
3033 * crossed period boundaries, finish.
3035 if (!accumulate_sum(delta
, cpu
, sa
, weight
, running
, cfs_rq
))
3039 * Step 2: update *_avg.
3041 sa
->load_avg
= div_u64(sa
->load_sum
, LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3043 cfs_rq
->runnable_load_avg
=
3044 div_u64(cfs_rq
->runnable_load_sum
, LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3046 sa
->util_avg
= sa
->util_sum
/ (LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3049 trace_sched_load_cfs_rq(cfs_rq
);
3052 trace_sched_load_se(container_of(sa
, struct sched_entity
, avg
));
3054 trace_sched_load_rt_rq(cpu
, rt_rq
);
3061 * When a task is dequeued, its estimated utilization should not be update if
3062 * its util_avg has not been updated at least once.
3063 * This flag is used to synchronize util_avg updates with util_est updates.
3064 * We map this information into the LSB bit of the utilization saved at
3065 * dequeue time (i.e. util_est.dequeued).
3067 #define UTIL_AVG_UNCHANGED 0x1
3069 static inline void cfs_se_util_change(struct sched_avg
*avg
)
3071 unsigned int enqueued
;
3073 if (!sched_feat(UTIL_EST
))
3076 /* Avoid store if the flag has been already set */
3077 enqueued
= avg
->util_est
.enqueued
;
3078 if (!(enqueued
& UTIL_AVG_UNCHANGED
))
3081 /* Reset flag to report util_avg has been updated */
3082 enqueued
&= ~UTIL_AVG_UNCHANGED
;
3083 WRITE_ONCE(avg
->util_est
.enqueued
, enqueued
);
3087 __update_load_avg_blocked_se(u64 now
, int cpu
, struct sched_entity
*se
)
3089 return ___update_load_avg(now
, cpu
, &se
->avg
, 0, 0, NULL
, NULL
);
3093 __update_load_avg_se(u64 now
, int cpu
, struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3095 if (___update_load_avg(now
, cpu
, &se
->avg
,
3096 se
->on_rq
* scale_load_down(se
->load
.weight
),
3097 cfs_rq
->curr
== se
, NULL
, NULL
)) {
3098 cfs_se_util_change(&se
->avg
);
3100 #ifdef UTIL_EST_DEBUG
3102 * Trace utilization only for actual tasks.
3104 * These trace events are mostly useful to get easier to
3105 * read plots for the estimated utilization, where we can
3106 * compare it with the actual grow/decrease of the original
3108 * Let's keep them disabled by default in "production kernels".
3110 if (entity_is_task(se
)) {
3111 struct task_struct
*tsk
= task_of(se
);
3113 trace_sched_util_est_task(tsk
, &se
->avg
);
3115 /* Trace utilization only for top level CFS RQ */
3116 cfs_rq
= &(task_rq(tsk
)->cfs
);
3117 trace_sched_util_est_cpu(cpu
, cfs_rq
);
3119 #endif /* UTIL_EST_DEBUG */
3128 __update_load_avg_cfs_rq(u64 now
, int cpu
, struct cfs_rq
*cfs_rq
)
3130 return ___update_load_avg(now
, cpu
, &cfs_rq
->avg
,
3131 scale_load_down(cfs_rq
->load
.weight
),
3132 cfs_rq
->curr
!= NULL
, cfs_rq
, NULL
);
3136 * Signed add and clamp on underflow.
3138 * Explicitly do a load-store to ensure the intermediate value never hits
3139 * memory. This allows lockless observations without ever seeing the negative
3142 #define add_positive(_ptr, _val) do { \
3143 typeof(_ptr) ptr = (_ptr); \
3144 typeof(_val) val = (_val); \
3145 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3149 if (val < 0 && res > var) \
3152 WRITE_ONCE(*ptr, res); \
3155 #ifdef CONFIG_FAIR_GROUP_SCHED
3157 * update_tg_load_avg - update the tg's load avg
3158 * @cfs_rq: the cfs_rq whose avg changed
3159 * @force: update regardless of how small the difference
3161 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3162 * However, because tg->load_avg is a global value there are performance
3165 * In order to avoid having to look at the other cfs_rq's, we use a
3166 * differential update where we store the last value we propagated. This in
3167 * turn allows skipping updates if the differential is 'small'.
3169 * Updating tg's load_avg is necessary before update_cfs_share().
3171 static inline void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
)
3173 long delta
= cfs_rq
->avg
.load_avg
- cfs_rq
->tg_load_avg_contrib
;
3176 * No need to update load_avg for root_task_group as it is not used.
3178 if (cfs_rq
->tg
== &root_task_group
)
3181 if (force
|| abs(delta
) > cfs_rq
->tg_load_avg_contrib
/ 64) {
3182 atomic_long_add(delta
, &cfs_rq
->tg
->load_avg
);
3183 cfs_rq
->tg_load_avg_contrib
= cfs_rq
->avg
.load_avg
;
3186 trace_sched_load_tg(cfs_rq
);
3190 * Called within set_task_rq() right before setting a task's cpu. The
3191 * caller only guarantees p->pi_lock is held; no other assumptions,
3192 * including the state of rq->lock, should be made.
3194 void set_task_rq_fair(struct sched_entity
*se
,
3195 struct cfs_rq
*prev
, struct cfs_rq
*next
)
3197 u64 p_last_update_time
;
3198 u64 n_last_update_time
;
3200 if (!sched_feat(ATTACH_AGE_LOAD
))
3204 * We are supposed to update the task to "current" time, then its up to
3205 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3206 * getting what current time is, so simply throw away the out-of-date
3207 * time. This will result in the wakee task is less decayed, but giving
3208 * the wakee more load sounds not bad.
3210 if (!(se
->avg
.last_update_time
&& prev
))
3213 #ifndef CONFIG_64BIT
3215 u64 p_last_update_time_copy
;
3216 u64 n_last_update_time_copy
;
3219 p_last_update_time_copy
= prev
->load_last_update_time_copy
;
3220 n_last_update_time_copy
= next
->load_last_update_time_copy
;
3224 p_last_update_time
= prev
->avg
.last_update_time
;
3225 n_last_update_time
= next
->avg
.last_update_time
;
3227 } while (p_last_update_time
!= p_last_update_time_copy
||
3228 n_last_update_time
!= n_last_update_time_copy
);
3231 p_last_update_time
= prev
->avg
.last_update_time
;
3232 n_last_update_time
= next
->avg
.last_update_time
;
3234 __update_load_avg_blocked_se(p_last_update_time
, cpu_of(rq_of(prev
)), se
);
3235 se
->avg
.last_update_time
= n_last_update_time
;
3238 /* Take into account change of utilization of a child task group */
3240 update_tg_cfs_util(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3242 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3243 long delta
= gcfs_rq
->avg
.util_avg
- se
->avg
.util_avg
;
3245 /* Nothing to update */
3249 /* Set new sched_entity's utilization */
3250 se
->avg
.util_avg
= gcfs_rq
->avg
.util_avg
;
3251 se
->avg
.util_sum
= se
->avg
.util_avg
* LOAD_AVG_MAX
;
3253 /* Update parent cfs_rq utilization */
3254 add_positive(&cfs_rq
->avg
.util_avg
, delta
);
3255 cfs_rq
->avg
.util_sum
= cfs_rq
->avg
.util_avg
* LOAD_AVG_MAX
;
3258 /* Take into account change of load of a child task group */
3260 update_tg_cfs_load(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3262 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3263 long delta
, load
= gcfs_rq
->avg
.load_avg
;
3266 * If the load of group cfs_rq is null, the load of the
3267 * sched_entity will also be null so we can skip the formula
3272 /* Get tg's load and ensure tg_load > 0 */
3273 tg_load
= atomic_long_read(&gcfs_rq
->tg
->load_avg
) + 1;
3275 /* Ensure tg_load >= load and updated with current load*/
3276 tg_load
-= gcfs_rq
->tg_load_avg_contrib
;
3280 * We need to compute a correction term in the case that the
3281 * task group is consuming more CPU than a task of equal
3282 * weight. A task with a weight equals to tg->shares will have
3283 * a load less or equal to scale_load_down(tg->shares).
3284 * Similarly, the sched_entities that represent the task group
3285 * at parent level, can't have a load higher than
3286 * scale_load_down(tg->shares). And the Sum of sched_entities'
3287 * load must be <= scale_load_down(tg->shares).
3289 if (tg_load
> scale_load_down(gcfs_rq
->tg
->shares
)) {
3290 /* scale gcfs_rq's load into tg's shares*/
3291 load
*= scale_load_down(gcfs_rq
->tg
->shares
);
3296 delta
= load
- se
->avg
.load_avg
;
3298 /* Nothing to update */
3302 /* Set new sched_entity's load */
3303 se
->avg
.load_avg
= load
;
3304 se
->avg
.load_sum
= se
->avg
.load_avg
* LOAD_AVG_MAX
;
3306 /* Update parent cfs_rq load */
3307 add_positive(&cfs_rq
->avg
.load_avg
, delta
);
3308 cfs_rq
->avg
.load_sum
= cfs_rq
->avg
.load_avg
* LOAD_AVG_MAX
;
3311 * If the sched_entity is already enqueued, we also have to update the
3312 * runnable load avg.
3315 /* Update parent cfs_rq runnable_load_avg */
3316 add_positive(&cfs_rq
->runnable_load_avg
, delta
);
3317 cfs_rq
->runnable_load_sum
= cfs_rq
->runnable_load_avg
* LOAD_AVG_MAX
;
3321 static inline void set_tg_cfs_propagate(struct cfs_rq
*cfs_rq
)
3323 cfs_rq
->propagate_avg
= 1;
3326 static inline int test_and_clear_tg_cfs_propagate(struct sched_entity
*se
)
3328 struct cfs_rq
*cfs_rq
= group_cfs_rq(se
);
3330 if (!cfs_rq
->propagate_avg
)
3333 cfs_rq
->propagate_avg
= 0;
3337 /* Update task and its cfs_rq load average */
3338 static inline int propagate_entity_load_avg(struct sched_entity
*se
)
3340 struct cfs_rq
*cfs_rq
;
3342 if (entity_is_task(se
))
3345 if (!test_and_clear_tg_cfs_propagate(se
))
3348 cfs_rq
= cfs_rq_of(se
);
3350 set_tg_cfs_propagate(cfs_rq
);
3352 update_tg_cfs_util(cfs_rq
, se
);
3353 update_tg_cfs_load(cfs_rq
, se
);
3355 trace_sched_load_cfs_rq(cfs_rq
);
3356 trace_sched_load_se(se
);
3362 * Check if we need to update the load and the utilization of a blocked
3365 static inline bool skip_blocked_update(struct sched_entity
*se
)
3367 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3370 * If sched_entity still have not zero load or utilization, we have to
3373 if (se
->avg
.load_avg
|| se
->avg
.util_avg
)
3377 * If there is a pending propagation, we have to update the load and
3378 * the utilization of the sched_entity:
3380 if (gcfs_rq
->propagate_avg
)
3384 * Otherwise, the load and the utilization of the sched_entity is
3385 * already zero and there is no pending propagation, so it will be a
3386 * waste of time to try to decay it:
3391 #else /* CONFIG_FAIR_GROUP_SCHED */
3393 static inline void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
) {}
3395 static inline int propagate_entity_load_avg(struct sched_entity
*se
)
3400 static inline void set_tg_cfs_propagate(struct cfs_rq
*cfs_rq
) {}
3402 #endif /* CONFIG_FAIR_GROUP_SCHED */
3405 * Unsigned subtract and clamp on underflow.
3407 * Explicitly do a load-store to ensure the intermediate value never hits
3408 * memory. This allows lockless observations without ever seeing the negative
3411 #define sub_positive(_ptr, _val) do { \
3412 typeof(_ptr) ptr = (_ptr); \
3413 typeof(*ptr) val = (_val); \
3414 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3418 WRITE_ONCE(*ptr, res); \
3422 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3423 * @now: current time, as per cfs_rq_clock_task()
3424 * @cfs_rq: cfs_rq to update
3426 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3427 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3428 * post_init_entity_util_avg().
3430 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3432 * Returns true if the load decayed or we removed load.
3434 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3435 * call update_tg_load_avg() when this function returns true.
3438 update_cfs_rq_load_avg(u64 now
, struct cfs_rq
*cfs_rq
)
3440 struct sched_avg
*sa
= &cfs_rq
->avg
;
3441 int decayed
, removed_load
= 0, removed_util
= 0;
3443 if (atomic_long_read(&cfs_rq
->removed_load_avg
)) {
3444 s64 r
= atomic_long_xchg(&cfs_rq
->removed_load_avg
, 0);
3445 sub_positive(&sa
->load_avg
, r
);
3446 sub_positive(&sa
->load_sum
, r
* LOAD_AVG_MAX
);
3448 set_tg_cfs_propagate(cfs_rq
);
3451 if (atomic_long_read(&cfs_rq
->removed_util_avg
)) {
3452 long r
= atomic_long_xchg(&cfs_rq
->removed_util_avg
, 0);
3453 sub_positive(&sa
->util_avg
, r
);
3454 sub_positive(&sa
->util_sum
, r
* LOAD_AVG_MAX
);
3456 set_tg_cfs_propagate(cfs_rq
);
3459 decayed
= __update_load_avg_cfs_rq(now
, cpu_of(rq_of(cfs_rq
)), cfs_rq
);
3461 #ifndef CONFIG_64BIT
3463 cfs_rq
->load_last_update_time_copy
= sa
->last_update_time
;
3466 if (decayed
|| removed_util
)
3467 cfs_rq_util_change(cfs_rq
);
3469 return decayed
|| removed_load
;
3472 int update_rt_rq_load_avg(u64 now
, int cpu
, struct rt_rq
*rt_rq
, int running
)
3476 ret
= ___update_load_avg(now
, cpu
, &rt_rq
->avg
, 0, running
, NULL
, rt_rq
);
3481 unsigned long sched_get_rt_rq_util(int cpu
)
3483 struct rt_rq
*rt_rq
= &(cpu_rq(cpu
)->rt
);
3484 return rt_rq
->avg
.util_avg
;
3488 * Optional action to be done while updating the load average
3490 #define UPDATE_TG 0x1
3491 #define SKIP_AGE_LOAD 0x2
3493 /* Update task and its cfs_rq load average */
3494 static inline void update_load_avg(struct sched_entity
*se
, int flags
)
3496 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3497 u64 now
= cfs_rq_clock_task(cfs_rq
);
3498 struct rq
*rq
= rq_of(cfs_rq
);
3499 int cpu
= cpu_of(rq
);
3503 * Track task load average for carrying it to new CPU after migrated, and
3504 * track group sched_entity load average for task_h_load calc in migration
3506 if (se
->avg
.last_update_time
&& !(flags
& SKIP_AGE_LOAD
))
3507 __update_load_avg_se(now
, cpu
, cfs_rq
, se
);
3509 decayed
= update_cfs_rq_load_avg(now
, cfs_rq
);
3510 decayed
|= propagate_entity_load_avg(se
);
3512 if (decayed
&& (flags
& UPDATE_TG
))
3513 update_tg_load_avg(cfs_rq
, 0);
3517 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3518 * @cfs_rq: cfs_rq to attach to
3519 * @se: sched_entity to attach
3521 * Must call update_cfs_rq_load_avg() before this, since we rely on
3522 * cfs_rq->avg.last_update_time being current.
3524 static void attach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3526 se
->avg
.last_update_time
= cfs_rq
->avg
.last_update_time
;
3527 cfs_rq
->avg
.load_avg
+= se
->avg
.load_avg
;
3528 cfs_rq
->avg
.load_sum
+= se
->avg
.load_sum
;
3529 cfs_rq
->avg
.util_avg
+= se
->avg
.util_avg
;
3530 cfs_rq
->avg
.util_sum
+= se
->avg
.util_sum
;
3531 set_tg_cfs_propagate(cfs_rq
);
3533 cfs_rq_util_change(cfs_rq
);
3535 trace_sched_load_cfs_rq(cfs_rq
);
3539 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3540 * @cfs_rq: cfs_rq to detach from
3541 * @se: sched_entity to detach
3543 * Must call update_cfs_rq_load_avg() before this, since we rely on
3544 * cfs_rq->avg.last_update_time being current.
3546 static void detach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3549 sub_positive(&cfs_rq
->avg
.load_avg
, se
->avg
.load_avg
);
3550 sub_positive(&cfs_rq
->avg
.load_sum
, se
->avg
.load_sum
);
3551 sub_positive(&cfs_rq
->avg
.util_avg
, se
->avg
.util_avg
);
3552 sub_positive(&cfs_rq
->avg
.util_sum
, se
->avg
.util_sum
);
3553 set_tg_cfs_propagate(cfs_rq
);
3555 cfs_rq_util_change(cfs_rq
);
3557 trace_sched_load_cfs_rq(cfs_rq
);
3560 /* Add the load generated by se into cfs_rq's load average */
3562 enqueue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3564 struct sched_avg
*sa
= &se
->avg
;
3566 cfs_rq
->runnable_load_avg
+= sa
->load_avg
;
3567 cfs_rq
->runnable_load_sum
+= sa
->load_sum
;
3569 if (!sa
->last_update_time
) {
3570 attach_entity_load_avg(cfs_rq
, se
);
3571 update_tg_load_avg(cfs_rq
, 0);
3575 /* Remove the runnable load generated by se from cfs_rq's runnable load average */
3577 dequeue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3579 cfs_rq
->runnable_load_avg
=
3580 max_t(long, cfs_rq
->runnable_load_avg
- se
->avg
.load_avg
, 0);
3581 cfs_rq
->runnable_load_sum
=
3582 max_t(s64
, cfs_rq
->runnable_load_sum
- se
->avg
.load_sum
, 0);
3585 #ifndef CONFIG_64BIT
3586 static inline u64
cfs_rq_last_update_time(struct cfs_rq
*cfs_rq
)
3588 u64 last_update_time_copy
;
3589 u64 last_update_time
;
3592 last_update_time_copy
= cfs_rq
->load_last_update_time_copy
;
3594 last_update_time
= cfs_rq
->avg
.last_update_time
;
3595 } while (last_update_time
!= last_update_time_copy
);
3597 return last_update_time
;
3600 static inline u64
cfs_rq_last_update_time(struct cfs_rq
*cfs_rq
)
3602 return cfs_rq
->avg
.last_update_time
;
3607 * Synchronize entity load avg of dequeued entity without locking
3610 void sync_entity_load_avg(struct sched_entity
*se
)
3612 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3613 u64 last_update_time
;
3615 last_update_time
= cfs_rq_last_update_time(cfs_rq
);
3616 __update_load_avg_blocked_se(last_update_time
, cpu_of(rq_of(cfs_rq
)), se
);
3620 * Task first catches up with cfs_rq, and then subtract
3621 * itself from the cfs_rq (task must be off the queue now).
3623 void remove_entity_load_avg(struct sched_entity
*se
)
3625 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3628 * tasks cannot exit without having gone through wake_up_new_task() ->
3629 * post_init_entity_util_avg() which will have added things to the
3630 * cfs_rq, so we can remove unconditionally.
3632 * Similarly for groups, they will have passed through
3633 * post_init_entity_util_avg() before unregister_sched_fair_group()
3637 sync_entity_load_avg(se
);
3638 atomic_long_add(se
->avg
.load_avg
, &cfs_rq
->removed_load_avg
);
3639 atomic_long_add(se
->avg
.util_avg
, &cfs_rq
->removed_util_avg
);
3642 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq
*cfs_rq
)
3644 return cfs_rq
->runnable_load_avg
;
3647 static inline unsigned long cfs_rq_load_avg(struct cfs_rq
*cfs_rq
)
3649 return cfs_rq
->avg
.load_avg
;
3652 static int idle_balance(struct rq
*this_rq
, struct rq_flags
*rf
);
3654 static inline int task_fits_capacity(struct task_struct
*p
, long capacity
);
3656 static inline void update_misfit_status(struct task_struct
*p
, struct rq
*rq
)
3658 if (!static_branch_unlikely(&sched_asym_cpucapacity
))
3662 rq
->misfit_task_load
= 0;
3666 if (task_fits_capacity(p
, capacity_of(cpu_of(rq
)))) {
3667 rq
->misfit_task_load
= 0;
3671 rq
->misfit_task_load
= task_h_load(p
);
3674 static inline unsigned long task_util(struct task_struct
*p
)
3676 #ifdef CONFIG_SCHED_WALT
3677 if (likely(!walt_disabled
&& sysctl_sched_use_walt_task_util
))
3678 return (p
->ravg
.demand
/
3679 (walt_ravg_window
>> SCHED_CAPACITY_SHIFT
));
3681 return READ_ONCE(p
->se
.avg
.util_avg
);
3684 static inline unsigned long _task_util_est(struct task_struct
*p
)
3686 struct util_est ue
= READ_ONCE(p
->se
.avg
.util_est
);
3688 return max(ue
.ewma
, ue
.enqueued
);
3691 static inline unsigned long task_util_est(struct task_struct
*p
)
3693 #ifdef CONFIG_SCHED_WALT
3694 if (likely(!walt_disabled
&& sysctl_sched_use_walt_task_util
))
3695 return (p
->ravg
.demand
/
3696 (walt_ravg_window
>> SCHED_CAPACITY_SHIFT
));
3698 return max(task_util(p
), _task_util_est(p
));
3701 static inline void util_est_enqueue(struct cfs_rq
*cfs_rq
,
3702 struct task_struct
*p
)
3704 unsigned int enqueued
;
3706 if (!sched_feat(UTIL_EST
))
3709 /* Update root cfs_rq's estimated utilization */
3710 enqueued
= cfs_rq
->avg
.util_est
.enqueued
;
3711 enqueued
+= (_task_util_est(p
) | UTIL_AVG_UNCHANGED
);
3712 WRITE_ONCE(cfs_rq
->avg
.util_est
.enqueued
, enqueued
);
3714 trace_sched_util_est_task(p
, &p
->se
.avg
);
3715 trace_sched_util_est_cpu(cpu_of(rq_of(cfs_rq
)), cfs_rq
);
3719 * Check if a (signed) value is within a specified (unsigned) margin,
3720 * based on the observation that:
3722 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
3724 * NOTE: this only works when value + maring < INT_MAX.
3726 static inline bool within_margin(int value
, int margin
)
3728 return ((unsigned int)(value
+ margin
- 1) < (2 * margin
- 1));
3732 util_est_dequeue(struct cfs_rq
*cfs_rq
, struct task_struct
*p
, bool task_sleep
)
3734 long last_ewma_diff
;
3737 if (!sched_feat(UTIL_EST
))
3741 * Update root cfs_rq's estimated utilization
3743 * If *p is the last task then the root cfs_rq's estimated utilization
3744 * of a CPU is 0 by definition.
3747 if (cfs_rq
->nr_running
) {
3748 ue
.enqueued
= cfs_rq
->avg
.util_est
.enqueued
;
3749 ue
.enqueued
-= min_t(unsigned int, ue
.enqueued
,
3750 (_task_util_est(p
) | UTIL_AVG_UNCHANGED
));
3752 WRITE_ONCE(cfs_rq
->avg
.util_est
.enqueued
, ue
.enqueued
);
3754 trace_sched_util_est_cpu(cpu_of(rq_of(cfs_rq
)), cfs_rq
);
3757 * Skip update of task's estimated utilization when the task has not
3758 * yet completed an activation, e.g. being migrated.
3764 * If the PELT values haven't changed since enqueue time,
3765 * skip the util_est update.
3767 ue
= p
->se
.avg
.util_est
;
3768 if (ue
.enqueued
& UTIL_AVG_UNCHANGED
)
3772 * Skip update of task's estimated utilization when its EWMA is
3773 * already ~1% close to its last activation value.
3775 ue
.enqueued
= (task_util(p
) | UTIL_AVG_UNCHANGED
);
3776 last_ewma_diff
= ue
.enqueued
- ue
.ewma
;
3777 if (within_margin(last_ewma_diff
, (SCHED_CAPACITY_SCALE
/ 100)))
3781 * Update Task's estimated utilization
3783 * When *p completes an activation we can consolidate another sample
3784 * of the task size. This is done by storing the current PELT value
3785 * as ue.enqueued and by using this value to update the Exponential
3786 * Weighted Moving Average (EWMA):
3788 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
3789 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
3790 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
3791 * = w * ( last_ewma_diff ) + ewma(t-1)
3792 * = w * (last_ewma_diff + ewma(t-1) / w)
3794 * Where 'w' is the weight of new samples, which is configured to be
3795 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
3797 ue
.ewma
<<= UTIL_EST_WEIGHT_SHIFT
;
3798 ue
.ewma
+= last_ewma_diff
;
3799 ue
.ewma
>>= UTIL_EST_WEIGHT_SHIFT
;
3800 WRITE_ONCE(p
->se
.avg
.util_est
, ue
);
3802 trace_sched_util_est_task(p
, &p
->se
.avg
);
3805 #else /* CONFIG_SMP */
3808 update_cfs_rq_load_avg(u64 now
, struct cfs_rq
*cfs_rq
)
3813 int update_rt_rq_load_avg(u64 now
, int cpu
, struct rt_rq
*rt_rq
, int running
)
3818 #define UPDATE_TG 0x0
3819 #define SKIP_AGE_LOAD 0x0
3821 static inline void update_load_avg(struct sched_entity
*se
, int not_used1
)
3823 cfs_rq_util_change(cfs_rq_of(se
));
3827 enqueue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3829 dequeue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3830 static inline void remove_entity_load_avg(struct sched_entity
*se
) {}
3833 attach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3835 detach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3837 static inline int idle_balance(struct rq
*rq
, struct rq_flags
*rf
)
3842 static inline void update_misfit_status(struct task_struct
*p
, struct rq
*rq
) {}
3845 util_est_enqueue(struct cfs_rq
*cfs_rq
, struct task_struct
*p
) {}
3848 util_est_dequeue(struct cfs_rq
*cfs_rq
, struct task_struct
*p
,
3851 #endif /* CONFIG_SMP */
3853 static void check_spread(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3855 #ifdef CONFIG_SCHED_DEBUG
3856 s64 d
= se
->vruntime
- cfs_rq
->min_vruntime
;
3861 if (d
> 3*sysctl_sched_latency
)
3862 schedstat_inc(cfs_rq
->nr_spread_over
);
3867 place_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int initial
)
3869 u64 vruntime
= cfs_rq
->min_vruntime
;
3872 * The 'current' period is already promised to the current tasks,
3873 * however the extra weight of the new task will slow them down a
3874 * little, place the new task so that it fits in the slot that
3875 * stays open at the end.
3877 if (initial
&& sched_feat(START_DEBIT
))
3878 vruntime
+= sched_vslice(cfs_rq
, se
);
3880 /* sleeps up to a single latency don't count. */
3882 unsigned long thresh
= sysctl_sched_latency
;
3885 * Halve their sleep time's effect, to allow
3886 * for a gentler effect of sleepers:
3888 if (sched_feat(GENTLE_FAIR_SLEEPERS
))
3894 /* ensure we never gain time by being placed backwards. */
3895 se
->vruntime
= max_vruntime(se
->vruntime
, vruntime
);
3898 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
);
3900 static inline void check_schedstat_required(void)
3902 #ifdef CONFIG_SCHEDSTATS
3903 if (schedstat_enabled())
3906 /* Force schedstat enabled if a dependent tracepoint is active */
3907 if (trace_sched_stat_wait_enabled() ||
3908 trace_sched_stat_sleep_enabled() ||
3909 trace_sched_stat_iowait_enabled() ||
3910 trace_sched_stat_blocked_enabled() ||
3911 trace_sched_stat_runtime_enabled()) {
3912 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
3913 "stat_blocked and stat_runtime require the "
3914 "kernel parameter schedstats=enable or "
3915 "kernel.sched_schedstats=1\n");
3926 * update_min_vruntime()
3927 * vruntime -= min_vruntime
3931 * update_min_vruntime()
3932 * vruntime += min_vruntime
3934 * this way the vruntime transition between RQs is done when both
3935 * min_vruntime are up-to-date.
3939 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
3940 * vruntime -= min_vruntime
3944 * update_min_vruntime()
3945 * vruntime += min_vruntime
3947 * this way we don't have the most up-to-date min_vruntime on the originating
3948 * CPU and an up-to-date min_vruntime on the destination CPU.
3952 enqueue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
3954 bool renorm
= !(flags
& ENQUEUE_WAKEUP
) || (flags
& ENQUEUE_MIGRATED
);
3955 bool curr
= cfs_rq
->curr
== se
;
3958 * If we're the current task, we must renormalise before calling
3962 se
->vruntime
+= cfs_rq
->min_vruntime
;
3964 update_curr(cfs_rq
);
3967 * Otherwise, renormalise after, such that we're placed at the current
3968 * moment in time, instead of some random moment in the past. Being
3969 * placed in the past could significantly boost this task to the
3970 * fairness detriment of existing tasks.
3972 if (renorm
&& !curr
)
3973 se
->vruntime
+= cfs_rq
->min_vruntime
;
3976 * When enqueuing a sched_entity, we must:
3977 * - Update loads to have both entity and cfs_rq synced with now.
3978 * - Add its load to cfs_rq->runnable_avg
3979 * - For group_entity, update its weight to reflect the new share of
3981 * - Add its new weight to cfs_rq->load.weight
3983 update_load_avg(se
, UPDATE_TG
);
3984 enqueue_entity_load_avg(cfs_rq
, se
);
3985 update_cfs_shares(se
);
3986 account_entity_enqueue(cfs_rq
, se
);
3988 if (flags
& ENQUEUE_WAKEUP
)
3989 place_entity(cfs_rq
, se
, 0);
3991 check_schedstat_required();
3992 update_stats_enqueue(cfs_rq
, se
, flags
);
3993 check_spread(cfs_rq
, se
);
3995 __enqueue_entity(cfs_rq
, se
);
3998 if (cfs_rq
->nr_running
== 1) {
3999 list_add_leaf_cfs_rq(cfs_rq
);
4000 check_enqueue_throttle(cfs_rq
);
4004 static void __clear_buddies_last(struct sched_entity
*se
)
4006 for_each_sched_entity(se
) {
4007 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
4008 if (cfs_rq
->last
!= se
)
4011 cfs_rq
->last
= NULL
;
4015 static void __clear_buddies_next(struct sched_entity
*se
)
4017 for_each_sched_entity(se
) {
4018 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
4019 if (cfs_rq
->next
!= se
)
4022 cfs_rq
->next
= NULL
;
4026 static void __clear_buddies_skip(struct sched_entity
*se
)
4028 for_each_sched_entity(se
) {
4029 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
4030 if (cfs_rq
->skip
!= se
)
4033 cfs_rq
->skip
= NULL
;
4037 static void clear_buddies(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
4039 if (cfs_rq
->last
== se
)
4040 __clear_buddies_last(se
);
4042 if (cfs_rq
->next
== se
)
4043 __clear_buddies_next(se
);
4045 if (cfs_rq
->skip
== se
)
4046 __clear_buddies_skip(se
);
4049 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
);
4052 dequeue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
4055 * Update run-time statistics of the 'current'.
4057 update_curr(cfs_rq
);
4060 * When dequeuing a sched_entity, we must:
4061 * - Update loads to have both entity and cfs_rq synced with now.
4062 * - Substract its load from the cfs_rq->runnable_avg.
4063 * - Substract its previous weight from cfs_rq->load.weight.
4064 * - For group entity, update its weight to reflect the new share
4065 * of its group cfs_rq.
4067 update_load_avg(se
, UPDATE_TG
);
4068 dequeue_entity_load_avg(cfs_rq
, se
);
4070 update_stats_dequeue(cfs_rq
, se
, flags
);
4072 clear_buddies(cfs_rq
, se
);
4074 if (se
!= cfs_rq
->curr
)
4075 __dequeue_entity(cfs_rq
, se
);
4077 account_entity_dequeue(cfs_rq
, se
);
4080 * Normalize after update_curr(); which will also have moved
4081 * min_vruntime if @se is the one holding it back. But before doing
4082 * update_min_vruntime() again, which will discount @se's position and
4083 * can move min_vruntime forward still more.
4085 if (!(flags
& DEQUEUE_SLEEP
))
4086 se
->vruntime
-= cfs_rq
->min_vruntime
;
4088 /* return excess runtime on last dequeue */
4089 return_cfs_rq_runtime(cfs_rq
);
4091 update_cfs_shares(se
);
4094 * Now advance min_vruntime if @se was the entity holding it back,
4095 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4096 * put back on, and if we advance min_vruntime, we'll be placed back
4097 * further than we started -- ie. we'll be penalized.
4099 if ((flags
& (DEQUEUE_SAVE
| DEQUEUE_MOVE
)) == DEQUEUE_SAVE
)
4100 update_min_vruntime(cfs_rq
);
4104 * Preempt the current task with a newly woken task if needed:
4107 check_preempt_tick(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
)
4109 unsigned long ideal_runtime
, delta_exec
;
4110 struct sched_entity
*se
;
4113 ideal_runtime
= sched_slice(cfs_rq
, curr
);
4114 delta_exec
= curr
->sum_exec_runtime
- curr
->prev_sum_exec_runtime
;
4115 if (delta_exec
> ideal_runtime
) {
4116 resched_curr(rq_of(cfs_rq
));
4118 * The current task ran long enough, ensure it doesn't get
4119 * re-elected due to buddy favours.
4121 clear_buddies(cfs_rq
, curr
);
4126 * Ensure that a task that missed wakeup preemption by a
4127 * narrow margin doesn't have to wait for a full slice.
4128 * This also mitigates buddy induced latencies under load.
4130 if (delta_exec
< sysctl_sched_min_granularity
)
4133 se
= __pick_first_entity(cfs_rq
);
4134 delta
= curr
->vruntime
- se
->vruntime
;
4139 if (delta
> ideal_runtime
)
4140 resched_curr(rq_of(cfs_rq
));
4144 set_next_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
4146 /* 'current' is not kept within the tree. */
4149 * Any task has to be enqueued before it get to execute on
4150 * a CPU. So account for the time it spent waiting on the
4153 update_stats_wait_end(cfs_rq
, se
);
4154 __dequeue_entity(cfs_rq
, se
);
4155 update_load_avg(se
, UPDATE_TG
);
4158 update_stats_curr_start(cfs_rq
, se
);
4162 * Track our maximum slice length, if the CPU's load is at
4163 * least twice that of our own weight (i.e. dont track it
4164 * when there are only lesser-weight tasks around):
4166 if (schedstat_enabled() && rq_of(cfs_rq
)->load
.weight
>= 2*se
->load
.weight
) {
4167 schedstat_set(se
->statistics
.slice_max
,
4168 max((u64
)schedstat_val(se
->statistics
.slice_max
),
4169 se
->sum_exec_runtime
- se
->prev_sum_exec_runtime
));
4172 se
->prev_sum_exec_runtime
= se
->sum_exec_runtime
;
4176 wakeup_preempt_entity(struct sched_entity
*curr
, struct sched_entity
*se
);
4179 * Pick the next process, keeping these things in mind, in this order:
4180 * 1) keep things fair between processes/task groups
4181 * 2) pick the "next" process, since someone really wants that to run
4182 * 3) pick the "last" process, for cache locality
4183 * 4) do not run the "skip" process, if something else is available
4185 static struct sched_entity
*
4186 pick_next_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
)
4188 struct sched_entity
*left
= __pick_first_entity(cfs_rq
);
4189 struct sched_entity
*se
;
4192 * If curr is set we have to see if its left of the leftmost entity
4193 * still in the tree, provided there was anything in the tree at all.
4195 if (!left
|| (curr
&& entity_before(curr
, left
)))
4198 se
= left
; /* ideally we run the leftmost entity */
4201 * Avoid running the skip buddy, if running something else can
4202 * be done without getting too unfair.
4204 if (cfs_rq
->skip
== se
) {
4205 struct sched_entity
*second
;
4208 second
= __pick_first_entity(cfs_rq
);
4210 second
= __pick_next_entity(se
);
4211 if (!second
|| (curr
&& entity_before(curr
, second
)))
4215 if (second
&& wakeup_preempt_entity(second
, left
) < 1)
4220 * Prefer last buddy, try to return the CPU to a preempted task.
4222 if (cfs_rq
->last
&& wakeup_preempt_entity(cfs_rq
->last
, left
) < 1)
4226 * Someone really wants this to run. If it's not unfair, run it.
4228 if (cfs_rq
->next
&& wakeup_preempt_entity(cfs_rq
->next
, left
) < 1)
4231 clear_buddies(cfs_rq
, se
);
4236 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
);
4238 static void put_prev_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*prev
)
4241 * If still on the runqueue then deactivate_task()
4242 * was not called and update_curr() has to be done:
4245 update_curr(cfs_rq
);
4247 /* throttle cfs_rqs exceeding runtime */
4248 check_cfs_rq_runtime(cfs_rq
);
4250 check_spread(cfs_rq
, prev
);
4253 update_stats_wait_start(cfs_rq
, prev
);
4254 /* Put 'current' back into the tree. */
4255 __enqueue_entity(cfs_rq
, prev
);
4256 /* in !on_rq case, update occurred at dequeue */
4257 update_load_avg(prev
, 0);
4259 cfs_rq
->curr
= NULL
;
4263 entity_tick(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
, int queued
)
4266 * Update run-time statistics of the 'current'.
4268 update_curr(cfs_rq
);
4271 * Ensure that runnable average is periodically updated.
4273 update_load_avg(curr
, UPDATE_TG
);
4274 update_cfs_shares(curr
);
4276 #ifdef CONFIG_SCHED_HRTICK
4278 * queued ticks are scheduled to match the slice, so don't bother
4279 * validating it and just reschedule.
4282 resched_curr(rq_of(cfs_rq
));
4286 * don't let the period tick interfere with the hrtick preemption
4288 if (!sched_feat(DOUBLE_TICK
) &&
4289 hrtimer_active(&rq_of(cfs_rq
)->hrtick_timer
))
4293 if (cfs_rq
->nr_running
> 1)
4294 check_preempt_tick(cfs_rq
, curr
);
4298 /**************************************************
4299 * CFS bandwidth control machinery
4302 #ifdef CONFIG_CFS_BANDWIDTH
4304 #ifdef HAVE_JUMP_LABEL
4305 static struct static_key __cfs_bandwidth_used
;
4307 static inline bool cfs_bandwidth_used(void)
4309 return static_key_false(&__cfs_bandwidth_used
);
4312 void cfs_bandwidth_usage_inc(void)
4314 static_key_slow_inc(&__cfs_bandwidth_used
);
4317 void cfs_bandwidth_usage_dec(void)
4319 static_key_slow_dec(&__cfs_bandwidth_used
);
4321 #else /* HAVE_JUMP_LABEL */
4322 static bool cfs_bandwidth_used(void)
4327 void cfs_bandwidth_usage_inc(void) {}
4328 void cfs_bandwidth_usage_dec(void) {}
4329 #endif /* HAVE_JUMP_LABEL */
4332 * default period for cfs group bandwidth.
4333 * default: 0.1s, units: nanoseconds
4335 static inline u64
default_cfs_period(void)
4337 return 100000000ULL;
4340 static inline u64
sched_cfs_bandwidth_slice(void)
4342 return (u64
)sysctl_sched_cfs_bandwidth_slice
* NSEC_PER_USEC
;
4346 * Replenish runtime according to assigned quota and update expiration time.
4347 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
4348 * additional synchronization around rq->lock.
4350 * requires cfs_b->lock
4352 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth
*cfs_b
)
4356 if (cfs_b
->quota
== RUNTIME_INF
)
4359 now
= sched_clock_cpu(smp_processor_id());
4360 cfs_b
->runtime
= cfs_b
->quota
;
4361 cfs_b
->runtime_expires
= now
+ ktime_to_ns(cfs_b
->period
);
4364 static inline struct cfs_bandwidth
*tg_cfs_bandwidth(struct task_group
*tg
)
4366 return &tg
->cfs_bandwidth
;
4369 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
4370 static inline u64
cfs_rq_clock_task(struct cfs_rq
*cfs_rq
)
4372 if (unlikely(cfs_rq
->throttle_count
))
4373 return cfs_rq
->throttled_clock_task
- cfs_rq
->throttled_clock_task_time
;
4375 return rq_clock_task(rq_of(cfs_rq
)) - cfs_rq
->throttled_clock_task_time
;
4378 /* returns 0 on failure to allocate runtime */
4379 static int assign_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4381 struct task_group
*tg
= cfs_rq
->tg
;
4382 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(tg
);
4383 u64 amount
= 0, min_amount
, expires
;
4385 /* note: this is a positive sum as runtime_remaining <= 0 */
4386 min_amount
= sched_cfs_bandwidth_slice() - cfs_rq
->runtime_remaining
;
4388 raw_spin_lock(&cfs_b
->lock
);
4389 if (cfs_b
->quota
== RUNTIME_INF
)
4390 amount
= min_amount
;
4392 start_cfs_bandwidth(cfs_b
);
4394 if (cfs_b
->runtime
> 0) {
4395 amount
= min(cfs_b
->runtime
, min_amount
);
4396 cfs_b
->runtime
-= amount
;
4400 expires
= cfs_b
->runtime_expires
;
4401 raw_spin_unlock(&cfs_b
->lock
);
4403 cfs_rq
->runtime_remaining
+= amount
;
4405 * we may have advanced our local expiration to account for allowed
4406 * spread between our sched_clock and the one on which runtime was
4409 if ((s64
)(expires
- cfs_rq
->runtime_expires
) > 0)
4410 cfs_rq
->runtime_expires
= expires
;
4412 return cfs_rq
->runtime_remaining
> 0;
4416 * Note: This depends on the synchronization provided by sched_clock and the
4417 * fact that rq->clock snapshots this value.
4419 static void expire_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4421 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4423 /* if the deadline is ahead of our clock, nothing to do */
4424 if (likely((s64
)(rq_clock(rq_of(cfs_rq
)) - cfs_rq
->runtime_expires
) < 0))
4427 if (cfs_rq
->runtime_remaining
< 0)
4431 * If the local deadline has passed we have to consider the
4432 * possibility that our sched_clock is 'fast' and the global deadline
4433 * has not truly expired.
4435 * Fortunately we can check determine whether this the case by checking
4436 * whether the global deadline has advanced. It is valid to compare
4437 * cfs_b->runtime_expires without any locks since we only care about
4438 * exact equality, so a partial write will still work.
4441 if (cfs_rq
->runtime_expires
!= cfs_b
->runtime_expires
) {
4442 /* extend local deadline, drift is bounded above by 2 ticks */
4443 cfs_rq
->runtime_expires
+= TICK_NSEC
;
4445 /* global deadline is ahead, expiration has passed */
4446 cfs_rq
->runtime_remaining
= 0;
4450 static void __account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
)
4452 /* dock delta_exec before expiring quota (as it could span periods) */
4453 cfs_rq
->runtime_remaining
-= delta_exec
;
4454 expire_cfs_rq_runtime(cfs_rq
);
4456 if (likely(cfs_rq
->runtime_remaining
> 0))
4460 * if we're unable to extend our runtime we resched so that the active
4461 * hierarchy can be throttled
4463 if (!assign_cfs_rq_runtime(cfs_rq
) && likely(cfs_rq
->curr
))
4464 resched_curr(rq_of(cfs_rq
));
4467 static __always_inline
4468 void account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
)
4470 if (!cfs_bandwidth_used() || !cfs_rq
->runtime_enabled
)
4473 __account_cfs_rq_runtime(cfs_rq
, delta_exec
);
4476 static inline int cfs_rq_throttled(struct cfs_rq
*cfs_rq
)
4478 return cfs_bandwidth_used() && cfs_rq
->throttled
;
4481 /* check whether cfs_rq, or any parent, is throttled */
4482 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
)
4484 return cfs_bandwidth_used() && cfs_rq
->throttle_count
;
4488 * Ensure that neither of the group entities corresponding to src_cpu or
4489 * dest_cpu are members of a throttled hierarchy when performing group
4490 * load-balance operations.
4492 static inline int throttled_lb_pair(struct task_group
*tg
,
4493 int src_cpu
, int dest_cpu
)
4495 struct cfs_rq
*src_cfs_rq
, *dest_cfs_rq
;
4497 src_cfs_rq
= tg
->cfs_rq
[src_cpu
];
4498 dest_cfs_rq
= tg
->cfs_rq
[dest_cpu
];
4500 return throttled_hierarchy(src_cfs_rq
) ||
4501 throttled_hierarchy(dest_cfs_rq
);
4504 /* updated child weight may affect parent so we have to do this bottom up */
4505 static int tg_unthrottle_up(struct task_group
*tg
, void *data
)
4507 struct rq
*rq
= data
;
4508 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4510 cfs_rq
->throttle_count
--;
4511 if (!cfs_rq
->throttle_count
) {
4512 /* adjust cfs_rq_clock_task() */
4513 cfs_rq
->throttled_clock_task_time
+= rq_clock_task(rq
) -
4514 cfs_rq
->throttled_clock_task
;
4520 static int tg_throttle_down(struct task_group
*tg
, void *data
)
4522 struct rq
*rq
= data
;
4523 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4525 /* group is entering throttled state, stop time */
4526 if (!cfs_rq
->throttle_count
)
4527 cfs_rq
->throttled_clock_task
= rq_clock_task(rq
);
4528 cfs_rq
->throttle_count
++;
4533 static void throttle_cfs_rq(struct cfs_rq
*cfs_rq
)
4535 struct rq
*rq
= rq_of(cfs_rq
);
4536 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4537 struct sched_entity
*se
;
4538 long task_delta
, dequeue
= 1;
4541 se
= cfs_rq
->tg
->se
[cpu_of(rq_of(cfs_rq
))];
4543 /* freeze hierarchy runnable averages while throttled */
4545 walk_tg_tree_from(cfs_rq
->tg
, tg_throttle_down
, tg_nop
, (void *)rq
);
4548 task_delta
= cfs_rq
->h_nr_running
;
4549 for_each_sched_entity(se
) {
4550 struct cfs_rq
*qcfs_rq
= cfs_rq_of(se
);
4551 /* throttled entity or throttle-on-deactivate */
4556 dequeue_entity(qcfs_rq
, se
, DEQUEUE_SLEEP
);
4557 qcfs_rq
->h_nr_running
-= task_delta
;
4559 if (qcfs_rq
->load
.weight
)
4564 sub_nr_running(rq
, task_delta
);
4566 cfs_rq
->throttled
= 1;
4567 cfs_rq
->throttled_clock
= rq_clock(rq
);
4568 raw_spin_lock(&cfs_b
->lock
);
4569 empty
= list_empty(&cfs_b
->throttled_cfs_rq
);
4572 * Add to the _head_ of the list, so that an already-started
4573 * distribute_cfs_runtime will not see us. If disribute_cfs_runtime is
4574 * not running add to the tail so that later runqueues don't get starved.
4576 if (cfs_b
->distribute_running
)
4577 list_add_rcu(&cfs_rq
->throttled_list
, &cfs_b
->throttled_cfs_rq
);
4579 list_add_tail_rcu(&cfs_rq
->throttled_list
, &cfs_b
->throttled_cfs_rq
);
4582 * If we're the first throttled task, make sure the bandwidth
4586 start_cfs_bandwidth(cfs_b
);
4588 raw_spin_unlock(&cfs_b
->lock
);
4591 void unthrottle_cfs_rq(struct cfs_rq
*cfs_rq
)
4593 struct rq
*rq
= rq_of(cfs_rq
);
4594 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4595 struct sched_entity
*se
;
4599 se
= cfs_rq
->tg
->se
[cpu_of(rq
)];
4601 cfs_rq
->throttled
= 0;
4603 update_rq_clock(rq
);
4605 raw_spin_lock(&cfs_b
->lock
);
4606 cfs_b
->throttled_time
+= rq_clock(rq
) - cfs_rq
->throttled_clock
;
4607 list_del_rcu(&cfs_rq
->throttled_list
);
4608 raw_spin_unlock(&cfs_b
->lock
);
4610 /* update hierarchical throttle state */
4611 walk_tg_tree_from(cfs_rq
->tg
, tg_nop
, tg_unthrottle_up
, (void *)rq
);
4613 if (!cfs_rq
->load
.weight
)
4616 task_delta
= cfs_rq
->h_nr_running
;
4617 for_each_sched_entity(se
) {
4621 cfs_rq
= cfs_rq_of(se
);
4623 enqueue_entity(cfs_rq
, se
, ENQUEUE_WAKEUP
);
4624 cfs_rq
->h_nr_running
+= task_delta
;
4626 if (cfs_rq_throttled(cfs_rq
))
4631 add_nr_running(rq
, task_delta
);
4633 /* determine whether we need to wake up potentially idle cpu */
4634 if (rq
->curr
== rq
->idle
&& rq
->cfs
.nr_running
)
4638 static u64
distribute_cfs_runtime(struct cfs_bandwidth
*cfs_b
,
4639 u64 remaining
, u64 expires
)
4641 struct cfs_rq
*cfs_rq
;
4643 u64 starting_runtime
= remaining
;
4646 list_for_each_entry_rcu(cfs_rq
, &cfs_b
->throttled_cfs_rq
,
4648 struct rq
*rq
= rq_of(cfs_rq
);
4652 if (!cfs_rq_throttled(cfs_rq
))
4655 runtime
= -cfs_rq
->runtime_remaining
+ 1;
4656 if (runtime
> remaining
)
4657 runtime
= remaining
;
4658 remaining
-= runtime
;
4660 cfs_rq
->runtime_remaining
+= runtime
;
4661 cfs_rq
->runtime_expires
= expires
;
4663 /* we check whether we're throttled above */
4664 if (cfs_rq
->runtime_remaining
> 0)
4665 unthrottle_cfs_rq(cfs_rq
);
4675 return starting_runtime
- remaining
;
4679 * Responsible for refilling a task_group's bandwidth and unthrottling its
4680 * cfs_rqs as appropriate. If there has been no activity within the last
4681 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4682 * used to track this state.
4684 static int do_sched_cfs_period_timer(struct cfs_bandwidth
*cfs_b
, int overrun
)
4686 u64 runtime
, runtime_expires
;
4689 /* no need to continue the timer with no bandwidth constraint */
4690 if (cfs_b
->quota
== RUNTIME_INF
)
4691 goto out_deactivate
;
4693 throttled
= !list_empty(&cfs_b
->throttled_cfs_rq
);
4694 cfs_b
->nr_periods
+= overrun
;
4697 * idle depends on !throttled (for the case of a large deficit), and if
4698 * we're going inactive then everything else can be deferred
4700 if (cfs_b
->idle
&& !throttled
)
4701 goto out_deactivate
;
4703 __refill_cfs_bandwidth_runtime(cfs_b
);
4706 /* mark as potentially idle for the upcoming period */
4711 /* account preceding periods in which throttling occurred */
4712 cfs_b
->nr_throttled
+= overrun
;
4714 runtime_expires
= cfs_b
->runtime_expires
;
4717 * This check is repeated as we are holding onto the new bandwidth while
4718 * we unthrottle. This can potentially race with an unthrottled group
4719 * trying to acquire new bandwidth from the global pool. This can result
4720 * in us over-using our runtime if it is all used during this loop, but
4721 * only by limited amounts in that extreme case.
4723 while (throttled
&& cfs_b
->runtime
> 0 && !cfs_b
->distribute_running
) {
4724 runtime
= cfs_b
->runtime
;
4725 cfs_b
->distribute_running
= 1;
4726 raw_spin_unlock(&cfs_b
->lock
);
4727 /* we can't nest cfs_b->lock while distributing bandwidth */
4728 runtime
= distribute_cfs_runtime(cfs_b
, runtime
,
4730 raw_spin_lock(&cfs_b
->lock
);
4732 cfs_b
->distribute_running
= 0;
4733 throttled
= !list_empty(&cfs_b
->throttled_cfs_rq
);
4735 cfs_b
->runtime
-= min(runtime
, cfs_b
->runtime
);
4739 * While we are ensured activity in the period following an
4740 * unthrottle, this also covers the case in which the new bandwidth is
4741 * insufficient to cover the existing bandwidth deficit. (Forcing the
4742 * timer to remain active while there are any throttled entities.)
4752 /* a cfs_rq won't donate quota below this amount */
4753 static const u64 min_cfs_rq_runtime
= 1 * NSEC_PER_MSEC
;
4754 /* minimum remaining period time to redistribute slack quota */
4755 static const u64 min_bandwidth_expiration
= 2 * NSEC_PER_MSEC
;
4756 /* how long we wait to gather additional slack before distributing */
4757 static const u64 cfs_bandwidth_slack_period
= 5 * NSEC_PER_MSEC
;
4760 * Are we near the end of the current quota period?
4762 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4763 * hrtimer base being cleared by hrtimer_start. In the case of
4764 * migrate_hrtimers, base is never cleared, so we are fine.
4766 static int runtime_refresh_within(struct cfs_bandwidth
*cfs_b
, u64 min_expire
)
4768 struct hrtimer
*refresh_timer
= &cfs_b
->period_timer
;
4771 /* if the call-back is running a quota refresh is already occurring */
4772 if (hrtimer_callback_running(refresh_timer
))
4775 /* is a quota refresh about to occur? */
4776 remaining
= ktime_to_ns(hrtimer_expires_remaining(refresh_timer
));
4777 if (remaining
< min_expire
)
4783 static void start_cfs_slack_bandwidth(struct cfs_bandwidth
*cfs_b
)
4785 u64 min_left
= cfs_bandwidth_slack_period
+ min_bandwidth_expiration
;
4787 /* if there's a quota refresh soon don't bother with slack */
4788 if (runtime_refresh_within(cfs_b
, min_left
))
4791 hrtimer_start(&cfs_b
->slack_timer
,
4792 ns_to_ktime(cfs_bandwidth_slack_period
),
4796 /* we know any runtime found here is valid as update_curr() precedes return */
4797 static void __return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4799 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4800 s64 slack_runtime
= cfs_rq
->runtime_remaining
- min_cfs_rq_runtime
;
4802 if (slack_runtime
<= 0)
4805 raw_spin_lock(&cfs_b
->lock
);
4806 if (cfs_b
->quota
!= RUNTIME_INF
&&
4807 cfs_rq
->runtime_expires
== cfs_b
->runtime_expires
) {
4808 cfs_b
->runtime
+= slack_runtime
;
4810 /* we are under rq->lock, defer unthrottling using a timer */
4811 if (cfs_b
->runtime
> sched_cfs_bandwidth_slice() &&
4812 !list_empty(&cfs_b
->throttled_cfs_rq
))
4813 start_cfs_slack_bandwidth(cfs_b
);
4815 raw_spin_unlock(&cfs_b
->lock
);
4817 /* even if it's not valid for return we don't want to try again */
4818 cfs_rq
->runtime_remaining
-= slack_runtime
;
4821 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4823 if (!cfs_bandwidth_used())
4826 if (!cfs_rq
->runtime_enabled
|| cfs_rq
->nr_running
)
4829 __return_cfs_rq_runtime(cfs_rq
);
4833 * This is done with a timer (instead of inline with bandwidth return) since
4834 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4836 static void do_sched_cfs_slack_timer(struct cfs_bandwidth
*cfs_b
)
4838 u64 runtime
= 0, slice
= sched_cfs_bandwidth_slice();
4841 /* confirm we're still not at a refresh boundary */
4842 raw_spin_lock(&cfs_b
->lock
);
4843 if (cfs_b
->distribute_running
) {
4844 raw_spin_unlock(&cfs_b
->lock
);
4848 if (runtime_refresh_within(cfs_b
, min_bandwidth_expiration
)) {
4849 raw_spin_unlock(&cfs_b
->lock
);
4853 if (cfs_b
->quota
!= RUNTIME_INF
&& cfs_b
->runtime
> slice
)
4854 runtime
= cfs_b
->runtime
;
4856 expires
= cfs_b
->runtime_expires
;
4858 cfs_b
->distribute_running
= 1;
4860 raw_spin_unlock(&cfs_b
->lock
);
4865 runtime
= distribute_cfs_runtime(cfs_b
, runtime
, expires
);
4867 raw_spin_lock(&cfs_b
->lock
);
4868 if (expires
== cfs_b
->runtime_expires
)
4869 cfs_b
->runtime
-= min(runtime
, cfs_b
->runtime
);
4870 cfs_b
->distribute_running
= 0;
4871 raw_spin_unlock(&cfs_b
->lock
);
4875 * When a group wakes up we want to make sure that its quota is not already
4876 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4877 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4879 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
)
4881 if (!cfs_bandwidth_used())
4884 /* an active group must be handled by the update_curr()->put() path */
4885 if (!cfs_rq
->runtime_enabled
|| cfs_rq
->curr
)
4888 /* ensure the group is not already throttled */
4889 if (cfs_rq_throttled(cfs_rq
))
4892 /* update runtime allocation */
4893 account_cfs_rq_runtime(cfs_rq
, 0);
4894 if (cfs_rq
->runtime_remaining
<= 0)
4895 throttle_cfs_rq(cfs_rq
);
4898 static void sync_throttle(struct task_group
*tg
, int cpu
)
4900 struct cfs_rq
*pcfs_rq
, *cfs_rq
;
4902 if (!cfs_bandwidth_used())
4908 cfs_rq
= tg
->cfs_rq
[cpu
];
4909 pcfs_rq
= tg
->parent
->cfs_rq
[cpu
];
4911 cfs_rq
->throttle_count
= pcfs_rq
->throttle_count
;
4912 cfs_rq
->throttled_clock_task
= rq_clock_task(cpu_rq(cpu
));
4915 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4916 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4918 if (!cfs_bandwidth_used())
4921 if (likely(!cfs_rq
->runtime_enabled
|| cfs_rq
->runtime_remaining
> 0))
4925 * it's possible for a throttled entity to be forced into a running
4926 * state (e.g. set_curr_task), in this case we're finished.
4928 if (cfs_rq_throttled(cfs_rq
))
4931 throttle_cfs_rq(cfs_rq
);
4935 static enum hrtimer_restart
sched_cfs_slack_timer(struct hrtimer
*timer
)
4937 struct cfs_bandwidth
*cfs_b
=
4938 container_of(timer
, struct cfs_bandwidth
, slack_timer
);
4940 do_sched_cfs_slack_timer(cfs_b
);
4942 return HRTIMER_NORESTART
;
4945 static enum hrtimer_restart
sched_cfs_period_timer(struct hrtimer
*timer
)
4947 struct cfs_bandwidth
*cfs_b
=
4948 container_of(timer
, struct cfs_bandwidth
, period_timer
);
4952 raw_spin_lock(&cfs_b
->lock
);
4954 overrun
= hrtimer_forward_now(timer
, cfs_b
->period
);
4958 idle
= do_sched_cfs_period_timer(cfs_b
, overrun
);
4961 cfs_b
->period_active
= 0;
4962 raw_spin_unlock(&cfs_b
->lock
);
4964 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
4967 void init_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
4969 raw_spin_lock_init(&cfs_b
->lock
);
4971 cfs_b
->quota
= RUNTIME_INF
;
4972 cfs_b
->period
= ns_to_ktime(default_cfs_period());
4974 INIT_LIST_HEAD(&cfs_b
->throttled_cfs_rq
);
4975 hrtimer_init(&cfs_b
->period_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_ABS_PINNED
);
4976 cfs_b
->period_timer
.function
= sched_cfs_period_timer
;
4977 hrtimer_init(&cfs_b
->slack_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
4978 cfs_b
->slack_timer
.function
= sched_cfs_slack_timer
;
4979 cfs_b
->distribute_running
= 0;
4982 static void init_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4984 cfs_rq
->runtime_enabled
= 0;
4985 INIT_LIST_HEAD(&cfs_rq
->throttled_list
);
4988 void start_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
4990 lockdep_assert_held(&cfs_b
->lock
);
4992 if (!cfs_b
->period_active
) {
4993 cfs_b
->period_active
= 1;
4994 hrtimer_forward_now(&cfs_b
->period_timer
, cfs_b
->period
);
4995 hrtimer_start_expires(&cfs_b
->period_timer
, HRTIMER_MODE_ABS_PINNED
);
4999 static void destroy_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
5001 /* init_cfs_bandwidth() was not called */
5002 if (!cfs_b
->throttled_cfs_rq
.next
)
5005 hrtimer_cancel(&cfs_b
->period_timer
);
5006 hrtimer_cancel(&cfs_b
->slack_timer
);
5010 * Both these cpu hotplug callbacks race against unregister_fair_sched_group()
5012 * The race is harmless, since modifying bandwidth settings of unhooked group
5013 * bits doesn't do much.
5016 /* cpu online calback */
5017 static void __maybe_unused
update_runtime_enabled(struct rq
*rq
)
5019 struct task_group
*tg
;
5021 lockdep_assert_held(&rq
->lock
);
5024 list_for_each_entry_rcu(tg
, &task_groups
, list
) {
5025 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
5026 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
5028 raw_spin_lock(&cfs_b
->lock
);
5029 cfs_rq
->runtime_enabled
= cfs_b
->quota
!= RUNTIME_INF
;
5030 raw_spin_unlock(&cfs_b
->lock
);
5035 /* cpu offline callback */
5036 static void __maybe_unused
unthrottle_offline_cfs_rqs(struct rq
*rq
)
5038 struct task_group
*tg
;
5040 lockdep_assert_held(&rq
->lock
);
5043 list_for_each_entry_rcu(tg
, &task_groups
, list
) {
5044 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
5046 if (!cfs_rq
->runtime_enabled
)
5050 * clock_task is not advancing so we just need to make sure
5051 * there's some valid quota amount
5053 cfs_rq
->runtime_remaining
= 1;
5055 * Offline rq is schedulable till cpu is completely disabled
5056 * in take_cpu_down(), so we prevent new cfs throttling here.
5058 cfs_rq
->runtime_enabled
= 0;
5060 if (cfs_rq_throttled(cfs_rq
))
5061 unthrottle_cfs_rq(cfs_rq
);
5066 #else /* CONFIG_CFS_BANDWIDTH */
5067 static inline u64
cfs_rq_clock_task(struct cfs_rq
*cfs_rq
)
5069 return rq_clock_task(rq_of(cfs_rq
));
5072 static void account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
) {}
5073 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) { return false; }
5074 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
) {}
5075 static inline void sync_throttle(struct task_group
*tg
, int cpu
) {}
5076 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) {}
5078 static inline int cfs_rq_throttled(struct cfs_rq
*cfs_rq
)
5083 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
)
5088 static inline int throttled_lb_pair(struct task_group
*tg
,
5089 int src_cpu
, int dest_cpu
)
5094 void init_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
) {}
5096 #ifdef CONFIG_FAIR_GROUP_SCHED
5097 static void init_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) {}
5100 static inline struct cfs_bandwidth
*tg_cfs_bandwidth(struct task_group
*tg
)
5104 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
) {}
5105 static inline void update_runtime_enabled(struct rq
*rq
) {}
5106 static inline void unthrottle_offline_cfs_rqs(struct rq
*rq
) {}
5108 #endif /* CONFIG_CFS_BANDWIDTH */
5110 /**************************************************
5111 * CFS operations on tasks:
5114 #ifdef CONFIG_SCHED_HRTICK
5115 static void hrtick_start_fair(struct rq
*rq
, struct task_struct
*p
)
5117 struct sched_entity
*se
= &p
->se
;
5118 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
5120 SCHED_WARN_ON(task_rq(p
) != rq
);
5122 if (rq
->cfs
.h_nr_running
> 1) {
5123 u64 slice
= sched_slice(cfs_rq
, se
);
5124 u64 ran
= se
->sum_exec_runtime
- se
->prev_sum_exec_runtime
;
5125 s64 delta
= slice
- ran
;
5132 hrtick_start(rq
, delta
);
5137 * called from enqueue/dequeue and updates the hrtick when the
5138 * current task is from our class and nr_running is low enough
5141 static void hrtick_update(struct rq
*rq
)
5143 struct task_struct
*curr
= rq
->curr
;
5145 if (!hrtick_enabled(rq
) || curr
->sched_class
!= &fair_sched_class
)
5148 if (cfs_rq_of(&curr
->se
)->nr_running
< sched_nr_latency
)
5149 hrtick_start_fair(rq
, curr
);
5151 #else /* !CONFIG_SCHED_HRTICK */
5153 hrtick_start_fair(struct rq
*rq
, struct task_struct
*p
)
5157 static inline void hrtick_update(struct rq
*rq
)
5163 static bool cpu_overutilized(int cpu
);
5165 static bool sd_overutilized(struct sched_domain
*sd
)
5167 return sd
->shared
->overutilized
;
5170 static void set_sd_overutilized(struct sched_domain
*sd
)
5172 trace_sched_overutilized(sd
, sd
->shared
->overutilized
, true);
5173 sd
->shared
->overutilized
= true;
5176 static void clear_sd_overutilized(struct sched_domain
*sd
)
5178 trace_sched_overutilized(sd
, sd
->shared
->overutilized
, false);
5179 sd
->shared
->overutilized
= false;
5182 static inline void update_overutilized_status(struct rq
*rq
)
5184 struct sched_domain
*sd
;
5187 sd
= rcu_dereference(rq
->sd
);
5188 if (sd
&& !sd_overutilized(sd
) &&
5189 cpu_overutilized(rq
->cpu
))
5190 set_sd_overutilized(sd
);
5194 unsigned long boosted_cpu_util(int cpu
, unsigned long other_util
);
5197 #define update_overutilized_status(rq) do {} while (0)
5198 #define boosted_cpu_util(cpu, other_util) cpu_util_freq(cpu)
5200 #endif /* CONFIG_SMP */
5203 * The enqueue_task method is called before nr_running is
5204 * increased. Here we update the fair scheduling stats and
5205 * then put the task into the rbtree:
5208 enqueue_task_fair(struct rq
*rq
, struct task_struct
*p
, int flags
)
5210 struct cfs_rq
*cfs_rq
;
5211 struct sched_entity
*se
= &p
->se
;
5212 int task_new
= !(flags
& ENQUEUE_WAKEUP
);
5215 * The code below (indirectly) updates schedutil which looks at
5216 * the cfs_rq utilization to select a frequency.
5217 * Let's add the task's estimated utilization to the cfs_rq's
5218 * estimated utilization, before we update schedutil.
5220 util_est_enqueue(&rq
->cfs
, p
);
5223 * The code below (indirectly) updates schedutil which looks at
5224 * the cfs_rq utilization to select a frequency.
5225 * Let's update schedtune here to ensure the boost value of the
5226 * current task is accounted for in the selection of the OPP.
5228 * We do it also in the case where we enqueue a throttled task;
5229 * we could argue that a throttled task should not boost a CPU,
5231 * a) properly implementing CPU boosting considering throttled
5232 * tasks will increase a lot the complexity of the solution
5233 * b) it's not easy to quantify the benefits introduced by
5234 * such a more complex solution.
5235 * Thus, for the time being we go for the simple solution and boost
5236 * also for throttled RQs.
5238 schedtune_enqueue_task(p
, cpu_of(rq
));
5241 * If in_iowait is set, the code below may not trigger any cpufreq
5242 * utilization updates, so do it here explicitly with the IOWAIT flag
5246 cpufreq_update_util(rq
, SCHED_CPUFREQ_IOWAIT
);
5248 for_each_sched_entity(se
) {
5251 cfs_rq
= cfs_rq_of(se
);
5252 enqueue_entity(cfs_rq
, se
, flags
);
5255 * end evaluation on encountering a throttled cfs_rq
5257 * note: in the case of encountering a throttled cfs_rq we will
5258 * post the final h_nr_running increment below.
5260 if (cfs_rq_throttled(cfs_rq
))
5262 cfs_rq
->h_nr_running
++;
5263 walt_inc_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5265 flags
= ENQUEUE_WAKEUP
;
5268 for_each_sched_entity(se
) {
5269 cfs_rq
= cfs_rq_of(se
);
5270 cfs_rq
->h_nr_running
++;
5271 walt_inc_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5273 if (cfs_rq_throttled(cfs_rq
))
5276 update_load_avg(se
, UPDATE_TG
);
5277 update_cfs_shares(se
);
5281 add_nr_running(rq
, 1);
5283 update_overutilized_status(rq
);
5284 walt_inc_cumulative_runnable_avg(rq
, p
);
5290 static void set_next_buddy(struct sched_entity
*se
);
5293 * The dequeue_task method is called before nr_running is
5294 * decreased. We remove the task from the rbtree and
5295 * update the fair scheduling stats:
5297 static void dequeue_task_fair(struct rq
*rq
, struct task_struct
*p
, int flags
)
5299 struct cfs_rq
*cfs_rq
;
5300 struct sched_entity
*se
= &p
->se
;
5301 int task_sleep
= flags
& DEQUEUE_SLEEP
;
5304 * The code below (indirectly) updates schedutil which looks at
5305 * the cfs_rq utilization to select a frequency.
5306 * Let's update schedtune here to ensure the boost value of the
5307 * current task is not more accounted for in the selection of the OPP.
5309 schedtune_dequeue_task(p
, cpu_of(rq
));
5311 for_each_sched_entity(se
) {
5312 cfs_rq
= cfs_rq_of(se
);
5313 dequeue_entity(cfs_rq
, se
, flags
);
5316 * end evaluation on encountering a throttled cfs_rq
5318 * note: in the case of encountering a throttled cfs_rq we will
5319 * post the final h_nr_running decrement below.
5321 if (cfs_rq_throttled(cfs_rq
))
5323 cfs_rq
->h_nr_running
--;
5324 walt_dec_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5326 /* Don't dequeue parent if it has other entities besides us */
5327 if (cfs_rq
->load
.weight
) {
5328 /* Avoid re-evaluating load for this entity: */
5329 se
= parent_entity(se
);
5331 * Bias pick_next to pick a task from this cfs_rq, as
5332 * p is sleeping when it is within its sched_slice.
5334 if (task_sleep
&& se
&& !throttled_hierarchy(cfs_rq
))
5338 flags
|= DEQUEUE_SLEEP
;
5341 for_each_sched_entity(se
) {
5342 cfs_rq
= cfs_rq_of(se
);
5343 cfs_rq
->h_nr_running
--;
5344 walt_dec_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5346 if (cfs_rq_throttled(cfs_rq
))
5349 update_load_avg(se
, UPDATE_TG
);
5350 update_cfs_shares(se
);
5354 sub_nr_running(rq
, 1);
5355 walt_dec_cumulative_runnable_avg(rq
, p
);
5358 util_est_dequeue(&rq
->cfs
, p
, task_sleep
);
5364 /* Working cpumask for: load_balance, load_balance_newidle. */
5365 DEFINE_PER_CPU(cpumask_var_t
, load_balance_mask
);
5366 DEFINE_PER_CPU(cpumask_var_t
, select_idle_mask
);
5368 #ifdef CONFIG_NO_HZ_COMMON
5370 * per rq 'load' arrray crap; XXX kill this.
5374 * The exact cpuload calculated at every tick would be:
5376 * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
5378 * If a cpu misses updates for n ticks (as it was idle) and update gets
5379 * called on the n+1-th tick when cpu may be busy, then we have:
5381 * load_n = (1 - 1/2^i)^n * load_0
5382 * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
5384 * decay_load_missed() below does efficient calculation of
5386 * load' = (1 - 1/2^i)^n * load
5388 * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
5389 * This allows us to precompute the above in said factors, thereby allowing the
5390 * reduction of an arbitrary n in O(log_2 n) steps. (See also
5391 * fixed_power_int())
5393 * The calculation is approximated on a 128 point scale.
5395 #define DEGRADE_SHIFT 7
5397 static const u8 degrade_zero_ticks
[CPU_LOAD_IDX_MAX
] = {0, 8, 32, 64, 128};
5398 static const u8 degrade_factor
[CPU_LOAD_IDX_MAX
][DEGRADE_SHIFT
+ 1] = {
5399 { 0, 0, 0, 0, 0, 0, 0, 0 },
5400 { 64, 32, 8, 0, 0, 0, 0, 0 },
5401 { 96, 72, 40, 12, 1, 0, 0, 0 },
5402 { 112, 98, 75, 43, 15, 1, 0, 0 },
5403 { 120, 112, 98, 76, 45, 16, 2, 0 }
5407 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
5408 * would be when CPU is idle and so we just decay the old load without
5409 * adding any new load.
5411 static unsigned long
5412 decay_load_missed(unsigned long load
, unsigned long missed_updates
, int idx
)
5416 if (!missed_updates
)
5419 if (missed_updates
>= degrade_zero_ticks
[idx
])
5423 return load
>> missed_updates
;
5425 while (missed_updates
) {
5426 if (missed_updates
% 2)
5427 load
= (load
* degrade_factor
[idx
][j
]) >> DEGRADE_SHIFT
;
5429 missed_updates
>>= 1;
5434 #endif /* CONFIG_NO_HZ_COMMON */
5437 * __cpu_load_update - update the rq->cpu_load[] statistics
5438 * @this_rq: The rq to update statistics for
5439 * @this_load: The current load
5440 * @pending_updates: The number of missed updates
5442 * Update rq->cpu_load[] statistics. This function is usually called every
5443 * scheduler tick (TICK_NSEC).
5445 * This function computes a decaying average:
5447 * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
5449 * Because of NOHZ it might not get called on every tick which gives need for
5450 * the @pending_updates argument.
5452 * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
5453 * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
5454 * = A * (A * load[i]_n-2 + B) + B
5455 * = A * (A * (A * load[i]_n-3 + B) + B) + B
5456 * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
5457 * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
5458 * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
5459 * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
5461 * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
5462 * any change in load would have resulted in the tick being turned back on.
5464 * For regular NOHZ, this reduces to:
5466 * load[i]_n = (1 - 1/2^i)^n * load[i]_0
5468 * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
5471 static void cpu_load_update(struct rq
*this_rq
, unsigned long this_load
,
5472 unsigned long pending_updates
)
5474 unsigned long __maybe_unused tickless_load
= this_rq
->cpu_load
[0];
5477 this_rq
->nr_load_updates
++;
5479 /* Update our load: */
5480 this_rq
->cpu_load
[0] = this_load
; /* Fasttrack for idx 0 */
5481 for (i
= 1, scale
= 2; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
5482 unsigned long old_load
, new_load
;
5484 /* scale is effectively 1 << i now, and >> i divides by scale */
5486 old_load
= this_rq
->cpu_load
[i
];
5487 #ifdef CONFIG_NO_HZ_COMMON
5488 old_load
= decay_load_missed(old_load
, pending_updates
- 1, i
);
5489 if (tickless_load
) {
5490 old_load
-= decay_load_missed(tickless_load
, pending_updates
- 1, i
);
5492 * old_load can never be a negative value because a
5493 * decayed tickless_load cannot be greater than the
5494 * original tickless_load.
5496 old_load
+= tickless_load
;
5499 new_load
= this_load
;
5501 * Round up the averaging division if load is increasing. This
5502 * prevents us from getting stuck on 9 if the load is 10, for
5505 if (new_load
> old_load
)
5506 new_load
+= scale
- 1;
5508 this_rq
->cpu_load
[i
] = (old_load
* (scale
- 1) + new_load
) >> i
;
5511 sched_avg_update(this_rq
);
5514 /* Used instead of source_load when we know the type == 0 */
5515 static unsigned long weighted_cpuload(struct rq
*rq
)
5517 return cfs_rq_runnable_load_avg(&rq
->cfs
);
5520 #ifdef CONFIG_NO_HZ_COMMON
5522 * There is no sane way to deal with nohz on smp when using jiffies because the
5523 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
5524 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
5526 * Therefore we need to avoid the delta approach from the regular tick when
5527 * possible since that would seriously skew the load calculation. This is why we
5528 * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
5529 * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
5530 * loop exit, nohz_idle_balance, nohz full exit...)
5532 * This means we might still be one tick off for nohz periods.
5535 static void cpu_load_update_nohz(struct rq
*this_rq
,
5536 unsigned long curr_jiffies
,
5539 unsigned long pending_updates
;
5541 pending_updates
= curr_jiffies
- this_rq
->last_load_update_tick
;
5542 if (pending_updates
) {
5543 this_rq
->last_load_update_tick
= curr_jiffies
;
5545 * In the regular NOHZ case, we were idle, this means load 0.
5546 * In the NOHZ_FULL case, we were non-idle, we should consider
5547 * its weighted load.
5549 cpu_load_update(this_rq
, load
, pending_updates
);
5554 * Called from nohz_idle_balance() to update the load ratings before doing the
5557 static void cpu_load_update_idle(struct rq
*this_rq
)
5560 * bail if there's load or we're actually up-to-date.
5562 if (weighted_cpuload(this_rq
))
5565 cpu_load_update_nohz(this_rq
, READ_ONCE(jiffies
), 0);
5569 * Record CPU load on nohz entry so we know the tickless load to account
5570 * on nohz exit. cpu_load[0] happens then to be updated more frequently
5571 * than other cpu_load[idx] but it should be fine as cpu_load readers
5572 * shouldn't rely into synchronized cpu_load[*] updates.
5574 void cpu_load_update_nohz_start(void)
5576 struct rq
*this_rq
= this_rq();
5579 * This is all lockless but should be fine. If weighted_cpuload changes
5580 * concurrently we'll exit nohz. And cpu_load write can race with
5581 * cpu_load_update_idle() but both updater would be writing the same.
5583 this_rq
->cpu_load
[0] = weighted_cpuload(this_rq
);
5587 * Account the tickless load in the end of a nohz frame.
5589 void cpu_load_update_nohz_stop(void)
5591 unsigned long curr_jiffies
= READ_ONCE(jiffies
);
5592 struct rq
*this_rq
= this_rq();
5596 if (curr_jiffies
== this_rq
->last_load_update_tick
)
5599 load
= weighted_cpuload(this_rq
);
5600 rq_lock(this_rq
, &rf
);
5601 update_rq_clock(this_rq
);
5602 cpu_load_update_nohz(this_rq
, curr_jiffies
, load
);
5603 rq_unlock(this_rq
, &rf
);
5605 #else /* !CONFIG_NO_HZ_COMMON */
5606 static inline void cpu_load_update_nohz(struct rq
*this_rq
,
5607 unsigned long curr_jiffies
,
5608 unsigned long load
) { }
5609 #endif /* CONFIG_NO_HZ_COMMON */
5611 static void cpu_load_update_periodic(struct rq
*this_rq
, unsigned long load
)
5613 #ifdef CONFIG_NO_HZ_COMMON
5614 /* See the mess around cpu_load_update_nohz(). */
5615 this_rq
->last_load_update_tick
= READ_ONCE(jiffies
);
5617 cpu_load_update(this_rq
, load
, 1);
5621 * Called from scheduler_tick()
5623 void cpu_load_update_active(struct rq
*this_rq
)
5625 unsigned long load
= weighted_cpuload(this_rq
);
5627 if (tick_nohz_tick_stopped())
5628 cpu_load_update_nohz(this_rq
, READ_ONCE(jiffies
), load
);
5630 cpu_load_update_periodic(this_rq
, load
);
5634 * Return a low guess at the load of a migration-source cpu weighted
5635 * according to the scheduling class and "nice" value.
5637 * We want to under-estimate the load of migration sources, to
5638 * balance conservatively.
5640 static unsigned long source_load(int cpu
, int type
)
5642 struct rq
*rq
= cpu_rq(cpu
);
5643 unsigned long total
= weighted_cpuload(rq
);
5645 if (type
== 0 || !sched_feat(LB_BIAS
))
5648 return min(rq
->cpu_load
[type
-1], total
);
5652 * Return a high guess at the load of a migration-target cpu weighted
5653 * according to the scheduling class and "nice" value.
5655 static unsigned long target_load(int cpu
, int type
)
5657 struct rq
*rq
= cpu_rq(cpu
);
5658 unsigned long total
= weighted_cpuload(rq
);
5660 if (type
== 0 || !sched_feat(LB_BIAS
))
5663 return max(rq
->cpu_load
[type
-1], total
);
5666 static unsigned long cpu_avg_load_per_task(int cpu
)
5668 struct rq
*rq
= cpu_rq(cpu
);
5669 unsigned long nr_running
= READ_ONCE(rq
->cfs
.h_nr_running
);
5670 unsigned long load_avg
= weighted_cpuload(rq
);
5673 return load_avg
/ nr_running
;
5678 static void record_wakee(struct task_struct
*p
)
5681 * Only decay a single time; tasks that have less then 1 wakeup per
5682 * jiffy will not have built up many flips.
5684 if (time_after(jiffies
, current
->wakee_flip_decay_ts
+ HZ
)) {
5685 current
->wakee_flips
>>= 1;
5686 current
->wakee_flip_decay_ts
= jiffies
;
5689 if (current
->last_wakee
!= p
) {
5690 current
->last_wakee
= p
;
5691 current
->wakee_flips
++;
5696 * Returns the current capacity of cpu after applying both
5697 * cpu and freq scaling.
5699 unsigned long capacity_curr_of(int cpu
)
5701 unsigned long max_cap
= cpu_rq(cpu
)->cpu_capacity_orig
;
5702 unsigned long scale_freq
= arch_scale_freq_capacity(NULL
, cpu
);
5704 return cap_scale(max_cap
, scale_freq
);
5707 static inline bool energy_aware(void)
5709 return sched_feat(ENERGY_AWARE
);
5713 * __cpu_norm_util() returns the cpu util relative to a specific capacity,
5714 * i.e. it's busy ratio, in the range [0..SCHED_CAPACITY_SCALE] which is useful
5715 * for energy calculations. Using the scale-invariant util returned by
5716 * cpu_util() and approximating scale-invariant util by:
5718 * util ~ (curr_freq/max_freq)*1024 * capacity_orig/1024 * running_time/time
5720 * the normalized util can be found using the specific capacity.
5722 * capacity = capacity_orig * curr_freq/max_freq
5724 * norm_util = running_time/time ~ util/capacity
5726 static unsigned long __cpu_norm_util(unsigned long util
, unsigned long capacity
)
5728 if (util
>= capacity
)
5729 return SCHED_CAPACITY_SCALE
;
5731 return (util
<< SCHED_CAPACITY_SHIFT
)/capacity
;
5737 * These are labels to reference CPU candidates for an energy_diff.
5738 * Currently we support only two possible candidates: the task's previous CPU
5739 * and another candiate CPU.
5740 * More advanced/aggressive EAS selection policies can consider more
5743 #define EAS_CPU_PRV 0
5744 #define EAS_CPU_NXT 1
5745 #define EAS_CPU_BKP 2
5748 * energy_diff - supports the computation of the estimated energy impact in
5749 * moving a "task"'s "util_delta" between different CPU candidates.
5752 * NOTE: When using or examining WALT task signals, all wakeup
5753 * latency is included as busy time for task util.
5755 * This is relevant here because:
5756 * When debugging is enabled, it can take as much as 1ms to
5757 * write the output to the trace buffer for each eenv
5758 * scenario. For periodic tasks where the sleep time is of
5759 * a similar order, the WALT task util can be inflated.
5761 * Further, and even without debugging enabled,
5762 * task wakeup latency changes depending upon the EAS
5763 * wakeup algorithm selected - FIND_BEST_TARGET only does
5764 * energy calculations for up to 2 candidate CPUs. When
5765 * NO_FIND_BEST_TARGET is configured, we can potentially
5766 * do an energy calculation across all CPUS in the system.
5768 * The impact to WALT task util on a Juno board
5769 * running a periodic task which only sleeps for 200usec
5770 * between 1ms activations has been measured.
5771 * (i.e. the wakeup latency induced by energy calculation
5772 * and debug output is double the desired sleep time and
5773 * almost equivalent to the runtime which is more-or-less
5774 * the worst case possible for this test)
5776 * In this scenario, a task which has a PELT util of around
5777 * 220 is inflated under WALT to have util around 400.
5779 * This is simply a property of the way WALT includes
5780 * wakeup latency in busy time while PELT does not.
5782 * Hence - be careful when enabling DEBUG_EENV_DECISIONS
5783 * expecially if WALT is the task signal.
5785 /*#define DEBUG_EENV_DECISIONS*/
5787 #ifdef DEBUG_EENV_DECISIONS
5788 /* max of 8 levels of sched groups traversed */
5789 #define EAS_EENV_DEBUG_LEVELS 16
5791 struct _eenv_debug
{
5793 unsigned long norm_util
;
5794 unsigned long cap_energy
;
5795 unsigned long idle_energy
;
5796 unsigned long this_energy
;
5797 unsigned long this_busy_energy
;
5798 unsigned long this_idle_energy
;
5799 cpumask_t group_cpumask
;
5800 unsigned long cpu_util
[1];
5805 /* CPU ID, must be in cpus_mask */
5809 * Index (into sched_group_energy::cap_states) of the OPP the
5810 * CPU needs to run at if the task is placed on it.
5811 * This includes the both active and blocked load, due to
5812 * other tasks on this CPU, as well as the task's own
5818 /* Estimated system energy */
5819 unsigned long energy
;
5821 /* Estimated energy variation wrt EAS_CPU_PRV */
5824 #ifdef DEBUG_EENV_DECISIONS
5825 struct _eenv_debug
*debug
;
5827 #endif /* DEBUG_EENV_DECISIONS */
5831 /* Utilization to move */
5832 struct task_struct
*p
;
5833 unsigned long util_delta
;
5834 unsigned long util_delta_boosted
;
5836 /* Mask of CPUs candidates to evaluate */
5837 cpumask_t cpus_mask
;
5839 /* CPU candidates to evaluate */
5840 struct eenv_cpu
*cpu
;
5843 #ifdef DEBUG_EENV_DECISIONS
5844 /* pointer to the memory block reserved
5845 * for debug on this CPU - there will be
5846 * sizeof(struct _eenv_debug) *
5847 * (EAS_CPU_CNT * EAS_EENV_DEBUG_LEVELS)
5848 * bytes allocated here.
5850 struct _eenv_debug
*debug
;
5853 * Index (into energy_env::cpu) of the morst energy efficient CPU for
5854 * the specified energy_env::task
5860 struct sched_group
*sg_top
;
5861 struct sched_group
*sg_cap
;
5862 struct sched_group
*sg
;
5866 * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
5867 * @cpu: the CPU to get the utilization of
5869 * The unit of the return value must be the one of capacity so we can compare
5870 * the utilization with the capacity of the CPU that is available for CFS task
5871 * (ie cpu_capacity).
5873 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
5874 * recent utilization of currently non-runnable tasks on a CPU. It represents
5875 * the amount of utilization of a CPU in the range [0..capacity_orig] where
5876 * capacity_orig is the cpu_capacity available at the highest frequency,
5877 * i.e. arch_scale_cpu_capacity().
5878 * The utilization of a CPU converges towards a sum equal to or less than the
5879 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
5880 * the running time on this CPU scaled by capacity_curr.
5882 * The estimated utilization of a CPU is defined to be the maximum between its
5883 * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
5884 * currently RUNNABLE on that CPU.
5885 * This allows to properly represent the expected utilization of a CPU which
5886 * has just got a big task running since a long sleep period. At the same time
5887 * however it preserves the benefits of the "blocked utilization" in
5888 * describing the potential for other tasks waking up on the same CPU.
5890 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
5891 * higher than capacity_orig because of unfortunate rounding in
5892 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
5893 * the average stabilizes with the new running time. We need to check that the
5894 * utilization stays within the range of [0..capacity_orig] and cap it if
5895 * necessary. Without utilization capping, a group could be seen as overloaded
5896 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
5897 * available capacity. We allow utilization to overshoot capacity_curr (but not
5898 * capacity_orig) as it useful for predicting the capacity required after task
5899 * migrations (scheduler-driven DVFS).
5901 * Return: the (estimated) utilization for the specified CPU
5903 static inline unsigned long cpu_util(int cpu
)
5905 struct cfs_rq
*cfs_rq
;
5908 #ifdef CONFIG_SCHED_WALT
5909 if (likely(!walt_disabled
&& sysctl_sched_use_walt_cpu_util
)) {
5910 u64 walt_cpu_util
= cpu_rq(cpu
)->cumulative_runnable_avg
;
5912 walt_cpu_util
<<= SCHED_CAPACITY_SHIFT
;
5913 do_div(walt_cpu_util
, walt_ravg_window
);
5915 return min_t(unsigned long, walt_cpu_util
,
5916 capacity_orig_of(cpu
));
5920 cfs_rq
= &cpu_rq(cpu
)->cfs
;
5921 util
= READ_ONCE(cfs_rq
->avg
.util_avg
);
5923 if (sched_feat(UTIL_EST
))
5924 util
= max(util
, READ_ONCE(cfs_rq
->avg
.util_est
.enqueued
));
5926 return min_t(unsigned long, util
, capacity_orig_of(cpu
));
5929 static inline unsigned long cpu_util_freq(int cpu
)
5931 #ifdef CONFIG_SCHED_WALT
5934 if (unlikely(walt_disabled
|| !sysctl_sched_use_walt_cpu_util
))
5935 return cpu_util(cpu
);
5937 walt_cpu_util
= cpu_rq(cpu
)->prev_runnable_sum
;
5938 walt_cpu_util
<<= SCHED_CAPACITY_SHIFT
;
5939 do_div(walt_cpu_util
, walt_ravg_window
);
5941 return min_t(unsigned long, walt_cpu_util
, capacity_orig_of(cpu
));
5943 return cpu_util(cpu
);
5948 * cpu_util_wake: Compute CPU utilization with any contributions from
5949 * the waking task p removed.
5951 static unsigned long cpu_util_wake(int cpu
, struct task_struct
*p
)
5953 struct cfs_rq
*cfs_rq
;
5956 #ifdef CONFIG_SCHED_WALT
5958 * WALT does not decay idle tasks in the same manner
5959 * as PELT, so it makes little sense to subtract task
5960 * utilization from cpu utilization. Instead just use
5961 * cpu_util for this case.
5963 if (likely(!walt_disabled
&& sysctl_sched_use_walt_cpu_util
))
5964 return cpu_util(cpu
);
5967 /* Task has no contribution or is new */
5968 if (cpu
!= task_cpu(p
) || !READ_ONCE(p
->se
.avg
.last_update_time
))
5969 return cpu_util(cpu
);
5971 cfs_rq
= &cpu_rq(cpu
)->cfs
;
5972 util
= READ_ONCE(cfs_rq
->avg
.util_avg
);
5974 /* Discount task's blocked util from CPU's util */
5975 util
-= min_t(unsigned int, util
, task_util(p
));
5980 * a) if *p is the only task sleeping on this CPU, then:
5981 * cpu_util (== task_util) > util_est (== 0)
5982 * and thus we return:
5983 * cpu_util_wake = (cpu_util - task_util) = 0
5985 * b) if other tasks are SLEEPING on this CPU, which is now exiting
5987 * cpu_util >= task_util
5988 * cpu_util > util_est (== 0)
5989 * and thus we discount *p's blocked utilization to return:
5990 * cpu_util_wake = (cpu_util - task_util) >= 0
5992 * c) if other tasks are RUNNABLE on that CPU and
5993 * util_est > cpu_util
5994 * then we use util_est since it returns a more restrictive
5995 * estimation of the spare capacity on that CPU, by just
5996 * considering the expected utilization of tasks already
5997 * runnable on that CPU.
5999 * Cases a) and b) are covered by the above code, while case c) is
6000 * covered by the following code when estimated utilization is
6003 if (sched_feat(UTIL_EST
))
6004 util
= max(util
, READ_ONCE(cfs_rq
->avg
.util_est
.enqueued
));
6007 * Utilization (estimated) can exceed the CPU capacity, thus let's
6008 * clamp to the maximum CPU capacity to ensure consistency with
6009 * the cpu_util call.
6011 return min_t(unsigned long, util
, capacity_orig_of(cpu
));
6014 static unsigned long group_max_util(struct energy_env
*eenv
, int cpu_idx
)
6016 unsigned long max_util
= 0;
6020 for_each_cpu(cpu
, sched_group_span(eenv
->sg_cap
)) {
6021 util
= cpu_util_wake(cpu
, eenv
->p
);
6024 * If we are looking at the target CPU specified by the eenv,
6025 * then we should add the (estimated) utilization of the task
6026 * assuming we will wake it up on that CPU.
6028 if (unlikely(cpu
== eenv
->cpu
[cpu_idx
].cpu_id
))
6029 util
+= eenv
->util_delta_boosted
;
6031 max_util
= max(max_util
, util
);
6038 * group_norm_util() returns the approximated group util relative to it's
6039 * current capacity (busy ratio) in the range [0..SCHED_CAPACITY_SCALE] for use
6040 * in energy calculations. Since task executions may or may not overlap in time
6041 * in the group the true normalized util is between max(cpu_norm_util(i)) and
6042 * sum(cpu_norm_util(i)) when iterating over all cpus in the group, i. The
6043 * latter is used as the estimate as it leads to a more pessimistic energy
6044 * estimate (more busy).
6047 long group_norm_util(struct energy_env
*eenv
, int cpu_idx
)
6049 unsigned long capacity
= eenv
->cpu
[cpu_idx
].cap
;
6050 unsigned long util
, util_sum
= 0;
6053 for_each_cpu(cpu
, sched_group_span(eenv
->sg
)) {
6054 util
= cpu_util_wake(cpu
, eenv
->p
);
6057 * If we are looking at the target CPU specified by the eenv,
6058 * then we should add the (estimated) utilization of the task
6059 * assuming we will wake it up on that CPU.
6061 if (unlikely(cpu
== eenv
->cpu
[cpu_idx
].cpu_id
))
6062 util
+= eenv
->util_delta
;
6064 util_sum
+= __cpu_norm_util(util
, capacity
);
6067 if (util_sum
> SCHED_CAPACITY_SCALE
)
6068 return SCHED_CAPACITY_SCALE
;
6072 static int find_new_capacity(struct energy_env
*eenv
, int cpu_idx
)
6074 const struct sched_group_energy
*sge
= eenv
->sg_cap
->sge
;
6075 unsigned long util
= group_max_util(eenv
, cpu_idx
);
6078 cap_idx
= sge
->nr_cap_states
- 1;
6080 for (idx
= 0; idx
< sge
->nr_cap_states
; idx
++) {
6081 if (sge
->cap_states
[idx
].cap
>= util
) {
6086 /* Keep track of SG's capacity */
6087 eenv
->cpu
[cpu_idx
].cap
= sge
->cap_states
[cap_idx
].cap
;
6088 eenv
->cpu
[cpu_idx
].cap_idx
= cap_idx
;
6093 static int group_idle_state(struct energy_env
*eenv
, int cpu_idx
)
6095 struct sched_group
*sg
= eenv
->sg
;
6096 int src_in_grp
, dst_in_grp
;
6097 int i
, state
= INT_MAX
;
6098 int max_idle_state_idx
;
6102 /* Find the shallowest idle state in the sched group. */
6103 for_each_cpu(i
, sched_group_span(sg
))
6104 state
= min(state
, idle_get_state_idx(cpu_rq(i
)));
6106 /* Take non-cpuidle idling into account (active idle/arch_cpu_idle()) */
6109 * Try to estimate if a deeper idle state is
6110 * achievable when we move the task.
6112 for_each_cpu(i
, sched_group_span(sg
))
6113 grp_util
+= cpu_util(i
);
6115 src_in_grp
= cpumask_test_cpu(eenv
->cpu
[EAS_CPU_PRV
].cpu_id
,
6116 sched_group_span(sg
));
6117 dst_in_grp
= cpumask_test_cpu(eenv
->cpu
[cpu_idx
].cpu_id
,
6118 sched_group_span(sg
));
6119 if (src_in_grp
== dst_in_grp
) {
6121 * both CPUs under consideration are in the same group or not in
6122 * either group, migration should leave idle state the same.
6127 * add or remove util as appropriate to indicate what group util
6128 * will be (worst case - no concurrent execution) after moving the task
6130 grp_util
+= src_in_grp
? -eenv
->util_delta
: eenv
->util_delta
;
6133 ((long)sg
->sgc
->max_capacity
* (int)sg
->group_weight
)) {
6135 * After moving, the group will be fully occupied
6136 * so assume it will not be idle at all.
6142 * after moving, this group is at most partly
6143 * occupied, so it should have some idle time.
6145 max_idle_state_idx
= sg
->sge
->nr_idle_states
- 2;
6146 new_state
= grp_util
* max_idle_state_idx
;
6147 if (grp_util
<= 0) {
6148 /* group will have no util, use lowest state */
6149 new_state
= max_idle_state_idx
+ 1;
6152 * for partially idle, linearly map util to idle
6153 * states, excluding the lowest one. This does not
6154 * correspond to the state we expect to enter in
6155 * reality, but an indication of what might happen.
6157 new_state
= min_t(int, max_idle_state_idx
,
6158 new_state
/ sg
->sgc
->max_capacity
);
6159 new_state
= max_idle_state_idx
- new_state
;
6164 #ifdef DEBUG_EENV_DECISIONS
6165 static struct _eenv_debug
*eenv_debug_entry_ptr(struct _eenv_debug
*base
, int idx
);
6167 static void store_energy_calc_debug_info(struct energy_env
*eenv
, int cpu_idx
, int cap_idx
, int idle_idx
)
6169 int debug_idx
= eenv
->cpu
[cpu_idx
].debug_idx
;
6170 unsigned long sg_util
, busy_energy
, idle_energy
;
6171 const struct sched_group_energy
*sge
;
6172 struct _eenv_debug
*dbg
;
6175 if (debug_idx
< EAS_EENV_DEBUG_LEVELS
) {
6176 sge
= eenv
->sg
->sge
;
6177 sg_util
= group_norm_util(eenv
, cpu_idx
);
6178 busy_energy
= sge
->cap_states
[cap_idx
].power
;
6179 busy_energy
*= sg_util
;
6180 idle_energy
= SCHED_CAPACITY_SCALE
- sg_util
;
6181 idle_energy
*= sge
->idle_states
[idle_idx
].power
;
6182 /* should we use sg_cap or sg? */
6183 dbg
= eenv_debug_entry_ptr(eenv
->cpu
[cpu_idx
].debug
, debug_idx
);
6184 dbg
->cap
= sge
->cap_states
[cap_idx
].cap
;
6185 dbg
->norm_util
= sg_util
;
6186 dbg
->cap_energy
= sge
->cap_states
[cap_idx
].power
;
6187 dbg
->idle_energy
= sge
->idle_states
[idle_idx
].power
;
6188 dbg
->this_energy
= busy_energy
+ idle_energy
;
6189 dbg
->this_busy_energy
= busy_energy
;
6190 dbg
->this_idle_energy
= idle_energy
;
6192 cpumask_copy(&dbg
->group_cpumask
,
6193 sched_group_span(eenv
->sg
));
6195 for_each_cpu(cpu
, &dbg
->group_cpumask
)
6196 dbg
->cpu_util
[cpu
] = cpu_util(cpu
);
6198 eenv
->cpu
[cpu_idx
].debug_idx
= debug_idx
+1;
6202 #define store_energy_calc_debug_info(a,b,c,d) {}
6203 #endif /* DEBUG_EENV_DECISIONS */
6206 * calc_sg_energy: compute energy for the eenv's SG (i.e. eenv->sg).
6208 * This works in iterations to compute the SG's energy for each CPU
6209 * candidate defined by the energy_env's cpu array.
6211 static void calc_sg_energy(struct energy_env
*eenv
)
6213 struct sched_group
*sg
= eenv
->sg
;
6214 unsigned long busy_energy
, idle_energy
;
6215 unsigned int busy_power
, idle_power
;
6216 unsigned long total_energy
= 0;
6217 unsigned long sg_util
;
6218 int cap_idx
, idle_idx
;
6221 for (cpu_idx
= EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; ++cpu_idx
) {
6222 if (eenv
->cpu
[cpu_idx
].cpu_id
== -1)
6225 /* Compute ACTIVE energy */
6226 cap_idx
= find_new_capacity(eenv
, cpu_idx
);
6227 busy_power
= sg
->sge
->cap_states
[cap_idx
].power
;
6228 sg_util
= group_norm_util(eenv
, cpu_idx
);
6229 busy_energy
= sg_util
* busy_power
;
6231 /* Compute IDLE energy */
6232 idle_idx
= group_idle_state(eenv
, cpu_idx
);
6233 idle_power
= sg
->sge
->idle_states
[idle_idx
].power
;
6234 idle_energy
= SCHED_CAPACITY_SCALE
- sg_util
;
6235 idle_energy
*= idle_power
;
6237 total_energy
= busy_energy
+ idle_energy
;
6238 eenv
->cpu
[cpu_idx
].energy
+= total_energy
;
6240 store_energy_calc_debug_info(eenv
, cpu_idx
, cap_idx
, idle_idx
);
6245 * compute_energy() computes the absolute variation in energy consumption by
6246 * moving eenv.util_delta from EAS_CPU_PRV to EAS_CPU_NXT.
6248 * NOTE: compute_energy() may fail when racing with sched_domain updates, in
6249 * which case we abort by returning -EINVAL.
6251 static int compute_energy(struct energy_env
*eenv
)
6253 struct sched_domain
*sd
;
6255 struct cpumask visit_cpus
;
6256 struct sched_group
*sg
;
6258 WARN_ON(!eenv
->sg_top
->sge
);
6260 cpumask_copy(&visit_cpus
, sched_group_span(eenv
->sg_top
));
6262 while (!cpumask_empty(&visit_cpus
)) {
6263 struct sched_group
*sg_shared_cap
= NULL
;
6265 cpu
= cpumask_first(&visit_cpus
);
6268 * Is the group utilization affected by cpus outside this
6271 sd
= rcu_dereference(per_cpu(sd_scs
, cpu
));
6272 if (sd
&& sd
->parent
)
6273 sg_shared_cap
= sd
->parent
->groups
;
6275 for_each_domain(cpu
, sd
) {
6278 /* Has this sched_domain already been visited? */
6279 if (sd
->child
&& group_first_cpu(sg
) != cpu
)
6284 if (sg_shared_cap
&& sg_shared_cap
->group_weight
>= sg
->group_weight
)
6285 eenv
->sg_cap
= sg_shared_cap
;
6288 * Compute the energy for all the candidate
6289 * CPUs in the current visited SG.
6292 calc_sg_energy(eenv
);
6294 /* remove CPUs we have just visited */
6296 cpumask_xor(&visit_cpus
, &visit_cpus
, sched_group_span(sg
));
6298 if (cpumask_equal(sched_group_span(sg
), sched_group_span(eenv
->sg_top
)))
6301 } while (sg
= sg
->next
, sg
!= sd
->groups
);
6310 static inline bool cpu_in_sg(struct sched_group
*sg
, int cpu
)
6312 return cpu
!= -1 && cpumask_test_cpu(cpu
, sched_group_span(sg
));
6315 #ifdef DEBUG_EENV_DECISIONS
6316 static void dump_eenv_debug(struct energy_env
*eenv
)
6318 int cpu_idx
, grp_idx
;
6319 char cpu_utils
[(NR_CPUS
*12)+10]="cpu_util: ";
6322 trace_printk("eenv scenario: task=%p %s task_util=%lu prev_cpu=%d",
6323 eenv
->p
, eenv
->p
->comm
, eenv
->util_delta
, eenv
->cpu
[EAS_CPU_PRV
].cpu_id
);
6325 for (cpu_idx
=EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; cpu_idx
++) {
6326 if (eenv
->cpu
[cpu_idx
].cpu_id
== -1)
6328 trace_printk("---Scenario %d: Place task on cpu %d energy=%lu (%d debug logs at %p)",
6329 cpu_idx
+1, eenv
->cpu
[cpu_idx
].cpu_id
,
6330 eenv
->cpu
[cpu_idx
].energy
>> SCHED_CAPACITY_SHIFT
,
6331 eenv
->cpu
[cpu_idx
].debug_idx
,
6332 eenv
->cpu
[cpu_idx
].debug
);
6333 for (grp_idx
= 0; grp_idx
< eenv
->cpu
[cpu_idx
].debug_idx
; grp_idx
++) {
6334 struct _eenv_debug
*debug
;
6337 debug
= eenv_debug_entry_ptr(eenv
->cpu
[cpu_idx
].debug
, grp_idx
);
6338 cpu
= scnprintf(cpulist
, sizeof(cpulist
), "%*pbl", cpumask_pr_args(&debug
->group_cpumask
));
6341 /* print out the relevant cpu_util */
6342 for_each_cpu(cpu
, &(debug
->group_cpumask
)) {
6344 if (written
> sizeof(cpu_utils
)-10) {
6345 cpu_utils
[written
]=0;
6348 written
+= snprintf(tmp
, sizeof(tmp
), "cpu%d(%lu) ", cpu
, debug
->cpu_util
[cpu
]);
6349 strcat(cpu_utils
, tmp
);
6351 /* trace the data */
6352 trace_printk(" | %s : cap=%lu nutil=%lu, cap_nrg=%lu, idle_nrg=%lu energy=%lu busy_energy=%lu idle_energy=%lu %s",
6353 cpulist
, debug
->cap
, debug
->norm_util
,
6354 debug
->cap_energy
, debug
->idle_energy
,
6355 debug
->this_energy
>> SCHED_CAPACITY_SHIFT
,
6356 debug
->this_busy_energy
>> SCHED_CAPACITY_SHIFT
,
6357 debug
->this_idle_energy
>> SCHED_CAPACITY_SHIFT
,
6361 trace_printk("---");
6363 trace_printk("----- done");
6367 #define dump_eenv_debug(a) {}
6368 #endif /* DEBUG_EENV_DECISIONS */
6370 * select_energy_cpu_idx(): estimate the energy impact of changing the
6371 * utilization distribution.
6373 * The eenv parameter specifies the changes: utilization amount and a
6374 * collection of possible CPU candidates. The number of candidates
6375 * depends upon the selection algorithm used.
6377 * If find_best_target was used to select candidate CPUs, there will
6378 * be at most 3 including prev_cpu. If not, we used a brute force
6379 * selection which will provide the union of:
6380 * * CPUs belonging to the highest sd which is not overutilized
6381 * * CPUs the task is allowed to run on
6384 * This function returns the index of a CPU candidate specified by the
6385 * energy_env which corresponds to the most energy efficient CPU.
6386 * Thus, 0 (EAS_CPU_PRV) means that non of the CPU candidate is more energy
6387 * efficient than running on prev_cpu. This is also the value returned in case
6388 * of abort due to error conditions during the computations. The only
6389 * exception to this if we fail to access the energy model via sd_ea, where
6390 * we return -1 with the intent of asking the system to use a different
6391 * wakeup placement algorithm.
6393 * A value greater than zero means that the most energy efficient CPU is the
6394 * one represented by eenv->cpu[eenv->next_idx].cpu_id.
6396 static inline int select_energy_cpu_idx(struct energy_env
*eenv
)
6398 int last_cpu_idx
= eenv
->max_cpu_count
- 1;
6399 struct sched_domain
*sd
;
6400 struct sched_group
*sg
;
6405 sd_cpu
= eenv
->cpu
[EAS_CPU_PRV
].cpu_id
;
6406 sd
= rcu_dereference(per_cpu(sd_ea
, sd_cpu
));
6410 cpumask_clear(&eenv
->cpus_mask
);
6411 for (cpu_idx
= EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; ++cpu_idx
) {
6412 int cpu
= eenv
->cpu
[cpu_idx
].cpu_id
;
6416 cpumask_set_cpu(cpu
, &eenv
->cpus_mask
);
6421 /* Skip SGs which do not contains a candidate CPU */
6422 if (!cpumask_intersects(&eenv
->cpus_mask
, sched_group_span(sg
)))
6426 if (compute_energy(eenv
) == -EINVAL
)
6428 } while (sg
= sg
->next
, sg
!= sd
->groups
);
6429 /* remember - eenv energy values are unscaled */
6432 * Compute the dead-zone margin used to prevent too many task
6433 * migrations with negligible energy savings.
6434 * An energy saving is considered meaningful if it reduces the energy
6435 * consumption of EAS_CPU_PRV CPU candidate by at least ~1.56%
6437 margin
= eenv
->cpu
[EAS_CPU_PRV
].energy
>> 6;
6440 * By default the EAS_CPU_PRV CPU is considered the most energy
6441 * efficient, with a 0 energy variation.
6443 eenv
->next_idx
= EAS_CPU_PRV
;
6444 eenv
->cpu
[EAS_CPU_PRV
].nrg_delta
= 0;
6446 dump_eenv_debug(eenv
);
6449 * Compare the other CPU candidates to find a CPU which can be
6450 * more energy efficient then EAS_CPU_PRV
6452 if (sched_feat(FBT_STRICT_ORDER
))
6453 last_cpu_idx
= EAS_CPU_BKP
;
6455 for(cpu_idx
= EAS_CPU_NXT
; cpu_idx
<= last_cpu_idx
; cpu_idx
++) {
6456 if (eenv
->cpu
[cpu_idx
].cpu_id
< 0)
6458 eenv
->cpu
[cpu_idx
].nrg_delta
=
6459 eenv
->cpu
[cpu_idx
].energy
-
6460 eenv
->cpu
[EAS_CPU_PRV
].energy
;
6462 /* filter energy variations within the dead-zone margin */
6463 if (abs(eenv
->cpu
[cpu_idx
].nrg_delta
) < margin
)
6464 eenv
->cpu
[cpu_idx
].nrg_delta
= 0;
6465 /* update the schedule candidate with min(nrg_delta) */
6466 if (eenv
->cpu
[cpu_idx
].nrg_delta
<
6467 eenv
->cpu
[eenv
->next_idx
].nrg_delta
) {
6468 eenv
->next_idx
= cpu_idx
;
6469 /* break out if we want to stop on first saving candidate */
6470 if (sched_feat(FBT_STRICT_ORDER
))
6475 return eenv
->next_idx
;
6479 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6481 * A waker of many should wake a different task than the one last awakened
6482 * at a frequency roughly N times higher than one of its wakees.
6484 * In order to determine whether we should let the load spread vs consolidating
6485 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6486 * partner, and a factor of lls_size higher frequency in the other.
6488 * With both conditions met, we can be relatively sure that the relationship is
6489 * non-monogamous, with partner count exceeding socket size.
6491 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6492 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6495 static int wake_wide(struct task_struct
*p
, int sibling_count_hint
)
6497 unsigned int master
= current
->wakee_flips
;
6498 unsigned int slave
= p
->wakee_flips
;
6499 int llc_size
= this_cpu_read(sd_llc_size
);
6501 if (sibling_count_hint
>= llc_size
)
6505 swap(master
, slave
);
6506 if (slave
< llc_size
|| master
< slave
* llc_size
)
6512 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6513 * soonest. For the purpose of speed we only consider the waking and previous
6516 * wake_affine_idle() - only considers 'now', it check if the waking CPU is (or
6519 * wake_affine_weight() - considers the weight to reflect the average
6520 * scheduling latency of the CPUs. This seems to work
6521 * for the overloaded case.
6525 wake_affine_idle(struct sched_domain
*sd
, struct task_struct
*p
,
6526 int this_cpu
, int prev_cpu
, int sync
)
6528 if (idle_cpu(this_cpu
))
6531 if (sync
&& cpu_rq(this_cpu
)->nr_running
== 1)
6538 wake_affine_weight(struct sched_domain
*sd
, struct task_struct
*p
,
6539 int this_cpu
, int prev_cpu
, int sync
)
6541 s64 this_eff_load
, prev_eff_load
;
6542 unsigned long task_load
;
6544 this_eff_load
= target_load(this_cpu
, sd
->wake_idx
);
6545 prev_eff_load
= source_load(prev_cpu
, sd
->wake_idx
);
6548 unsigned long current_load
= task_h_load(current
);
6550 if (current_load
> this_eff_load
)
6553 this_eff_load
-= current_load
;
6556 task_load
= task_h_load(p
);
6558 this_eff_load
+= task_load
;
6559 if (sched_feat(WA_BIAS
))
6560 this_eff_load
*= 100;
6561 this_eff_load
*= capacity_of(prev_cpu
);
6563 prev_eff_load
-= task_load
;
6564 if (sched_feat(WA_BIAS
))
6565 prev_eff_load
*= 100 + (sd
->imbalance_pct
- 100) / 2;
6566 prev_eff_load
*= capacity_of(this_cpu
);
6568 return this_eff_load
<= prev_eff_load
;
6571 static int wake_affine(struct sched_domain
*sd
, struct task_struct
*p
,
6572 int prev_cpu
, int sync
)
6574 int this_cpu
= smp_processor_id();
6575 bool affine
= false;
6577 if (sched_feat(WA_IDLE
) && !affine
)
6578 affine
= wake_affine_idle(sd
, p
, this_cpu
, prev_cpu
, sync
);
6580 if (sched_feat(WA_WEIGHT
) && !affine
)
6581 affine
= wake_affine_weight(sd
, p
, this_cpu
, prev_cpu
, sync
);
6583 schedstat_inc(p
->se
.statistics
.nr_wakeups_affine_attempts
);
6585 schedstat_inc(sd
->ttwu_move_affine
);
6586 schedstat_inc(p
->se
.statistics
.nr_wakeups_affine
);
6592 #ifdef CONFIG_SCHED_TUNE
6593 struct reciprocal_value schedtune_spc_rdiv
;
6596 schedtune_margin(unsigned long signal
, long boost
)
6598 long long margin
= 0;
6601 * Signal proportional compensation (SPC)
6603 * The Boost (B) value is used to compute a Margin (M) which is
6604 * proportional to the complement of the original Signal (S):
6605 * M = B * (SCHED_CAPACITY_SCALE - S)
6606 * The obtained M could be used by the caller to "boost" S.
6609 margin
= SCHED_CAPACITY_SCALE
- signal
;
6612 margin
= -signal
* boost
;
6614 margin
= reciprocal_divide(margin
, schedtune_spc_rdiv
);
6622 schedtune_cpu_margin(unsigned long util
, int cpu
)
6624 int boost
= schedtune_cpu_boost(cpu
);
6629 return schedtune_margin(util
, boost
);
6633 schedtune_task_margin(struct task_struct
*task
)
6635 int boost
= schedtune_task_boost(task
);
6642 util
= task_util_est(task
);
6643 margin
= schedtune_margin(util
, boost
);
6648 #else /* CONFIG_SCHED_TUNE */
6651 schedtune_cpu_margin(unsigned long util
, int cpu
)
6657 schedtune_task_margin(struct task_struct
*task
)
6662 #endif /* CONFIG_SCHED_TUNE */
6665 boosted_cpu_util(int cpu
, unsigned long other_util
)
6667 unsigned long util
= cpu_util_freq(cpu
) + other_util
;
6668 long margin
= schedtune_cpu_margin(util
, cpu
);
6670 trace_sched_boost_cpu(cpu
, util
, margin
);
6672 return util
+ margin
;
6675 static inline unsigned long
6676 boosted_task_util(struct task_struct
*task
)
6678 unsigned long util
= task_util_est(task
);
6679 long margin
= schedtune_task_margin(task
);
6681 trace_sched_boost_task(task
, util
, margin
);
6683 return util
+ margin
;
6686 static unsigned long capacity_spare_wake(int cpu
, struct task_struct
*p
)
6688 return max_t(long, capacity_of(cpu
) - cpu_util_wake(cpu
, p
), 0);
6692 * find_idlest_group finds and returns the least busy CPU group within the
6695 * Assumes p is allowed on at least one CPU in sd.
6697 static struct sched_group
*
6698 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
,
6699 int this_cpu
, int sd_flag
)
6701 struct sched_group
*idlest
= NULL
, *group
= sd
->groups
;
6702 struct sched_group
*most_spare_sg
= NULL
;
6703 unsigned long min_runnable_load
= ULONG_MAX
;
6704 unsigned long this_runnable_load
= ULONG_MAX
;
6705 unsigned long min_avg_load
= ULONG_MAX
, this_avg_load
= ULONG_MAX
;
6706 unsigned long most_spare
= 0, this_spare
= 0;
6707 int load_idx
= sd
->forkexec_idx
;
6708 int imbalance_scale
= 100 + (sd
->imbalance_pct
-100)/2;
6709 unsigned long imbalance
= scale_load_down(NICE_0_LOAD
) *
6710 (sd
->imbalance_pct
-100) / 100;
6712 if (sd_flag
& SD_BALANCE_WAKE
)
6713 load_idx
= sd
->wake_idx
;
6716 unsigned long load
, avg_load
, runnable_load
;
6717 unsigned long spare_cap
, max_spare_cap
;
6721 /* Skip over this group if it has no CPUs allowed */
6722 if (!cpumask_intersects(sched_group_span(group
),
6726 local_group
= cpumask_test_cpu(this_cpu
,
6727 sched_group_span(group
));
6730 * Tally up the load of all CPUs in the group and find
6731 * the group containing the CPU with most spare capacity.
6737 for_each_cpu(i
, sched_group_span(group
)) {
6738 /* Bias balancing toward cpus of our domain */
6740 load
= source_load(i
, load_idx
);
6742 load
= target_load(i
, load_idx
);
6744 runnable_load
+= load
;
6746 avg_load
+= cfs_rq_load_avg(&cpu_rq(i
)->cfs
);
6748 spare_cap
= capacity_spare_wake(i
, p
);
6750 if (spare_cap
> max_spare_cap
)
6751 max_spare_cap
= spare_cap
;
6754 /* Adjust by relative CPU capacity of the group */
6755 avg_load
= (avg_load
* SCHED_CAPACITY_SCALE
) /
6756 group
->sgc
->capacity
;
6757 runnable_load
= (runnable_load
* SCHED_CAPACITY_SCALE
) /
6758 group
->sgc
->capacity
;
6761 this_runnable_load
= runnable_load
;
6762 this_avg_load
= avg_load
;
6763 this_spare
= max_spare_cap
;
6765 if (min_runnable_load
> (runnable_load
+ imbalance
)) {
6767 * The runnable load is significantly smaller
6768 * so we can pick this new cpu
6770 min_runnable_load
= runnable_load
;
6771 min_avg_load
= avg_load
;
6773 } else if ((runnable_load
< (min_runnable_load
+ imbalance
)) &&
6774 (100*min_avg_load
> imbalance_scale
*avg_load
)) {
6776 * The runnable loads are close so take the
6777 * blocked load into account through avg_load.
6779 min_avg_load
= avg_load
;
6783 if (most_spare
< max_spare_cap
) {
6784 most_spare
= max_spare_cap
;
6785 most_spare_sg
= group
;
6788 } while (group
= group
->next
, group
!= sd
->groups
);
6791 * The cross-over point between using spare capacity or least load
6792 * is too conservative for high utilization tasks on partially
6793 * utilized systems if we require spare_capacity > task_util(p),
6794 * so we allow for some task stuffing by using
6795 * spare_capacity > task_util(p)/2.
6797 * Spare capacity can't be used for fork because the utilization has
6798 * not been set yet, we must first select a rq to compute the initial
6801 if (sd_flag
& SD_BALANCE_FORK
)
6804 if (this_spare
> task_util(p
) / 2 &&
6805 imbalance_scale
*this_spare
> 100*most_spare
)
6808 if (most_spare
> task_util(p
) / 2)
6809 return most_spare_sg
;
6815 if (min_runnable_load
> (this_runnable_load
+ imbalance
))
6818 if ((this_runnable_load
< (min_runnable_load
+ imbalance
)) &&
6819 (100*this_avg_load
< imbalance_scale
*min_avg_load
))
6826 * find_idlest_group_cpu - find the idlest cpu among the cpus in group.
6829 find_idlest_group_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
6831 unsigned long load
, min_load
= ULONG_MAX
;
6832 unsigned int min_exit_latency
= UINT_MAX
;
6833 u64 latest_idle_timestamp
= 0;
6834 int least_loaded_cpu
= this_cpu
;
6835 int shallowest_idle_cpu
= -1;
6838 /* Check if we have any choice: */
6839 if (group
->group_weight
== 1)
6840 return cpumask_first(sched_group_span(group
));
6842 /* Traverse only the allowed CPUs */
6843 for_each_cpu_and(i
, sched_group_span(group
), &p
->cpus_allowed
) {
6845 struct rq
*rq
= cpu_rq(i
);
6846 struct cpuidle_state
*idle
= idle_get_state(rq
);
6847 if (idle
&& idle
->exit_latency
< min_exit_latency
) {
6849 * We give priority to a CPU whose idle state
6850 * has the smallest exit latency irrespective
6851 * of any idle timestamp.
6853 min_exit_latency
= idle
->exit_latency
;
6854 latest_idle_timestamp
= rq
->idle_stamp
;
6855 shallowest_idle_cpu
= i
;
6856 } else if ((!idle
|| idle
->exit_latency
== min_exit_latency
) &&
6857 rq
->idle_stamp
> latest_idle_timestamp
) {
6859 * If equal or no active idle state, then
6860 * the most recently idled CPU might have
6863 latest_idle_timestamp
= rq
->idle_stamp
;
6864 shallowest_idle_cpu
= i
;
6866 } else if (shallowest_idle_cpu
== -1) {
6867 load
= weighted_cpuload(cpu_rq(i
));
6868 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
6870 least_loaded_cpu
= i
;
6875 return shallowest_idle_cpu
!= -1 ? shallowest_idle_cpu
: least_loaded_cpu
;
6878 static inline int find_idlest_cpu(struct sched_domain
*sd
, struct task_struct
*p
,
6879 int cpu
, int prev_cpu
, int sd_flag
)
6883 if (!cpumask_intersects(sched_domain_span(sd
), &p
->cpus_allowed
))
6887 struct sched_group
*group
;
6888 struct sched_domain
*tmp
;
6891 if (!(sd
->flags
& sd_flag
)) {
6896 group
= find_idlest_group(sd
, p
, cpu
, sd_flag
);
6902 new_cpu
= find_idlest_group_cpu(group
, p
, cpu
);
6903 if (new_cpu
== cpu
) {
6904 /* Now try balancing at a lower domain level of cpu */
6909 /* Now try balancing at a lower domain level of new_cpu */
6911 weight
= sd
->span_weight
;
6913 for_each_domain(cpu
, tmp
) {
6914 if (weight
<= tmp
->span_weight
)
6916 if (tmp
->flags
& sd_flag
)
6919 /* while loop will break here if sd == NULL */
6925 #ifdef CONFIG_SCHED_SMT
6926 DEFINE_STATIC_KEY_FALSE(sched_smt_present
);
6928 static inline void set_idle_cores(int cpu
, int val
)
6930 struct sched_domain_shared
*sds
;
6932 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
6934 WRITE_ONCE(sds
->has_idle_cores
, val
);
6937 static inline bool test_idle_cores(int cpu
, bool def
)
6939 struct sched_domain_shared
*sds
;
6941 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
6943 return READ_ONCE(sds
->has_idle_cores
);
6949 * Scans the local SMT mask to see if the entire core is idle, and records this
6950 * information in sd_llc_shared->has_idle_cores.
6952 * Since SMT siblings share all cache levels, inspecting this limited remote
6953 * state should be fairly cheap.
6955 void __update_idle_core(struct rq
*rq
)
6957 int core
= cpu_of(rq
);
6961 if (test_idle_cores(core
, true))
6964 for_each_cpu(cpu
, cpu_smt_mask(core
)) {
6972 set_idle_cores(core
, 1);
6978 * Scan the entire LLC domain for idle cores; this dynamically switches off if
6979 * there are no idle cores left in the system; tracked through
6980 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6982 static int select_idle_core(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6984 struct cpumask
*cpus
= this_cpu_cpumask_var_ptr(select_idle_mask
);
6987 if (!static_branch_likely(&sched_smt_present
))
6990 if (!test_idle_cores(target
, false))
6993 cpumask_and(cpus
, sched_domain_span(sd
), &p
->cpus_allowed
);
6995 for_each_cpu_wrap(core
, cpus
, target
) {
6998 for_each_cpu(cpu
, cpu_smt_mask(core
)) {
6999 cpumask_clear_cpu(cpu
, cpus
);
7009 * Failed to find an idle core; stop looking for one.
7011 set_idle_cores(target
, 0);
7017 * Scan the local SMT mask for idle CPUs.
7019 static int select_idle_smt(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
7023 if (!static_branch_likely(&sched_smt_present
))
7026 for_each_cpu(cpu
, cpu_smt_mask(target
)) {
7027 if (!cpumask_test_cpu(cpu
, &p
->cpus_allowed
))
7036 #else /* CONFIG_SCHED_SMT */
7038 static inline int select_idle_core(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
7043 static inline int select_idle_smt(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
7048 #endif /* CONFIG_SCHED_SMT */
7051 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7052 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7053 * average idle time for this rq (as found in rq->avg_idle).
7055 static int select_idle_cpu(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
7057 struct sched_domain
*this_sd
;
7058 u64 avg_cost
, avg_idle
;
7061 int cpu
, nr
= INT_MAX
;
7063 this_sd
= rcu_dereference(*this_cpu_ptr(&sd_llc
));
7068 * Due to large variance we need a large fuzz factor; hackbench in
7069 * particularly is sensitive here.
7071 avg_idle
= this_rq()->avg_idle
/ 512;
7072 avg_cost
= this_sd
->avg_scan_cost
+ 1;
7074 if (sched_feat(SIS_AVG_CPU
) && avg_idle
< avg_cost
)
7077 if (sched_feat(SIS_PROP
)) {
7078 u64 span_avg
= sd
->span_weight
* avg_idle
;
7079 if (span_avg
> 4*avg_cost
)
7080 nr
= div_u64(span_avg
, avg_cost
);
7085 time
= local_clock();
7087 for_each_cpu_wrap(cpu
, sched_domain_span(sd
), target
) {
7090 if (!cpumask_test_cpu(cpu
, &p
->cpus_allowed
))
7096 time
= local_clock() - time
;
7097 cost
= this_sd
->avg_scan_cost
;
7098 delta
= (s64
)(time
- cost
) / 8;
7099 this_sd
->avg_scan_cost
+= delta
;
7105 * Try and locate an idle core/thread in the LLC cache domain.
7107 static inline int __select_idle_sibling(struct task_struct
*p
, int prev
, int target
)
7109 struct sched_domain
*sd
;
7112 if (idle_cpu(target
))
7116 * If the previous cpu is cache affine and idle, don't be stupid.
7118 if (prev
!= target
&& cpus_share_cache(prev
, target
) && idle_cpu(prev
))
7121 sd
= rcu_dereference(per_cpu(sd_llc
, target
));
7125 i
= select_idle_core(p
, sd
, target
);
7126 if ((unsigned)i
< nr_cpumask_bits
)
7129 i
= select_idle_cpu(p
, sd
, target
);
7130 if ((unsigned)i
< nr_cpumask_bits
)
7133 i
= select_idle_smt(p
, sd
, target
);
7134 if ((unsigned)i
< nr_cpumask_bits
)
7140 static inline int select_idle_sibling_cstate_aware(struct task_struct
*p
, int prev
, int target
)
7142 struct sched_domain
*sd
;
7143 struct sched_group
*sg
;
7144 int best_idle_cpu
= -1;
7145 int best_idle_cstate
= -1;
7146 int best_idle_capacity
= INT_MAX
;
7150 * Iterate the domains and find an elegible idle cpu.
7152 sd
= rcu_dereference(per_cpu(sd_llc
, target
));
7153 for_each_lower_domain(sd
) {
7156 if (!cpumask_intersects(
7157 sched_group_span(sg
), &p
->cpus_allowed
))
7160 for_each_cpu_and(i
, &p
->cpus_allowed
, sched_group_span(sg
)) {
7162 unsigned long new_usage
;
7163 unsigned long capacity_orig
;
7168 /* figure out if the task can fit here at all */
7169 new_usage
= boosted_task_util(p
);
7170 capacity_orig
= capacity_orig_of(i
);
7172 if (new_usage
> capacity_orig
)
7175 /* if the task fits without changing OPP and we
7176 * intended to use this CPU, just proceed
7178 if (i
== target
&& new_usage
<= capacity_curr_of(target
)) {
7182 /* otherwise select CPU with shallowest idle state
7183 * to reduce wakeup latency.
7185 idle_idx
= idle_get_state_idx(cpu_rq(i
));
7187 if (idle_idx
< best_idle_cstate
&&
7188 capacity_orig
<= best_idle_capacity
) {
7190 best_idle_cstate
= idle_idx
;
7191 best_idle_capacity
= capacity_orig
;
7196 } while (sg
!= sd
->groups
);
7199 if (best_idle_cpu
>= 0)
7200 target
= best_idle_cpu
;
7205 static int select_idle_sibling(struct task_struct
*p
, int prev
, int target
)
7207 if (!sysctl_sched_cstate_aware
)
7208 return __select_idle_sibling(p
, prev
, target
);
7210 return select_idle_sibling_cstate_aware(p
, prev
, target
);
7213 static inline int task_fits_capacity(struct task_struct
*p
, long capacity
)
7215 return capacity
* 1024 > boosted_task_util(p
) * capacity_margin
;
7218 static int start_cpu(bool boosted
)
7220 struct root_domain
*rd
= cpu_rq(smp_processor_id())->rd
;
7222 return boosted
? rd
->max_cap_orig_cpu
: rd
->min_cap_orig_cpu
;
7225 static inline int find_best_target(struct task_struct
*p
, int *backup_cpu
,
7226 bool boosted
, bool prefer_idle
)
7228 unsigned long min_util
= boosted_task_util(p
);
7229 unsigned long target_capacity
= ULONG_MAX
;
7230 unsigned long min_wake_util
= ULONG_MAX
;
7231 unsigned long target_max_spare_cap
= 0;
7232 unsigned long target_util
= ULONG_MAX
;
7233 unsigned long best_active_util
= ULONG_MAX
;
7234 int best_idle_cstate
= INT_MAX
;
7235 struct sched_domain
*sd
;
7236 struct sched_group
*sg
;
7237 int best_active_cpu
= -1;
7238 int best_idle_cpu
= -1;
7239 int target_cpu
= -1;
7245 * In most cases, target_capacity tracks capacity_orig of the most
7246 * energy efficient CPU candidate, thus requiring to minimise
7247 * target_capacity. For these cases target_capacity is already
7248 * initialized to ULONG_MAX.
7249 * However, for prefer_idle and boosted tasks we look for a high
7250 * performance CPU, thus requiring to maximise target_capacity. In this
7251 * case we initialise target_capacity to 0.
7253 if (prefer_idle
&& boosted
)
7254 target_capacity
= 0;
7256 /* Find start CPU based on boost value */
7257 cpu
= start_cpu(boosted
);
7261 /* Find SD for the start CPU */
7262 sd
= rcu_dereference(per_cpu(sd_ea
, cpu
));
7266 /* Scan CPUs in all SDs */
7269 for_each_cpu_and(i
, &p
->cpus_allowed
, sched_group_span(sg
)) {
7270 unsigned long capacity_curr
= capacity_curr_of(i
);
7271 unsigned long capacity_orig
= capacity_orig_of(i
);
7272 unsigned long wake_util
, new_util
;
7274 int idle_idx
= INT_MAX
;
7279 if (walt_cpu_high_irqload(i
))
7283 * p's blocked utilization is still accounted for on prev_cpu
7284 * so prev_cpu will receive a negative bias due to the double
7285 * accounting. However, the blocked utilization may be zero.
7287 wake_util
= cpu_util_wake(i
, p
);
7288 new_util
= wake_util
+ task_util_est(p
);
7291 * Ensure minimum capacity to grant the required boost.
7292 * The target CPU can be already at a capacity level higher
7293 * than the one required to boost the task.
7295 new_util
= max(min_util
, new_util
);
7296 if (new_util
> capacity_orig
)
7300 * Pre-compute the maximum possible capacity we expect
7301 * to have available on this CPU once the task is
7304 spare_cap
= capacity_orig
- new_util
;
7307 idle_idx
= idle_get_state_idx(cpu_rq(i
));
7311 * Case A) Latency sensitive tasks
7313 * Unconditionally favoring tasks that prefer idle CPU to
7317 * - an idle CPU, whatever its idle_state is, since
7318 * the first CPUs we explore are more likely to be
7319 * reserved for latency sensitive tasks.
7320 * - a non idle CPU where the task fits in its current
7321 * capacity and has the maximum spare capacity.
7322 * - a non idle CPU with lower contention from other
7323 * tasks and running at the lowest possible OPP.
7325 * The last two goals tries to favor a non idle CPU
7326 * where the task can run as if it is "almost alone".
7327 * A maximum spare capacity CPU is favoured since
7328 * the task already fits into that CPU's capacity
7329 * without waiting for an OPP chance.
7331 * The following code path is the only one in the CPUs
7332 * exploration loop which is always used by
7333 * prefer_idle tasks. It exits the loop with wither a
7334 * best_active_cpu or a target_cpu which should
7335 * represent an optimal choice for latency sensitive
7341 * Case A.1: IDLE CPU
7342 * Return the best IDLE CPU we find:
7343 * - for boosted tasks: the CPU with the highest
7344 * performance (i.e. biggest capacity_orig)
7345 * - for !boosted tasks: the most energy
7346 * efficient CPU (i.e. smallest capacity_orig)
7350 capacity_orig
< target_capacity
)
7353 capacity_orig
> target_capacity
)
7355 if (capacity_orig
== target_capacity
&&
7356 sysctl_sched_cstate_aware
&&
7357 best_idle_cstate
<= idle_idx
)
7360 target_capacity
= capacity_orig
;
7361 best_idle_cstate
= idle_idx
;
7365 if (best_idle_cpu
!= -1)
7369 * Case A.2: Target ACTIVE CPU
7370 * Favor CPUs with max spare capacity.
7372 if (capacity_curr
> new_util
&&
7373 spare_cap
> target_max_spare_cap
) {
7374 target_max_spare_cap
= spare_cap
;
7378 if (target_cpu
!= -1)
7383 * Case A.3: Backup ACTIVE CPU
7385 * - lower utilization due to other tasks
7386 * - lower utilization with the task in
7388 if (wake_util
> min_wake_util
)
7390 if (new_util
> best_active_util
)
7392 min_wake_util
= wake_util
;
7393 best_active_util
= new_util
;
7394 best_active_cpu
= i
;
7401 * For non latency sensitive tasks, skip CPUs that
7402 * will be overutilized by moving the task there.
7404 * The goal here is to remain in EAS mode as long as
7405 * possible at least for !prefer_idle tasks.
7407 if ((new_util
* capacity_margin
) >
7408 (capacity_orig
* SCHED_CAPACITY_SCALE
))
7412 * Favor CPUs with smaller capacity for non latency
7415 if (capacity_orig
> target_capacity
)
7419 * Case B) Non latency sensitive tasks on IDLE CPUs.
7421 * Find an optimal backup IDLE CPU for non latency
7425 * - minimizing the capacity_orig,
7426 * i.e. preferring LITTLE CPUs
7427 * - favoring shallowest idle states
7428 * i.e. avoid to wakeup deep-idle CPUs
7430 * The following code path is used by non latency
7431 * sensitive tasks if IDLE CPUs are available. If at
7432 * least one of such CPUs are available it sets the
7433 * best_idle_cpu to the most suitable idle CPU to be
7436 * If idle CPUs are available, favour these CPUs to
7437 * improve performances by spreading tasks.
7438 * Indeed, the energy_diff() computed by the caller
7439 * will take care to ensure the minimization of energy
7440 * consumptions without affecting performance.
7444 * Skip CPUs in deeper idle state, but only
7445 * if they are also less energy efficient.
7446 * IOW, prefer a deep IDLE LITTLE CPU vs a
7447 * shallow idle big CPU.
7449 if (capacity_orig
== target_capacity
&&
7450 sysctl_sched_cstate_aware
&&
7451 best_idle_cstate
<= idle_idx
)
7454 target_capacity
= capacity_orig
;
7455 best_idle_cstate
= idle_idx
;
7461 * Case C) Non latency sensitive tasks on ACTIVE CPUs.
7463 * Pack tasks in the most energy efficient capacities.
7465 * This task packing strategy prefers more energy
7466 * efficient CPUs (i.e. pack on smaller maximum
7467 * capacity CPUs) while also trying to spread tasks to
7468 * run them all at the lower OPP.
7470 * This assumes for example that it's more energy
7471 * efficient to run two tasks on two CPUs at a lower
7472 * OPP than packing both on a single CPU but running
7473 * that CPU at an higher OPP.
7475 * Thus, this case keep track of the CPU with the
7476 * smallest maximum capacity and highest spare maximum
7480 /* Favor CPUs with maximum spare capacity */
7481 if (capacity_orig
== target_capacity
&&
7482 spare_cap
< target_max_spare_cap
)
7485 target_max_spare_cap
= spare_cap
;
7486 target_capacity
= capacity_orig
;
7487 target_util
= new_util
;
7491 } while (sg
= sg
->next
, sg
!= sd
->groups
);
7494 * For non latency sensitive tasks, cases B and C in the previous loop,
7495 * we pick the best IDLE CPU only if we was not able to find a target
7498 * Policies priorities:
7500 * - prefer_idle tasks:
7502 * a) IDLE CPU available: best_idle_cpu
7503 * b) ACTIVE CPU where task fits and has the bigger maximum spare
7504 * capacity (i.e. target_cpu)
7505 * c) ACTIVE CPU with less contention due to other tasks
7506 * (i.e. best_active_cpu)
7508 * - NON prefer_idle tasks:
7510 * a) ACTIVE CPU: target_cpu
7511 * b) IDLE CPU: best_idle_cpu
7514 if (prefer_idle
&& (best_idle_cpu
!= -1)) {
7515 trace_sched_find_best_target(p
, prefer_idle
, min_util
, cpu
,
7516 best_idle_cpu
, best_active_cpu
,
7519 return best_idle_cpu
;
7522 if (target_cpu
== -1)
7523 target_cpu
= prefer_idle
7527 *backup_cpu
= prefer_idle
7531 trace_sched_find_best_target(p
, prefer_idle
, min_util
, cpu
,
7532 best_idle_cpu
, best_active_cpu
,
7535 /* it is possible for target and backup
7536 * to select same CPU - if so, drop backup
7538 if (*backup_cpu
== target_cpu
)
7545 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
7546 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
7548 * In that case WAKE_AFFINE doesn't make sense and we'll let
7549 * BALANCE_WAKE sort things out.
7551 static int wake_cap(struct task_struct
*p
, int cpu
, int prev_cpu
)
7553 long min_cap
, max_cap
;
7555 if (!static_branch_unlikely(&sched_asym_cpucapacity
))
7558 min_cap
= min(capacity_orig_of(prev_cpu
), capacity_orig_of(cpu
));
7559 max_cap
= cpu_rq(cpu
)->rd
->max_cpu_capacity
.val
;
7561 /* Minimum capacity is close to max, no need to abort wake_affine */
7562 if (max_cap
- min_cap
< max_cap
>> 3)
7565 /* Bring task utilization in sync with prev_cpu */
7566 sync_entity_load_avg(&p
->se
);
7568 return !task_fits_capacity(p
, min_cap
);
7571 static bool cpu_overutilized(int cpu
)
7573 return (capacity_of(cpu
) * 1024) < (cpu_util(cpu
) * capacity_margin
);
7576 DEFINE_PER_CPU(struct energy_env
, eenv_cache
);
7578 /* kernels often have NR_CPUS defined to be much
7579 * larger than exist in practise on booted systems.
7580 * Allocate the cpu array for eenv calculations
7581 * at boot time to avoid massive overprovisioning.
7583 #ifdef DEBUG_EENV_DECISIONS
7584 static inline int eenv_debug_size_per_dbg_entry(void)
7586 return sizeof(struct _eenv_debug
) + (sizeof(unsigned long) * num_possible_cpus());
7589 static inline int eenv_debug_size_per_cpu_entry(void)
7591 /* each cpu struct has an array of _eenv_debug structs
7592 * which have an array of unsigned longs at the end -
7593 * the allocation should be extended so that there are
7594 * at least 'num_possible_cpus' entries in the array.
7596 return EAS_EENV_DEBUG_LEVELS
* eenv_debug_size_per_dbg_entry();
7598 /* given a per-_eenv_cpu debug env ptr, get the ptr for a given index */
7599 static inline struct _eenv_debug
*eenv_debug_entry_ptr(struct _eenv_debug
*base
, int idx
)
7601 char *ptr
= (char *)base
;
7602 ptr
+= (idx
* eenv_debug_size_per_dbg_entry());
7603 return (struct _eenv_debug
*)ptr
;
7605 /* given a pointer to the per-cpu global copy of _eenv_debug, get
7606 * a pointer to the specified _eenv_cpu debug env.
7608 static inline struct _eenv_debug
*eenv_debug_percpu_debug_env_ptr(struct _eenv_debug
*base
, int cpu_idx
)
7610 char *ptr
= (char *)base
;
7611 ptr
+= (cpu_idx
* eenv_debug_size_per_cpu_entry());
7612 return (struct _eenv_debug
*)ptr
;
7615 static inline int eenv_debug_size(void)
7617 return num_possible_cpus() * eenv_debug_size_per_cpu_entry();
7621 static inline void alloc_eenv(void)
7624 int cpu_count
= num_possible_cpus();
7626 for_each_possible_cpu(cpu
) {
7627 struct energy_env
*eenv
= &per_cpu(eenv_cache
, cpu
);
7628 eenv
->cpu
= kmalloc(sizeof(struct eenv_cpu
) * cpu_count
, GFP_KERNEL
);
7629 eenv
->eenv_cpu_count
= cpu_count
;
7630 #ifdef DEBUG_EENV_DECISIONS
7631 eenv
->debug
= (struct _eenv_debug
*)kmalloc(eenv_debug_size(), GFP_KERNEL
);
7636 static inline void reset_eenv(struct energy_env
*eenv
)
7639 struct eenv_cpu
*cpu
;
7640 #ifdef DEBUG_EENV_DECISIONS
7641 struct _eenv_debug
*debug
;
7643 debug
= eenv
->debug
;
7646 cpu_count
= eenv
->eenv_cpu_count
;
7648 memset(eenv
, 0, sizeof(struct energy_env
));
7650 memset(eenv
->cpu
, 0, sizeof(struct eenv_cpu
)*cpu_count
);
7651 eenv
->eenv_cpu_count
= cpu_count
;
7653 #ifdef DEBUG_EENV_DECISIONS
7654 memset(debug
, 0, eenv_debug_size());
7655 eenv
->debug
= debug
;
7656 for(cpu_idx
= 0; cpu_idx
< eenv
->cpu_array_len
; cpu_idx
++)
7657 eenv
->cpu
[cpu_idx
].debug
= eenv_debug_percpu_debug_env_ptr(debug
, cpu_idx
);
7661 * get_eenv - reset the eenv struct cached for this CPU
7663 * When the eenv is returned, it is configured to do
7664 * energy calculations for the maximum number of CPUs
7665 * the task can be placed on. The prev_cpu entry is
7666 * filled in here. Callers are responsible for adding
7667 * other CPU candidates up to eenv->max_cpu_count.
7669 static inline struct energy_env
*get_eenv(struct task_struct
*p
, int prev_cpu
)
7671 struct energy_env
*eenv
;
7672 cpumask_t cpumask_possible_cpus
;
7673 int cpu
= smp_processor_id();
7676 eenv
= &(per_cpu(eenv_cache
, cpu
));
7681 /* use boosted task util for capacity selection
7682 * during energy calculation, but unboosted task
7683 * util for group utilization calculations
7685 eenv
->util_delta
= task_util_est(p
);
7686 eenv
->util_delta_boosted
= boosted_task_util(p
);
7688 cpumask_and(&cpumask_possible_cpus
, &p
->cpus_allowed
, cpu_online_mask
);
7689 eenv
->max_cpu_count
= cpumask_weight(&cpumask_possible_cpus
);
7691 for (i
=0; i
< eenv
->max_cpu_count
; i
++)
7692 eenv
->cpu
[i
].cpu_id
= -1;
7693 eenv
->cpu
[EAS_CPU_PRV
].cpu_id
= prev_cpu
;
7694 eenv
->next_idx
= EAS_CPU_PRV
;
7700 * Needs to be called inside rcu_read_lock critical section.
7701 * sd is a pointer to the sched domain we wish to use for an
7702 * energy-aware placement option.
7704 static int find_energy_efficient_cpu(struct sched_domain
*sd
,
7705 struct task_struct
*p
,
7706 int cpu
, int prev_cpu
,
7709 int use_fbt
= sched_feat(FIND_BEST_TARGET
);
7710 int cpu_iter
, eas_cpu_idx
= EAS_CPU_NXT
;
7711 int target_cpu
= -1;
7712 struct energy_env
*eenv
;
7714 if (sysctl_sched_sync_hint_enable
&& sync
) {
7715 if (cpumask_test_cpu(cpu
, &p
->cpus_allowed
)) {
7720 /* prepopulate energy diff environment */
7721 eenv
= get_eenv(p
, prev_cpu
);
7722 if (eenv
->max_cpu_count
< 2)
7727 * using this function outside wakeup balance will not supply
7728 * an sd ptr. Instead, fetch the highest level with energy data.
7731 sd
= rcu_dereference(per_cpu(sd_ea
, prev_cpu
));
7733 for_each_cpu_and(cpu_iter
, &p
->cpus_allowed
, sched_domain_span(sd
)) {
7734 unsigned long spare
;
7736 /* prev_cpu already in list */
7737 if (cpu_iter
== prev_cpu
)
7741 * Consider only CPUs where the task is expected to
7742 * fit without making the CPU overutilized.
7744 spare
= capacity_spare_wake(cpu_iter
, p
);
7745 if (spare
* 1024 < capacity_margin
* task_util_est(p
))
7748 /* Add CPU candidate */
7749 eenv
->cpu
[eas_cpu_idx
++].cpu_id
= cpu_iter
;
7750 eenv
->max_cpu_count
= eas_cpu_idx
;
7752 /* stop adding CPUs if we have no space left */
7753 if (eas_cpu_idx
>= eenv
->eenv_cpu_count
)
7757 int boosted
= (schedtune_task_boost(p
) > 0);
7761 * give compiler a hint that if sched_features
7762 * cannot be changed, it is safe to optimise out
7763 * all if(prefer_idle) blocks.
7765 prefer_idle
= sched_feat(EAS_PREFER_IDLE
) ?
7766 (schedtune_prefer_idle(p
) > 0) : 0;
7768 eenv
->max_cpu_count
= EAS_CPU_BKP
+ 1;
7770 /* Find a cpu with sufficient capacity */
7771 target_cpu
= find_best_target(p
, &eenv
->cpu
[EAS_CPU_BKP
].cpu_id
,
7772 boosted
, prefer_idle
);
7774 /* Immediately return a found idle CPU for a prefer_idle task */
7775 if (prefer_idle
&& target_cpu
>= 0 && idle_cpu(target_cpu
))
7778 /* Place target into NEXT slot */
7779 eenv
->cpu
[EAS_CPU_NXT
].cpu_id
= target_cpu
;
7781 /* take note if no backup was found */
7782 if (eenv
->cpu
[EAS_CPU_BKP
].cpu_id
< 0)
7783 eenv
->max_cpu_count
= EAS_CPU_BKP
;
7785 /* take note if no target was found */
7786 if (eenv
->cpu
[EAS_CPU_NXT
].cpu_id
< 0)
7787 eenv
->max_cpu_count
= EAS_CPU_NXT
;
7790 if (eenv
->max_cpu_count
== EAS_CPU_NXT
) {
7792 * we did not find any energy-awareness
7793 * candidates beyond prev_cpu, so we will
7794 * fall-back to the regular slow-path.
7799 /* find most energy-efficient CPU */
7800 target_cpu
= select_energy_cpu_idx(eenv
) < 0 ? -1 :
7801 eenv
->cpu
[eenv
->next_idx
].cpu_id
;
7806 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
);
7807 static void nohz_balancer_kick(bool only_update
);
7810 * wake_energy: Make the decision if we want to use an energy-aware
7811 * wakeup task placement or not. This is limited to situations where
7812 * we cannot use energy-awareness right now.
7814 * Returns TRUE if we should attempt energy-aware wakeup, FALSE if not.
7816 * Should only be called from select_task_rq_fair inside the RCU
7817 * read-side critical section.
7819 static inline int wake_energy(struct task_struct
*p
, int prev_cpu
,
7820 int sd_flag
, int wake_flags
)
7822 struct sched_domain
*sd
= NULL
;
7823 int sync
= wake_flags
& WF_SYNC
;
7825 sd
= rcu_dereference_sched(cpu_rq(prev_cpu
)->sd
);
7828 * Check all definite no-energy-awareness conditions
7833 if (!energy_aware())
7836 if (sd_overutilized(sd
))
7840 * we cannot do energy-aware wakeup placement sensibly
7841 * for tasks with 0 utilization, so let them be placed
7842 * according to the normal strategy.
7843 * However if fbt is in use we may still benefit from
7844 * the heuristics we use there in selecting candidate
7847 if (unlikely(!sched_feat(FIND_BEST_TARGET
) && !task_util_est(p
)))
7850 if(!sched_feat(EAS_PREFER_IDLE
)){
7852 * Force prefer-idle tasks into the slow path, this may not happen
7853 * if none of the sd flags matched.
7855 if (schedtune_prefer_idle(p
) > 0 && !sync
)
7862 * select_task_rq_fair: Select target runqueue for the waking task in domains
7863 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
7864 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7866 * Balances load by selecting the idlest cpu in the idlest group, or under
7867 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
7869 * Returns the target cpu number.
7871 * preempt must be disabled.
7874 select_task_rq_fair(struct task_struct
*p
, int prev_cpu
, int sd_flag
, int wake_flags
,
7875 int sibling_count_hint
)
7877 struct sched_domain
*tmp
, *affine_sd
= NULL
;
7878 struct sched_domain
*sd
= NULL
, *energy_sd
= NULL
;
7879 int cpu
= smp_processor_id();
7880 int new_cpu
= prev_cpu
;
7881 int want_affine
= 0;
7882 int want_energy
= 0;
7883 int sync
= wake_flags
& WF_SYNC
;
7887 if (sd_flag
& SD_BALANCE_WAKE
) {
7889 want_energy
= wake_energy(p
, prev_cpu
, sd_flag
, wake_flags
);
7890 want_affine
= !want_energy
&&
7891 !wake_wide(p
, sibling_count_hint
) &&
7892 !wake_cap(p
, cpu
, prev_cpu
) &&
7893 cpumask_test_cpu(cpu
, &p
->cpus_allowed
);
7896 for_each_domain(cpu
, tmp
) {
7897 if (!(tmp
->flags
& SD_LOAD_BALANCE
))
7901 * If both cpu and prev_cpu are part of this domain,
7902 * cpu is a valid SD_WAKE_AFFINE target.
7904 if (want_affine
&& (tmp
->flags
& SD_WAKE_AFFINE
) &&
7905 cpumask_test_cpu(prev_cpu
, sched_domain_span(tmp
))) {
7911 * If we are able to try an energy-aware wakeup,
7912 * select the highest non-overutilized sched domain
7913 * which includes this cpu and prev_cpu
7915 * maybe want to not test prev_cpu and only consider
7919 !sd_overutilized(tmp
) &&
7920 cpumask_test_cpu(prev_cpu
, sched_domain_span(tmp
)))
7923 if (tmp
->flags
& sd_flag
)
7925 else if (!(want_affine
|| want_energy
))
7930 sd
= NULL
; /* Prefer wake_affine over balance flags */
7931 if (cpu
== prev_cpu
)
7934 if (wake_affine(affine_sd
, p
, prev_cpu
, sync
))
7938 if (sd
&& !(sd_flag
& SD_BALANCE_FORK
)) {
7940 * We're going to need the task's util for capacity_spare_wake
7941 * in find_idlest_group. Sync it up to prev_cpu's
7944 sync_entity_load_avg(&p
->se
);
7949 if (sd_flag
& SD_BALANCE_WAKE
) /* XXX always ? */
7950 new_cpu
= select_idle_sibling(p
, prev_cpu
, new_cpu
);
7954 new_cpu
= find_energy_efficient_cpu(energy_sd
, p
, cpu
, prev_cpu
, sync
);
7956 /* if we did an energy-aware placement and had no choices available
7957 * then fall back to the default find_idlest_cpu choice
7959 if (!energy_sd
|| (energy_sd
&& new_cpu
== -1))
7960 new_cpu
= find_idlest_cpu(sd
, p
, cpu
, prev_cpu
, sd_flag
);
7965 #ifdef CONFIG_NO_HZ_COMMON
7966 if (nohz_kick_needed(cpu_rq(new_cpu
), true))
7967 nohz_balancer_kick(true);
7974 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
7975 * cfs_rq_of(p) references at time of call are still valid and identify the
7976 * previous cpu. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7978 static void migrate_task_rq_fair(struct task_struct
*p
)
7981 * As blocked tasks retain absolute vruntime the migration needs to
7982 * deal with this by subtracting the old and adding the new
7983 * min_vruntime -- the latter is done by enqueue_entity() when placing
7984 * the task on the new runqueue.
7986 if (p
->state
== TASK_WAKING
) {
7987 struct sched_entity
*se
= &p
->se
;
7988 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
7991 #ifndef CONFIG_64BIT
7992 u64 min_vruntime_copy
;
7995 min_vruntime_copy
= cfs_rq
->min_vruntime_copy
;
7997 min_vruntime
= cfs_rq
->min_vruntime
;
7998 } while (min_vruntime
!= min_vruntime_copy
);
8000 min_vruntime
= cfs_rq
->min_vruntime
;
8003 se
->vruntime
-= min_vruntime
;
8007 * We are supposed to update the task to "current" time, then its up to date
8008 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
8009 * what current time is, so simply throw away the out-of-date time. This
8010 * will result in the wakee task is less decayed, but giving the wakee more
8011 * load sounds not bad.
8013 remove_entity_load_avg(&p
->se
);
8015 /* Tell new CPU we are migrated */
8016 p
->se
.avg
.last_update_time
= 0;
8018 /* We have migrated, no longer consider this task hot */
8019 p
->se
.exec_start
= 0;
8022 static void task_dead_fair(struct task_struct
*p
)
8024 remove_entity_load_avg(&p
->se
);
8026 #endif /* CONFIG_SMP */
8028 static unsigned long
8029 wakeup_gran(struct sched_entity
*curr
, struct sched_entity
*se
)
8031 unsigned long gran
= sysctl_sched_wakeup_granularity
;
8034 * Since its curr running now, convert the gran from real-time
8035 * to virtual-time in his units.
8037 * By using 'se' instead of 'curr' we penalize light tasks, so
8038 * they get preempted easier. That is, if 'se' < 'curr' then
8039 * the resulting gran will be larger, therefore penalizing the
8040 * lighter, if otoh 'se' > 'curr' then the resulting gran will
8041 * be smaller, again penalizing the lighter task.
8043 * This is especially important for buddies when the leftmost
8044 * task is higher priority than the buddy.
8046 return calc_delta_fair(gran
, se
);
8050 * Should 'se' preempt 'curr'.
8064 wakeup_preempt_entity(struct sched_entity
*curr
, struct sched_entity
*se
)
8066 s64 gran
, vdiff
= curr
->vruntime
- se
->vruntime
;
8071 gran
= wakeup_gran(curr
, se
);
8078 static void set_last_buddy(struct sched_entity
*se
)
8080 if (entity_is_task(se
) && unlikely(task_of(se
)->policy
== SCHED_IDLE
))
8083 for_each_sched_entity(se
) {
8084 if (SCHED_WARN_ON(!se
->on_rq
))
8086 cfs_rq_of(se
)->last
= se
;
8090 static void set_next_buddy(struct sched_entity
*se
)
8092 if (entity_is_task(se
) && unlikely(task_of(se
)->policy
== SCHED_IDLE
))
8095 for_each_sched_entity(se
) {
8096 if (SCHED_WARN_ON(!se
->on_rq
))
8098 cfs_rq_of(se
)->next
= se
;
8102 static void set_skip_buddy(struct sched_entity
*se
)
8104 for_each_sched_entity(se
)
8105 cfs_rq_of(se
)->skip
= se
;
8109 * Preempt the current task with a newly woken task if needed:
8111 static void check_preempt_wakeup(struct rq
*rq
, struct task_struct
*p
, int wake_flags
)
8113 struct task_struct
*curr
= rq
->curr
;
8114 struct sched_entity
*se
= &curr
->se
, *pse
= &p
->se
;
8115 struct cfs_rq
*cfs_rq
= task_cfs_rq(curr
);
8116 int scale
= cfs_rq
->nr_running
>= sched_nr_latency
;
8117 int next_buddy_marked
= 0;
8119 if (unlikely(se
== pse
))
8123 * This is possible from callers such as attach_tasks(), in which we
8124 * unconditionally check_prempt_curr() after an enqueue (which may have
8125 * lead to a throttle). This both saves work and prevents false
8126 * next-buddy nomination below.
8128 if (unlikely(throttled_hierarchy(cfs_rq_of(pse
))))
8131 if (sched_feat(NEXT_BUDDY
) && scale
&& !(wake_flags
& WF_FORK
)) {
8132 set_next_buddy(pse
);
8133 next_buddy_marked
= 1;
8137 * We can come here with TIF_NEED_RESCHED already set from new task
8140 * Note: this also catches the edge-case of curr being in a throttled
8141 * group (e.g. via set_curr_task), since update_curr() (in the
8142 * enqueue of curr) will have resulted in resched being set. This
8143 * prevents us from potentially nominating it as a false LAST_BUDDY
8146 if (test_tsk_need_resched(curr
))
8149 /* Idle tasks are by definition preempted by non-idle tasks. */
8150 if (unlikely(curr
->policy
== SCHED_IDLE
) &&
8151 likely(p
->policy
!= SCHED_IDLE
))
8155 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8156 * is driven by the tick):
8158 if (unlikely(p
->policy
!= SCHED_NORMAL
) || !sched_feat(WAKEUP_PREEMPTION
))
8161 find_matching_se(&se
, &pse
);
8162 update_curr(cfs_rq_of(se
));
8164 if (wakeup_preempt_entity(se
, pse
) == 1) {
8166 * Bias pick_next to pick the sched entity that is
8167 * triggering this preemption.
8169 if (!next_buddy_marked
)
8170 set_next_buddy(pse
);
8179 * Only set the backward buddy when the current task is still
8180 * on the rq. This can happen when a wakeup gets interleaved
8181 * with schedule on the ->pre_schedule() or idle_balance()
8182 * point, either of which can * drop the rq lock.
8184 * Also, during early boot the idle thread is in the fair class,
8185 * for obvious reasons its a bad idea to schedule back to it.
8187 if (unlikely(!se
->on_rq
|| curr
== rq
->idle
))
8190 if (sched_feat(LAST_BUDDY
) && scale
&& entity_is_task(se
))
8194 static struct task_struct
*
8195 pick_next_task_fair(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
8197 struct cfs_rq
*cfs_rq
= &rq
->cfs
;
8198 struct sched_entity
*se
;
8199 struct task_struct
*p
;
8203 if (!cfs_rq
->nr_running
)
8206 #ifdef CONFIG_FAIR_GROUP_SCHED
8207 if (prev
->sched_class
!= &fair_sched_class
)
8211 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8212 * likely that a next task is from the same cgroup as the current.
8214 * Therefore attempt to avoid putting and setting the entire cgroup
8215 * hierarchy, only change the part that actually changes.
8219 struct sched_entity
*curr
= cfs_rq
->curr
;
8222 * Since we got here without doing put_prev_entity() we also
8223 * have to consider cfs_rq->curr. If it is still a runnable
8224 * entity, update_curr() will update its vruntime, otherwise
8225 * forget we've ever seen it.
8229 update_curr(cfs_rq
);
8234 * This call to check_cfs_rq_runtime() will do the
8235 * throttle and dequeue its entity in the parent(s).
8236 * Therefore the nr_running test will indeed
8239 if (unlikely(check_cfs_rq_runtime(cfs_rq
))) {
8242 if (!cfs_rq
->nr_running
)
8249 se
= pick_next_entity(cfs_rq
, curr
);
8250 cfs_rq
= group_cfs_rq(se
);
8256 * Since we haven't yet done put_prev_entity and if the selected task
8257 * is a different task than we started out with, try and touch the
8258 * least amount of cfs_rqs.
8261 struct sched_entity
*pse
= &prev
->se
;
8263 while (!(cfs_rq
= is_same_group(se
, pse
))) {
8264 int se_depth
= se
->depth
;
8265 int pse_depth
= pse
->depth
;
8267 if (se_depth
<= pse_depth
) {
8268 put_prev_entity(cfs_rq_of(pse
), pse
);
8269 pse
= parent_entity(pse
);
8271 if (se_depth
>= pse_depth
) {
8272 set_next_entity(cfs_rq_of(se
), se
);
8273 se
= parent_entity(se
);
8277 put_prev_entity(cfs_rq
, pse
);
8278 set_next_entity(cfs_rq
, se
);
8281 if (hrtick_enabled(rq
))
8282 hrtick_start_fair(rq
, p
);
8284 update_misfit_status(p
, rq
);
8290 put_prev_task(rq
, prev
);
8293 se
= pick_next_entity(cfs_rq
, NULL
);
8294 set_next_entity(cfs_rq
, se
);
8295 cfs_rq
= group_cfs_rq(se
);
8300 if (hrtick_enabled(rq
))
8301 hrtick_start_fair(rq
, p
);
8303 update_misfit_status(p
, rq
);
8308 update_misfit_status(NULL
, rq
);
8309 new_tasks
= idle_balance(rq
, rf
);
8312 * Because idle_balance() releases (and re-acquires) rq->lock, it is
8313 * possible for any higher priority task to appear. In that case we
8314 * must re-start the pick_next_entity() loop.
8326 * Account for a descheduled task:
8328 static void put_prev_task_fair(struct rq
*rq
, struct task_struct
*prev
)
8330 struct sched_entity
*se
= &prev
->se
;
8331 struct cfs_rq
*cfs_rq
;
8333 for_each_sched_entity(se
) {
8334 cfs_rq
= cfs_rq_of(se
);
8335 put_prev_entity(cfs_rq
, se
);
8340 * sched_yield() is very simple
8342 * The magic of dealing with the ->skip buddy is in pick_next_entity.
8344 static void yield_task_fair(struct rq
*rq
)
8346 struct task_struct
*curr
= rq
->curr
;
8347 struct cfs_rq
*cfs_rq
= task_cfs_rq(curr
);
8348 struct sched_entity
*se
= &curr
->se
;
8351 * Are we the only task in the tree?
8353 if (unlikely(rq
->nr_running
== 1))
8356 clear_buddies(cfs_rq
, se
);
8358 if (curr
->policy
!= SCHED_BATCH
) {
8359 update_rq_clock(rq
);
8361 * Update run-time statistics of the 'current'.
8363 update_curr(cfs_rq
);
8365 * Tell update_rq_clock() that we've just updated,
8366 * so we don't do microscopic update in schedule()
8367 * and double the fastpath cost.
8369 rq_clock_skip_update(rq
, true);
8375 static bool yield_to_task_fair(struct rq
*rq
, struct task_struct
*p
, bool preempt
)
8377 struct sched_entity
*se
= &p
->se
;
8379 /* throttled hierarchies are not runnable */
8380 if (!se
->on_rq
|| throttled_hierarchy(cfs_rq_of(se
)))
8383 /* Tell the scheduler that we'd really like pse to run next. */
8386 yield_task_fair(rq
);
8392 /**************************************************
8393 * Fair scheduling class load-balancing methods.
8397 * The purpose of load-balancing is to achieve the same basic fairness the
8398 * per-cpu scheduler provides, namely provide a proportional amount of compute
8399 * time to each task. This is expressed in the following equation:
8401 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8403 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
8404 * W_i,0 is defined as:
8406 * W_i,0 = \Sum_j w_i,j (2)
8408 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
8409 * is derived from the nice value as per sched_prio_to_weight[].
8411 * The weight average is an exponential decay average of the instantaneous
8414 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8416 * C_i is the compute capacity of cpu i, typically it is the
8417 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8418 * can also include other factors [XXX].
8420 * To achieve this balance we define a measure of imbalance which follows
8421 * directly from (1):
8423 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8425 * We them move tasks around to minimize the imbalance. In the continuous
8426 * function space it is obvious this converges, in the discrete case we get
8427 * a few fun cases generally called infeasible weight scenarios.
8430 * - infeasible weights;
8431 * - local vs global optima in the discrete case. ]
8436 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8437 * for all i,j solution, we create a tree of cpus that follows the hardware
8438 * topology where each level pairs two lower groups (or better). This results
8439 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
8440 * tree to only the first of the previous level and we decrease the frequency
8441 * of load-balance at each level inv. proportional to the number of cpus in
8447 * \Sum { --- * --- * 2^i } = O(n) (5)
8449 * `- size of each group
8450 * | | `- number of cpus doing load-balance
8452 * `- sum over all levels
8454 * Coupled with a limit on how many tasks we can migrate every balance pass,
8455 * this makes (5) the runtime complexity of the balancer.
8457 * An important property here is that each CPU is still (indirectly) connected
8458 * to every other cpu in at most O(log n) steps:
8460 * The adjacency matrix of the resulting graph is given by:
8463 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8466 * And you'll find that:
8468 * A^(log_2 n)_i,j != 0 for all i,j (7)
8470 * Showing there's indeed a path between every cpu in at most O(log n) steps.
8471 * The task movement gives a factor of O(m), giving a convergence complexity
8474 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8479 * In order to avoid CPUs going idle while there's still work to do, new idle
8480 * balancing is more aggressive and has the newly idle cpu iterate up the domain
8481 * tree itself instead of relying on other CPUs to bring it work.
8483 * This adds some complexity to both (5) and (8) but it reduces the total idle
8491 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8494 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8499 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8501 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
8503 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8506 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8507 * rewrite all of this once again.]
8510 static unsigned long __read_mostly max_load_balance_interval
= HZ
/10;
8512 enum fbq_type
{ regular
, remote
, all
};
8521 #define LBF_ALL_PINNED 0x01
8522 #define LBF_NEED_BREAK 0x02
8523 #define LBF_DST_PINNED 0x04
8524 #define LBF_SOME_PINNED 0x08
8527 struct sched_domain
*sd
;
8535 struct cpumask
*dst_grpmask
;
8537 enum cpu_idle_type idle
;
8539 unsigned int src_grp_nr_running
;
8540 /* The set of CPUs under consideration for load-balancing */
8541 struct cpumask
*cpus
;
8546 unsigned int loop_break
;
8547 unsigned int loop_max
;
8549 enum fbq_type fbq_type
;
8550 enum group_type src_grp_type
;
8551 struct list_head tasks
;
8555 * Is this task likely cache-hot:
8557 static int task_hot(struct task_struct
*p
, struct lb_env
*env
)
8561 lockdep_assert_held(&env
->src_rq
->lock
);
8563 if (p
->sched_class
!= &fair_sched_class
)
8566 if (unlikely(p
->policy
== SCHED_IDLE
))
8570 * Buddy candidates are cache hot:
8572 if (sched_feat(CACHE_HOT_BUDDY
) && env
->dst_rq
->nr_running
&&
8573 (&p
->se
== cfs_rq_of(&p
->se
)->next
||
8574 &p
->se
== cfs_rq_of(&p
->se
)->last
))
8577 if (sysctl_sched_migration_cost
== -1)
8579 if (sysctl_sched_migration_cost
== 0)
8582 delta
= rq_clock_task(env
->src_rq
) - p
->se
.exec_start
;
8584 return delta
< (s64
)sysctl_sched_migration_cost
;
8587 #ifdef CONFIG_NUMA_BALANCING
8589 * Returns 1, if task migration degrades locality
8590 * Returns 0, if task migration improves locality i.e migration preferred.
8591 * Returns -1, if task migration is not affected by locality.
8593 static int migrate_degrades_locality(struct task_struct
*p
, struct lb_env
*env
)
8595 struct numa_group
*numa_group
= rcu_dereference(p
->numa_group
);
8596 unsigned long src_faults
, dst_faults
;
8597 int src_nid
, dst_nid
;
8599 if (!static_branch_likely(&sched_numa_balancing
))
8602 if (!p
->numa_faults
|| !(env
->sd
->flags
& SD_NUMA
))
8605 src_nid
= cpu_to_node(env
->src_cpu
);
8606 dst_nid
= cpu_to_node(env
->dst_cpu
);
8608 if (src_nid
== dst_nid
)
8611 /* Migrating away from the preferred node is always bad. */
8612 if (src_nid
== p
->numa_preferred_nid
) {
8613 if (env
->src_rq
->nr_running
> env
->src_rq
->nr_preferred_running
)
8619 /* Encourage migration to the preferred node. */
8620 if (dst_nid
== p
->numa_preferred_nid
)
8623 /* Leaving a core idle is often worse than degrading locality. */
8624 if (env
->idle
!= CPU_NOT_IDLE
)
8628 src_faults
= group_faults(p
, src_nid
);
8629 dst_faults
= group_faults(p
, dst_nid
);
8631 src_faults
= task_faults(p
, src_nid
);
8632 dst_faults
= task_faults(p
, dst_nid
);
8635 return dst_faults
< src_faults
;
8639 static inline int migrate_degrades_locality(struct task_struct
*p
,
8647 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8650 int can_migrate_task(struct task_struct
*p
, struct lb_env
*env
)
8654 lockdep_assert_held(&env
->src_rq
->lock
);
8657 * We do not migrate tasks that are:
8658 * 1) throttled_lb_pair, or
8659 * 2) cannot be migrated to this CPU due to cpus_allowed, or
8660 * 3) running (obviously), or
8661 * 4) are cache-hot on their current CPU.
8663 if (throttled_lb_pair(task_group(p
), env
->src_cpu
, env
->dst_cpu
))
8666 if (!cpumask_test_cpu(env
->dst_cpu
, &p
->cpus_allowed
)) {
8669 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_affine
);
8671 env
->flags
|= LBF_SOME_PINNED
;
8674 * Remember if this task can be migrated to any other cpu in
8675 * our sched_group. We may want to revisit it if we couldn't
8676 * meet load balance goals by pulling other tasks on src_cpu.
8678 * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
8679 * already computed one in current iteration.
8681 if (env
->idle
== CPU_NEWLY_IDLE
|| (env
->flags
& LBF_DST_PINNED
))
8684 /* Prevent to re-select dst_cpu via env's cpus */
8685 for_each_cpu_and(cpu
, env
->dst_grpmask
, env
->cpus
) {
8686 if (cpumask_test_cpu(cpu
, &p
->cpus_allowed
)) {
8687 env
->flags
|= LBF_DST_PINNED
;
8688 env
->new_dst_cpu
= cpu
;
8696 /* Record that we found atleast one task that could run on dst_cpu */
8697 env
->flags
&= ~LBF_ALL_PINNED
;
8699 if (task_running(env
->src_rq
, p
)) {
8700 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_running
);
8705 * Aggressive migration if:
8706 * 1) destination numa is preferred
8707 * 2) task is cache cold, or
8708 * 3) too many balance attempts have failed.
8710 tsk_cache_hot
= migrate_degrades_locality(p
, env
);
8711 if (tsk_cache_hot
== -1)
8712 tsk_cache_hot
= task_hot(p
, env
);
8714 if (tsk_cache_hot
<= 0 ||
8715 env
->sd
->nr_balance_failed
> env
->sd
->cache_nice_tries
) {
8716 if (tsk_cache_hot
== 1) {
8717 schedstat_inc(env
->sd
->lb_hot_gained
[env
->idle
]);
8718 schedstat_inc(p
->se
.statistics
.nr_forced_migrations
);
8723 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_hot
);
8728 * detach_task() -- detach the task for the migration specified in env
8730 static void detach_task(struct task_struct
*p
, struct lb_env
*env
)
8732 lockdep_assert_held(&env
->src_rq
->lock
);
8734 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
8735 deactivate_task(env
->src_rq
, p
, DEQUEUE_NOCLOCK
);
8736 set_task_cpu(p
, env
->dst_cpu
);
8740 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8741 * part of active balancing operations within "domain".
8743 * Returns a task if successful and NULL otherwise.
8745 static struct task_struct
*detach_one_task(struct lb_env
*env
)
8747 struct task_struct
*p
, *n
;
8749 lockdep_assert_held(&env
->src_rq
->lock
);
8751 list_for_each_entry_safe(p
, n
, &env
->src_rq
->cfs_tasks
, se
.group_node
) {
8752 if (!can_migrate_task(p
, env
))
8755 detach_task(p
, env
);
8758 * Right now, this is only the second place where
8759 * lb_gained[env->idle] is updated (other is detach_tasks)
8760 * so we can safely collect stats here rather than
8761 * inside detach_tasks().
8763 schedstat_inc(env
->sd
->lb_gained
[env
->idle
]);
8769 static const unsigned int sched_nr_migrate_break
= 32;
8772 * detach_tasks() -- tries to detach up to imbalance weighted load from
8773 * busiest_rq, as part of a balancing operation within domain "sd".
8775 * Returns number of detached tasks if successful and 0 otherwise.
8777 static int detach_tasks(struct lb_env
*env
)
8779 struct list_head
*tasks
= &env
->src_rq
->cfs_tasks
;
8780 struct task_struct
*p
;
8784 lockdep_assert_held(&env
->src_rq
->lock
);
8786 if (env
->imbalance
<= 0)
8789 while (!list_empty(tasks
)) {
8791 * We don't want to steal all, otherwise we may be treated likewise,
8792 * which could at worst lead to a livelock crash.
8794 if (env
->idle
!= CPU_NOT_IDLE
&& env
->src_rq
->nr_running
<= 1)
8797 p
= list_first_entry(tasks
, struct task_struct
, se
.group_node
);
8800 /* We've more or less seen every task there is, call it quits */
8801 if (env
->loop
> env
->loop_max
)
8804 /* take a breather every nr_migrate tasks */
8805 if (env
->loop
> env
->loop_break
) {
8806 env
->loop_break
+= sched_nr_migrate_break
;
8807 env
->flags
|= LBF_NEED_BREAK
;
8811 if (!can_migrate_task(p
, env
))
8814 load
= task_h_load(p
);
8816 if (sched_feat(LB_MIN
) && load
< 16 && !env
->sd
->nr_balance_failed
)
8819 if ((load
/ 2) > env
->imbalance
)
8822 detach_task(p
, env
);
8823 list_add(&p
->se
.group_node
, &env
->tasks
);
8826 env
->imbalance
-= load
;
8828 #ifdef CONFIG_PREEMPT
8830 * NEWIDLE balancing is a source of latency, so preemptible
8831 * kernels will stop after the first task is detached to minimize
8832 * the critical section.
8834 if (env
->idle
== CPU_NEWLY_IDLE
)
8839 * We only want to steal up to the prescribed amount of
8842 if (env
->imbalance
<= 0)
8847 list_move_tail(&p
->se
.group_node
, tasks
);
8851 * Right now, this is one of only two places we collect this stat
8852 * so we can safely collect detach_one_task() stats here rather
8853 * than inside detach_one_task().
8855 schedstat_add(env
->sd
->lb_gained
[env
->idle
], detached
);
8861 * attach_task() -- attach the task detached by detach_task() to its new rq.
8863 static void attach_task(struct rq
*rq
, struct task_struct
*p
)
8865 lockdep_assert_held(&rq
->lock
);
8867 BUG_ON(task_rq(p
) != rq
);
8868 activate_task(rq
, p
, ENQUEUE_NOCLOCK
);
8869 p
->on_rq
= TASK_ON_RQ_QUEUED
;
8870 check_preempt_curr(rq
, p
, 0);
8874 * attach_one_task() -- attaches the task returned from detach_one_task() to
8877 static void attach_one_task(struct rq
*rq
, struct task_struct
*p
)
8882 update_rq_clock(rq
);
8888 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8891 static void attach_tasks(struct lb_env
*env
)
8893 struct list_head
*tasks
= &env
->tasks
;
8894 struct task_struct
*p
;
8897 rq_lock(env
->dst_rq
, &rf
);
8898 update_rq_clock(env
->dst_rq
);
8900 while (!list_empty(tasks
)) {
8901 p
= list_first_entry(tasks
, struct task_struct
, se
.group_node
);
8902 list_del_init(&p
->se
.group_node
);
8904 attach_task(env
->dst_rq
, p
);
8907 rq_unlock(env
->dst_rq
, &rf
);
8910 #ifdef CONFIG_FAIR_GROUP_SCHED
8912 static inline bool cfs_rq_is_decayed(struct cfs_rq
*cfs_rq
)
8914 if (cfs_rq
->load
.weight
)
8917 if (cfs_rq
->avg
.load_sum
)
8920 if (cfs_rq
->avg
.util_sum
)
8923 if (cfs_rq
->runnable_load_sum
)
8929 static void update_blocked_averages(int cpu
)
8931 struct rq
*rq
= cpu_rq(cpu
);
8932 struct cfs_rq
*cfs_rq
, *pos
;
8935 rq_lock_irqsave(rq
, &rf
);
8936 update_rq_clock(rq
);
8939 * Iterates the task_group tree in a bottom up fashion, see
8940 * list_add_leaf_cfs_rq() for details.
8942 for_each_leaf_cfs_rq_safe(rq
, cfs_rq
, pos
) {
8943 struct sched_entity
*se
;
8945 /* throttled entities do not contribute to load */
8946 if (throttled_hierarchy(cfs_rq
))
8949 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq
), cfs_rq
))
8950 update_tg_load_avg(cfs_rq
, 0);
8952 /* Propagate pending load changes to the parent, if any: */
8953 se
= cfs_rq
->tg
->se
[cpu
];
8954 if (se
&& !skip_blocked_update(se
))
8955 update_load_avg(se
, 0);
8958 * There can be a lot of idle CPU cgroups. Don't let fully
8959 * decayed cfs_rqs linger on the list.
8961 if (cfs_rq_is_decayed(cfs_rq
))
8962 list_del_leaf_cfs_rq(cfs_rq
);
8964 update_rt_rq_load_avg(rq_clock_task(rq
), cpu
, &rq
->rt
, 0);
8965 #ifdef CONFIG_NO_HZ_COMMON
8966 rq
->last_blocked_load_update_tick
= jiffies
;
8968 rq_unlock_irqrestore(rq
, &rf
);
8972 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
8973 * This needs to be done in a top-down fashion because the load of a child
8974 * group is a fraction of its parents load.
8976 static void update_cfs_rq_h_load(struct cfs_rq
*cfs_rq
)
8978 struct rq
*rq
= rq_of(cfs_rq
);
8979 struct sched_entity
*se
= cfs_rq
->tg
->se
[cpu_of(rq
)];
8980 unsigned long now
= jiffies
;
8983 if (cfs_rq
->last_h_load_update
== now
)
8986 cfs_rq
->h_load_next
= NULL
;
8987 for_each_sched_entity(se
) {
8988 cfs_rq
= cfs_rq_of(se
);
8989 cfs_rq
->h_load_next
= se
;
8990 if (cfs_rq
->last_h_load_update
== now
)
8995 cfs_rq
->h_load
= cfs_rq_load_avg(cfs_rq
);
8996 cfs_rq
->last_h_load_update
= now
;
8999 while ((se
= cfs_rq
->h_load_next
) != NULL
) {
9000 load
= cfs_rq
->h_load
;
9001 load
= div64_ul(load
* se
->avg
.load_avg
,
9002 cfs_rq_load_avg(cfs_rq
) + 1);
9003 cfs_rq
= group_cfs_rq(se
);
9004 cfs_rq
->h_load
= load
;
9005 cfs_rq
->last_h_load_update
= now
;
9009 static unsigned long task_h_load(struct task_struct
*p
)
9011 struct cfs_rq
*cfs_rq
= task_cfs_rq(p
);
9013 update_cfs_rq_h_load(cfs_rq
);
9014 return div64_ul(p
->se
.avg
.load_avg
* cfs_rq
->h_load
,
9015 cfs_rq_load_avg(cfs_rq
) + 1);
9018 static inline void update_blocked_averages(int cpu
)
9020 struct rq
*rq
= cpu_rq(cpu
);
9021 struct cfs_rq
*cfs_rq
= &rq
->cfs
;
9024 rq_lock_irqsave(rq
, &rf
);
9025 update_rq_clock(rq
);
9026 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq
), cfs_rq
);
9027 update_rt_rq_load_avg(rq_clock_task(rq
), cpu
, &rq
->rt
, 0);
9028 #ifdef CONFIG_NO_HZ_COMMON
9029 rq
->last_blocked_load_update_tick
= jiffies
;
9031 rq_unlock_irqrestore(rq
, &rf
);
9034 static unsigned long task_h_load(struct task_struct
*p
)
9036 return p
->se
.avg
.load_avg
;
9040 /********** Helpers for find_busiest_group ************************/
9043 * sg_lb_stats - stats of a sched_group required for load_balancing
9045 struct sg_lb_stats
{
9046 unsigned long avg_load
; /*Avg load across the CPUs of the group */
9047 unsigned long group_load
; /* Total load over the CPUs of the group */
9048 unsigned long sum_weighted_load
; /* Weighted load of group's tasks */
9049 unsigned long load_per_task
;
9050 unsigned long group_capacity
;
9051 unsigned long group_util
; /* Total utilization of the group */
9052 unsigned int sum_nr_running
; /* Nr tasks running in the group */
9053 unsigned int idle_cpus
;
9054 unsigned int group_weight
;
9055 enum group_type group_type
;
9056 int group_no_capacity
;
9057 /* A cpu has a task too big for its capacity */
9058 unsigned long group_misfit_task_load
;
9059 #ifdef CONFIG_NUMA_BALANCING
9060 unsigned int nr_numa_running
;
9061 unsigned int nr_preferred_running
;
9066 * sd_lb_stats - Structure to store the statistics of a sched_domain
9067 * during load balancing.
9069 struct sd_lb_stats
{
9070 struct sched_group
*busiest
; /* Busiest group in this sd */
9071 struct sched_group
*local
; /* Local group in this sd */
9072 unsigned long total_running
;
9073 unsigned long total_load
; /* Total load of all groups in sd */
9074 unsigned long total_capacity
; /* Total capacity of all groups in sd */
9075 unsigned long total_util
; /* Total util of all groups in sd */
9076 unsigned long avg_load
; /* Average load across all groups in sd */
9078 struct sg_lb_stats busiest_stat
;/* Statistics of the busiest group */
9079 struct sg_lb_stats local_stat
; /* Statistics of the local group */
9082 static inline void init_sd_lb_stats(struct sd_lb_stats
*sds
)
9085 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9086 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9087 * We must however clear busiest_stat::avg_load because
9088 * update_sd_pick_busiest() reads this before assignment.
9090 *sds
= (struct sd_lb_stats
){
9093 .total_running
= 0UL,
9095 .total_capacity
= 0UL,
9099 .sum_nr_running
= 0,
9100 .group_type
= group_other
,
9106 * get_sd_load_idx - Obtain the load index for a given sched domain.
9107 * @sd: The sched_domain whose load_idx is to be obtained.
9108 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
9110 * Return: The load index.
9112 static inline int get_sd_load_idx(struct sched_domain
*sd
,
9113 enum cpu_idle_type idle
)
9119 load_idx
= sd
->busy_idx
;
9122 case CPU_NEWLY_IDLE
:
9123 load_idx
= sd
->newidle_idx
;
9126 load_idx
= sd
->idle_idx
;
9133 static unsigned long scale_rt_capacity(int cpu
)
9135 struct rq
*rq
= cpu_rq(cpu
);
9136 u64 total
, used
, age_stamp
, avg
;
9140 * Since we're reading these variables without serialization make sure
9141 * we read them once before doing sanity checks on them.
9143 age_stamp
= READ_ONCE(rq
->age_stamp
);
9144 avg
= READ_ONCE(rq
->rt_avg
);
9145 delta
= __rq_clock_broken(rq
) - age_stamp
;
9147 if (unlikely(delta
< 0))
9150 total
= sched_avg_period() + delta
;
9152 used
= div_u64(avg
, total
);
9154 if (likely(used
< SCHED_CAPACITY_SCALE
))
9155 return SCHED_CAPACITY_SCALE
- used
;
9160 void init_max_cpu_capacity(struct max_cpu_capacity
*mcc
)
9162 raw_spin_lock_init(&mcc
->lock
);
9167 static void update_cpu_capacity(struct sched_domain
*sd
, int cpu
)
9169 unsigned long capacity
= arch_scale_cpu_capacity(sd
, cpu
);
9170 struct sched_group
*sdg
= sd
->groups
;
9171 struct max_cpu_capacity
*mcc
;
9172 unsigned long max_capacity
;
9174 unsigned long flags
;
9176 cpu_rq(cpu
)->cpu_capacity_orig
= capacity
;
9178 capacity
*= arch_scale_max_freq_capacity(sd
, cpu
);
9179 capacity
>>= SCHED_CAPACITY_SHIFT
;
9181 mcc
= &cpu_rq(cpu
)->rd
->max_cpu_capacity
;
9183 raw_spin_lock_irqsave(&mcc
->lock
, flags
);
9184 max_capacity
= mcc
->val
;
9185 max_cap_cpu
= mcc
->cpu
;
9187 if ((max_capacity
> capacity
&& max_cap_cpu
== cpu
) ||
9188 max_capacity
< capacity
) {
9189 mcc
->val
= capacity
;
9191 #ifdef CONFIG_SCHED_DEBUG
9192 raw_spin_unlock_irqrestore(&mcc
->lock
, flags
);
9193 pr_info("CPU%d: update max cpu_capacity %lu\n", cpu
, capacity
);
9197 raw_spin_unlock_irqrestore(&mcc
->lock
, flags
);
9199 skip_unlock
: __attribute__ ((unused
));
9200 capacity
*= scale_rt_capacity(cpu
);
9201 capacity
>>= SCHED_CAPACITY_SHIFT
;
9206 cpu_rq(cpu
)->cpu_capacity
= capacity
;
9207 sdg
->sgc
->capacity
= capacity
;
9208 sdg
->sgc
->min_capacity
= capacity
;
9209 sdg
->sgc
->max_capacity
= capacity
;
9212 void update_group_capacity(struct sched_domain
*sd
, int cpu
)
9214 struct sched_domain
*child
= sd
->child
;
9215 struct sched_group
*group
, *sdg
= sd
->groups
;
9216 unsigned long capacity
, min_capacity
, max_capacity
;
9217 unsigned long interval
;
9219 interval
= msecs_to_jiffies(sd
->balance_interval
);
9220 interval
= clamp(interval
, 1UL, max_load_balance_interval
);
9221 sdg
->sgc
->next_update
= jiffies
+ interval
;
9224 update_cpu_capacity(sd
, cpu
);
9229 min_capacity
= ULONG_MAX
;
9232 if (child
->flags
& SD_OVERLAP
) {
9234 * SD_OVERLAP domains cannot assume that child groups
9235 * span the current group.
9238 for_each_cpu(cpu
, sched_group_span(sdg
)) {
9239 struct sched_group_capacity
*sgc
;
9240 struct rq
*rq
= cpu_rq(cpu
);
9243 * build_sched_domains() -> init_sched_groups_capacity()
9244 * gets here before we've attached the domains to the
9247 * Use capacity_of(), which is set irrespective of domains
9248 * in update_cpu_capacity().
9250 * This avoids capacity from being 0 and
9251 * causing divide-by-zero issues on boot.
9253 if (unlikely(!rq
->sd
)) {
9254 capacity
+= capacity_of(cpu
);
9256 sgc
= rq
->sd
->groups
->sgc
;
9257 capacity
+= sgc
->capacity
;
9260 min_capacity
= min(capacity
, min_capacity
);
9261 max_capacity
= max(capacity
, max_capacity
);
9265 * !SD_OVERLAP domains can assume that child groups
9266 * span the current group.
9269 group
= child
->groups
;
9271 struct sched_group_capacity
*sgc
= group
->sgc
;
9273 capacity
+= sgc
->capacity
;
9274 min_capacity
= min(sgc
->min_capacity
, min_capacity
);
9275 max_capacity
= max(sgc
->max_capacity
, max_capacity
);
9276 group
= group
->next
;
9277 } while (group
!= child
->groups
);
9280 sdg
->sgc
->capacity
= capacity
;
9281 sdg
->sgc
->min_capacity
= min_capacity
;
9282 sdg
->sgc
->max_capacity
= max_capacity
;
9286 * Check whether the capacity of the rq has been noticeably reduced by side
9287 * activity. The imbalance_pct is used for the threshold.
9288 * Return true is the capacity is reduced
9291 check_cpu_capacity(struct rq
*rq
, struct sched_domain
*sd
)
9293 return ((rq
->cpu_capacity
* sd
->imbalance_pct
) <
9294 (rq
->cpu_capacity_orig
* 100));
9298 * Group imbalance indicates (and tries to solve) the problem where balancing
9299 * groups is inadequate due to ->cpus_allowed constraints.
9301 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
9302 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
9305 * { 0 1 2 3 } { 4 5 6 7 }
9308 * If we were to balance group-wise we'd place two tasks in the first group and
9309 * two tasks in the second group. Clearly this is undesired as it will overload
9310 * cpu 3 and leave one of the cpus in the second group unused.
9312 * The current solution to this issue is detecting the skew in the first group
9313 * by noticing the lower domain failed to reach balance and had difficulty
9314 * moving tasks due to affinity constraints.
9316 * When this is so detected; this group becomes a candidate for busiest; see
9317 * update_sd_pick_busiest(). And calculate_imbalance() and
9318 * find_busiest_group() avoid some of the usual balance conditions to allow it
9319 * to create an effective group imbalance.
9321 * This is a somewhat tricky proposition since the next run might not find the
9322 * group imbalance and decide the groups need to be balanced again. A most
9323 * subtle and fragile situation.
9326 static inline int sg_imbalanced(struct sched_group
*group
)
9328 return group
->sgc
->imbalance
;
9332 * group_has_capacity returns true if the group has spare capacity that could
9333 * be used by some tasks.
9334 * We consider that a group has spare capacity if the * number of task is
9335 * smaller than the number of CPUs or if the utilization is lower than the
9336 * available capacity for CFS tasks.
9337 * For the latter, we use a threshold to stabilize the state, to take into
9338 * account the variance of the tasks' load and to return true if the available
9339 * capacity in meaningful for the load balancer.
9340 * As an example, an available capacity of 1% can appear but it doesn't make
9341 * any benefit for the load balance.
9344 group_has_capacity(struct lb_env
*env
, struct sg_lb_stats
*sgs
)
9346 if (sgs
->sum_nr_running
< sgs
->group_weight
)
9349 if ((sgs
->group_capacity
* 100) >
9350 (sgs
->group_util
* env
->sd
->imbalance_pct
))
9357 * group_is_overloaded returns true if the group has more tasks than it can
9359 * group_is_overloaded is not equals to !group_has_capacity because a group
9360 * with the exact right number of tasks, has no more spare capacity but is not
9361 * overloaded so both group_has_capacity and group_is_overloaded return
9365 group_is_overloaded(struct lb_env
*env
, struct sg_lb_stats
*sgs
)
9367 if (sgs
->sum_nr_running
<= sgs
->group_weight
)
9370 if ((sgs
->group_capacity
* 100) <
9371 (sgs
->group_util
* env
->sd
->imbalance_pct
))
9378 * group_smaller_min_cpu_capacity: Returns true if sched_group sg has smaller
9379 * per-CPU capacity than sched_group ref.
9382 group_smaller_min_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
9384 return sg
->sgc
->min_capacity
* capacity_margin
<
9385 ref
->sgc
->min_capacity
* 1024;
9389 * group_smaller_max_cpu_capacity: Returns true if sched_group sg has smaller
9390 * per-CPU capacity_orig than sched_group ref.
9393 group_smaller_max_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
9395 return sg
->sgc
->max_capacity
* capacity_margin
<
9396 ref
->sgc
->max_capacity
* 1024;
9400 * group_similar_cpu_capacity: Returns true if the minimum capacity of the
9401 * compared groups differ by less than 12.5%.
9404 group_similar_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
9406 long diff
= sg
->sgc
->min_capacity
- ref
->sgc
->min_capacity
;
9407 long max
= max(sg
->sgc
->min_capacity
, ref
->sgc
->min_capacity
);
9409 return abs(diff
) < max
>> 3;
9413 group_type
group_classify(struct sched_group
*group
,
9414 struct sg_lb_stats
*sgs
)
9416 if (sgs
->group_no_capacity
)
9417 return group_overloaded
;
9419 if (sg_imbalanced(group
))
9420 return group_imbalanced
;
9422 if (sgs
->group_misfit_task_load
)
9423 return group_misfit_task
;
9429 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9430 * @env: The load balancing environment.
9431 * @group: sched_group whose statistics are to be updated.
9432 * @load_idx: Load index of sched_domain of this_cpu for load calc.
9433 * @local_group: Does group contain this_cpu.
9434 * @sgs: variable to hold the statistics for this group.
9435 * @overload: Indicate pullable load (e.g. >1 runnable task).
9436 * @overutilized: Indicate overutilization for any CPU.
9438 static inline void update_sg_lb_stats(struct lb_env
*env
,
9439 struct sched_group
*group
, int load_idx
,
9440 int local_group
, struct sg_lb_stats
*sgs
,
9441 bool *overload
, bool *overutilized
, bool *misfit_task
)
9446 memset(sgs
, 0, sizeof(*sgs
));
9448 for_each_cpu_and(i
, sched_group_span(group
), env
->cpus
) {
9449 struct rq
*rq
= cpu_rq(i
);
9451 /* Bias balancing toward cpus of our domain */
9453 load
= target_load(i
, load_idx
);
9455 load
= source_load(i
, load_idx
);
9457 sgs
->group_load
+= load
;
9458 sgs
->group_util
+= cpu_util(i
);
9459 sgs
->sum_nr_running
+= rq
->cfs
.h_nr_running
;
9461 nr_running
= rq
->nr_running
;
9465 #ifdef CONFIG_NUMA_BALANCING
9466 sgs
->nr_numa_running
+= rq
->nr_numa_running
;
9467 sgs
->nr_preferred_running
+= rq
->nr_preferred_running
;
9469 sgs
->sum_weighted_load
+= weighted_cpuload(rq
);
9471 * No need to call idle_cpu() if nr_running is not 0
9473 if (!nr_running
&& idle_cpu(i
))
9476 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
9477 sgs
->group_misfit_task_load
< rq
->misfit_task_load
) {
9478 sgs
->group_misfit_task_load
= rq
->misfit_task_load
;
9483 if (cpu_overutilized(i
)) {
9484 *overutilized
= true;
9486 if (rq
->misfit_task_load
)
9487 *misfit_task
= true;
9491 /* Adjust by relative CPU capacity of the group */
9492 sgs
->group_capacity
= group
->sgc
->capacity
;
9493 sgs
->avg_load
= (sgs
->group_load
*SCHED_CAPACITY_SCALE
) / sgs
->group_capacity
;
9495 if (sgs
->sum_nr_running
)
9496 sgs
->load_per_task
= sgs
->sum_weighted_load
/ sgs
->sum_nr_running
;
9498 sgs
->group_weight
= group
->group_weight
;
9500 sgs
->group_no_capacity
= group_is_overloaded(env
, sgs
);
9501 sgs
->group_type
= group_classify(group
, sgs
);
9505 * update_sd_pick_busiest - return 1 on busiest group
9506 * @env: The load balancing environment.
9507 * @sds: sched_domain statistics
9508 * @sg: sched_group candidate to be checked for being the busiest
9509 * @sgs: sched_group statistics
9511 * Determine if @sg is a busier group than the previously selected
9514 * Return: %true if @sg is a busier group than the previously selected
9515 * busiest group. %false otherwise.
9517 static bool update_sd_pick_busiest(struct lb_env
*env
,
9518 struct sd_lb_stats
*sds
,
9519 struct sched_group
*sg
,
9520 struct sg_lb_stats
*sgs
)
9522 struct sg_lb_stats
*busiest
= &sds
->busiest_stat
;
9525 * Don't try to pull misfit tasks we can't help.
9526 * We can use max_capacity here as reduction in capacity on some
9527 * cpus in the group should either be possible to resolve
9528 * internally or be covered by avg_load imbalance (eventually).
9530 if (sgs
->group_type
== group_misfit_task
&&
9531 (!group_smaller_max_cpu_capacity(sg
, sds
->local
) ||
9532 !group_has_capacity(env
, &sds
->local_stat
)))
9535 if (sgs
->group_type
> busiest
->group_type
)
9538 if (sgs
->group_type
< busiest
->group_type
)
9541 if (sgs
->avg_load
<= busiest
->avg_load
)
9544 if (!(env
->sd
->flags
& SD_ASYM_CPUCAPACITY
))
9548 * Candidate sg has no more than one task per CPU and
9549 * has higher per-CPU capacity. Migrating tasks to less
9550 * capable CPUs may harm throughput. Maximize throughput,
9551 * power/energy consequences are not considered.
9553 if (sgs
->sum_nr_running
<= sgs
->group_weight
&&
9554 group_smaller_min_cpu_capacity(sds
->local
, sg
))
9558 * Candidate sg doesn't face any severe imbalance issues so
9559 * don't disturb unless the groups are of similar capacity
9560 * where balancing is more harmless.
9562 if (sgs
->group_type
== group_other
&&
9563 !group_similar_cpu_capacity(sds
->local
, sg
))
9567 * If we have more than one misfit sg go with the biggest misfit.
9569 if (sgs
->group_type
== group_misfit_task
&&
9570 sgs
->group_misfit_task_load
< busiest
->group_misfit_task_load
)
9574 /* This is the busiest node in its class. */
9575 if (!(env
->sd
->flags
& SD_ASYM_PACKING
))
9578 /* No ASYM_PACKING if target cpu is already busy */
9579 if (env
->idle
== CPU_NOT_IDLE
)
9582 * ASYM_PACKING needs to move all the work to the highest
9583 * prority CPUs in the group, therefore mark all groups
9584 * of lower priority than ourself as busy.
9586 if (sgs
->sum_nr_running
&&
9587 sched_asym_prefer(env
->dst_cpu
, sg
->asym_prefer_cpu
)) {
9591 /* Prefer to move from lowest priority cpu's work */
9592 if (sched_asym_prefer(sds
->busiest
->asym_prefer_cpu
,
9593 sg
->asym_prefer_cpu
))
9600 #ifdef CONFIG_NUMA_BALANCING
9601 static inline enum fbq_type
fbq_classify_group(struct sg_lb_stats
*sgs
)
9603 if (sgs
->sum_nr_running
> sgs
->nr_numa_running
)
9605 if (sgs
->sum_nr_running
> sgs
->nr_preferred_running
)
9610 static inline enum fbq_type
fbq_classify_rq(struct rq
*rq
)
9612 if (rq
->nr_running
> rq
->nr_numa_running
)
9614 if (rq
->nr_running
> rq
->nr_preferred_running
)
9619 static inline enum fbq_type
fbq_classify_group(struct sg_lb_stats
*sgs
)
9624 static inline enum fbq_type
fbq_classify_rq(struct rq
*rq
)
9628 #endif /* CONFIG_NUMA_BALANCING */
9630 #ifdef CONFIG_NO_HZ_COMMON
9632 cpumask_var_t idle_cpus_mask
;
9634 unsigned long next_balance
; /* in jiffy units */
9635 unsigned long next_update
; /* in jiffy units */
9636 } nohz ____cacheline_aligned
;
9639 #define lb_sd_parent(sd) \
9640 (sd->parent && sd->parent->groups != sd->parent->groups->next)
9643 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
9644 * @env: The load balancing environment.
9645 * @sds: variable to hold the statistics for this sched_domain.
9647 static inline void update_sd_lb_stats(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9649 struct sched_domain
*child
= env
->sd
->child
;
9650 struct sched_group
*sg
= env
->sd
->groups
;
9651 struct sg_lb_stats
*local
= &sds
->local_stat
;
9652 struct sg_lb_stats tmp_sgs
;
9654 bool overload
= false, overutilized
= false, misfit_task
= false;
9655 bool prefer_sibling
= child
&& child
->flags
& SD_PREFER_SIBLING
;
9657 #ifdef CONFIG_NO_HZ_COMMON
9658 if (env
->idle
== CPU_NEWLY_IDLE
) {
9661 /* Update the stats of NOHZ idle CPUs in the sd */
9662 for_each_cpu_and(cpu
, sched_domain_span(env
->sd
),
9663 nohz
.idle_cpus_mask
) {
9664 struct rq
*rq
= cpu_rq(cpu
);
9666 /* ... Unless we've already done since the last tick */
9667 if (time_after(jiffies
,
9668 rq
->last_blocked_load_update_tick
))
9669 update_blocked_averages(cpu
);
9673 * If we've just updated all of the NOHZ idle CPUs, then we can push
9674 * back the next nohz.next_update, which will prevent an unnecessary
9675 * wakeup for the nohz stats kick
9677 if (cpumask_subset(nohz
.idle_cpus_mask
, sched_domain_span(env
->sd
)))
9678 nohz
.next_update
= jiffies
+ LOAD_AVG_PERIOD
;
9681 load_idx
= get_sd_load_idx(env
->sd
, env
->idle
);
9684 struct sg_lb_stats
*sgs
= &tmp_sgs
;
9687 local_group
= cpumask_test_cpu(env
->dst_cpu
, sched_group_span(sg
));
9692 if (env
->idle
!= CPU_NEWLY_IDLE
||
9693 time_after_eq(jiffies
, sg
->sgc
->next_update
))
9694 update_group_capacity(env
->sd
, env
->dst_cpu
);
9697 update_sg_lb_stats(env
, sg
, load_idx
, local_group
, sgs
,
9698 &overload
, &overutilized
,
9705 * In case the child domain prefers tasks go to siblings
9706 * first, lower the sg capacity so that we'll try
9707 * and move all the excess tasks away. We lower the capacity
9708 * of a group only if the local group has the capacity to fit
9709 * these excess tasks. The extra check prevents the case where
9710 * you always pull from the heaviest group when it is already
9711 * under-utilized (possible with a large weight task outweighs
9712 * the tasks on the system).
9714 if (prefer_sibling
&& sds
->local
&&
9715 group_has_capacity(env
, local
) &&
9716 (sgs
->sum_nr_running
> local
->sum_nr_running
+ 1)) {
9717 sgs
->group_no_capacity
= 1;
9718 sgs
->group_type
= group_classify(sg
, sgs
);
9721 if (update_sd_pick_busiest(env
, sds
, sg
, sgs
)) {
9723 sds
->busiest_stat
= *sgs
;
9727 /* Now, start updating sd_lb_stats */
9728 sds
->total_running
+= sgs
->sum_nr_running
;
9729 sds
->total_load
+= sgs
->group_load
;
9730 sds
->total_capacity
+= sgs
->group_capacity
;
9731 sds
->total_util
+= sgs
->group_util
;
9734 } while (sg
!= env
->sd
->groups
);
9736 if (env
->sd
->flags
& SD_NUMA
)
9737 env
->fbq_type
= fbq_classify_group(&sds
->busiest_stat
);
9739 env
->src_grp_nr_running
= sds
->busiest_stat
.sum_nr_running
;
9741 if (!lb_sd_parent(env
->sd
)) {
9742 /* update overload indicator if we are at root domain */
9743 if (READ_ONCE(env
->dst_rq
->rd
->overload
) != overload
)
9744 WRITE_ONCE(env
->dst_rq
->rd
->overload
, overload
);
9748 set_sd_overutilized(env
->sd
);
9750 clear_sd_overutilized(env
->sd
);
9753 * If there is a misfit task in one cpu in this sched_domain
9754 * it is likely that the imbalance cannot be sorted out among
9755 * the cpu's in this sched_domain. In this case set the
9756 * overutilized flag at the parent sched_domain.
9759 struct sched_domain
*sd
= env
->sd
->parent
;
9762 * In case of a misfit task, load balance at the parent
9763 * sched domain level will make sense only if the the cpus
9764 * have a different capacity. If cpus at a domain level have
9765 * the same capacity, the misfit task cannot be well
9766 * accomodated in any of the cpus and there in no point in
9767 * trying a load balance at this level
9770 if (sd
->flags
& SD_ASYM_CPUCAPACITY
) {
9771 set_sd_overutilized(sd
);
9779 * If the domain util is greater that domain capacity, load balancing
9780 * needs to be done at the next sched domain level as well.
9782 if (lb_sd_parent(env
->sd
) &&
9783 sds
->total_capacity
* 1024 < sds
->total_util
* capacity_margin
)
9784 set_sd_overutilized(env
->sd
->parent
);
9788 * check_asym_packing - Check to see if the group is packed into the
9791 * This is primarily intended to used at the sibling level. Some
9792 * cores like POWER7 prefer to use lower numbered SMT threads. In the
9793 * case of POWER7, it can move to lower SMT modes only when higher
9794 * threads are idle. When in lower SMT modes, the threads will
9795 * perform better since they share less core resources. Hence when we
9796 * have idle threads, we want them to be the higher ones.
9798 * This packing function is run on idle threads. It checks to see if
9799 * the busiest CPU in this domain (core in the P7 case) has a higher
9800 * CPU number than the packing function is being run on. Here we are
9801 * assuming lower CPU number will be equivalent to lower a SMT thread
9804 * Return: 1 when packing is required and a task should be moved to
9805 * this CPU. The amount of the imbalance is returned in env->imbalance.
9807 * @env: The load balancing environment.
9808 * @sds: Statistics of the sched_domain which is to be packed
9810 static int check_asym_packing(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9814 if (!(env
->sd
->flags
& SD_ASYM_PACKING
))
9817 if (env
->idle
== CPU_NOT_IDLE
)
9823 busiest_cpu
= sds
->busiest
->asym_prefer_cpu
;
9824 if (sched_asym_prefer(busiest_cpu
, env
->dst_cpu
))
9827 env
->imbalance
= DIV_ROUND_CLOSEST(
9828 sds
->busiest_stat
.avg_load
* sds
->busiest_stat
.group_capacity
,
9829 SCHED_CAPACITY_SCALE
);
9835 * fix_small_imbalance - Calculate the minor imbalance that exists
9836 * amongst the groups of a sched_domain, during
9838 * @env: The load balancing environment.
9839 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
9842 void fix_small_imbalance(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9844 unsigned long tmp
, capa_now
= 0, capa_move
= 0;
9845 unsigned int imbn
= 2;
9846 unsigned long scaled_busy_load_per_task
;
9847 struct sg_lb_stats
*local
, *busiest
;
9849 local
= &sds
->local_stat
;
9850 busiest
= &sds
->busiest_stat
;
9852 if (!local
->sum_nr_running
)
9853 local
->load_per_task
= cpu_avg_load_per_task(env
->dst_cpu
);
9854 else if (busiest
->load_per_task
> local
->load_per_task
)
9857 scaled_busy_load_per_task
=
9858 (busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) /
9859 busiest
->group_capacity
;
9861 if (busiest
->avg_load
+ scaled_busy_load_per_task
>=
9862 local
->avg_load
+ (scaled_busy_load_per_task
* imbn
)) {
9863 env
->imbalance
= busiest
->load_per_task
;
9868 * OK, we don't have enough imbalance to justify moving tasks,
9869 * however we may be able to increase total CPU capacity used by
9873 capa_now
+= busiest
->group_capacity
*
9874 min(busiest
->load_per_task
, busiest
->avg_load
);
9875 capa_now
+= local
->group_capacity
*
9876 min(local
->load_per_task
, local
->avg_load
);
9877 capa_now
/= SCHED_CAPACITY_SCALE
;
9879 /* Amount of load we'd subtract */
9880 if (busiest
->avg_load
> scaled_busy_load_per_task
) {
9881 capa_move
+= busiest
->group_capacity
*
9882 min(busiest
->load_per_task
,
9883 busiest
->avg_load
- scaled_busy_load_per_task
);
9886 /* Amount of load we'd add */
9887 if (busiest
->avg_load
* busiest
->group_capacity
<
9888 busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) {
9889 tmp
= (busiest
->avg_load
* busiest
->group_capacity
) /
9890 local
->group_capacity
;
9892 tmp
= (busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) /
9893 local
->group_capacity
;
9895 capa_move
+= local
->group_capacity
*
9896 min(local
->load_per_task
, local
->avg_load
+ tmp
);
9897 capa_move
/= SCHED_CAPACITY_SCALE
;
9899 /* Move if we gain throughput */
9900 if (capa_move
> capa_now
) {
9901 env
->imbalance
= busiest
->load_per_task
;
9905 /* We can't see throughput improvement with the load-based
9906 * method, but it is possible depending upon group size and
9907 * capacity range that there might still be an underutilized
9908 * cpu available in an asymmetric capacity system. Do one last
9909 * check just in case.
9911 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
9912 busiest
->group_type
== group_overloaded
&&
9913 busiest
->sum_nr_running
> busiest
->group_weight
&&
9914 local
->sum_nr_running
< local
->group_weight
&&
9915 local
->group_capacity
< busiest
->group_capacity
)
9916 env
->imbalance
= busiest
->load_per_task
;
9920 * calculate_imbalance - Calculate the amount of imbalance present within the
9921 * groups of a given sched_domain during load balance.
9922 * @env: load balance environment
9923 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
9925 static inline void calculate_imbalance(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9927 unsigned long max_pull
, load_above_capacity
= ~0UL;
9928 struct sg_lb_stats
*local
, *busiest
;
9930 local
= &sds
->local_stat
;
9931 busiest
= &sds
->busiest_stat
;
9933 if (busiest
->group_type
== group_imbalanced
) {
9935 * In the group_imb case we cannot rely on group-wide averages
9936 * to ensure cpu-load equilibrium, look at wider averages. XXX
9938 busiest
->load_per_task
=
9939 min(busiest
->load_per_task
, sds
->avg_load
);
9943 * Avg load of busiest sg can be less and avg load of local sg can
9944 * be greater than avg load across all sgs of sd because avg load
9945 * factors in sg capacity and sgs with smaller group_type are
9946 * skipped when updating the busiest sg:
9948 if (busiest
->group_type
!= group_misfit_task
&&
9949 (busiest
->avg_load
<= sds
->avg_load
||
9950 local
->avg_load
>= sds
->avg_load
)) {
9952 return fix_small_imbalance(env
, sds
);
9956 * If there aren't any idle cpus, avoid creating some.
9958 if (busiest
->group_type
== group_overloaded
&&
9959 local
->group_type
== group_overloaded
) {
9960 load_above_capacity
= busiest
->sum_nr_running
* SCHED_CAPACITY_SCALE
;
9961 if (load_above_capacity
> busiest
->group_capacity
) {
9962 load_above_capacity
-= busiest
->group_capacity
;
9963 load_above_capacity
*= scale_load_down(NICE_0_LOAD
);
9964 load_above_capacity
/= busiest
->group_capacity
;
9966 load_above_capacity
= ~0UL;
9970 * We're trying to get all the cpus to the average_load, so we don't
9971 * want to push ourselves above the average load, nor do we wish to
9972 * reduce the max loaded cpu below the average load. At the same time,
9973 * we also don't want to reduce the group load below the group
9974 * capacity. Thus we look for the minimum possible imbalance.
9976 max_pull
= min(busiest
->avg_load
- sds
->avg_load
, load_above_capacity
);
9978 /* How much load to actually move to equalise the imbalance */
9979 env
->imbalance
= min(
9980 max_pull
* busiest
->group_capacity
,
9981 (sds
->avg_load
- local
->avg_load
) * local
->group_capacity
9982 ) / SCHED_CAPACITY_SCALE
;
9984 /* Boost imbalance to allow misfit task to be balanced.
9985 * Always do this if we are doing a NEWLY_IDLE balance
9986 * on the assumption that any tasks we have must not be
9987 * long-running (and hence we cannot rely upon load).
9988 * However if we are not idle, we should assume the tasks
9989 * we have are longer running and not override load-based
9990 * calculations above unless we are sure that the local
9991 * group is underutilized.
9993 if (busiest
->group_type
== group_misfit_task
&&
9994 (env
->idle
== CPU_NEWLY_IDLE
||
9995 local
->sum_nr_running
< local
->group_weight
)) {
9996 env
->imbalance
= max_t(long, env
->imbalance
,
9997 busiest
->group_misfit_task_load
);
10001 * if *imbalance is less than the average load per runnable task
10002 * there is no guarantee that any tasks will be moved so we'll have
10003 * a think about bumping its value to force at least one task to be
10006 if (env
->imbalance
< busiest
->load_per_task
)
10007 return fix_small_imbalance(env
, sds
);
10010 /******* find_busiest_group() helpers end here *********************/
10013 * find_busiest_group - Returns the busiest group within the sched_domain
10014 * if there is an imbalance.
10016 * Also calculates the amount of weighted load which should be moved
10017 * to restore balance.
10019 * @env: The load balancing environment.
10021 * Return: - The busiest group if imbalance exists.
10023 static struct sched_group
*find_busiest_group(struct lb_env
*env
)
10025 struct sg_lb_stats
*local
, *busiest
;
10026 struct sd_lb_stats sds
;
10028 init_sd_lb_stats(&sds
);
10031 * Compute the various statistics relavent for load balancing at
10034 update_sd_lb_stats(env
, &sds
);
10036 if (energy_aware() && !sd_overutilized(env
->sd
))
10039 local
= &sds
.local_stat
;
10040 busiest
= &sds
.busiest_stat
;
10042 /* ASYM feature bypasses nice load balance check */
10043 if (check_asym_packing(env
, &sds
))
10044 return sds
.busiest
;
10046 /* There is no busy sibling group to pull tasks from */
10047 if (!sds
.busiest
|| busiest
->sum_nr_running
== 0)
10050 /* XXX broken for overlapping NUMA groups */
10051 sds
.avg_load
= (SCHED_CAPACITY_SCALE
* sds
.total_load
)
10052 / sds
.total_capacity
;
10055 * If the busiest group is imbalanced the below checks don't
10056 * work because they assume all things are equal, which typically
10057 * isn't true due to cpus_allowed constraints and the like.
10059 if (busiest
->group_type
== group_imbalanced
)
10060 goto force_balance
;
10063 * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
10064 * capacities from resulting in underutilization due to avg_load.
10066 if (env
->idle
!= CPU_NOT_IDLE
&& group_has_capacity(env
, local
) &&
10067 busiest
->group_no_capacity
)
10068 goto force_balance
;
10070 /* Misfit tasks should be dealt with regardless of the avg load */
10071 if (busiest
->group_type
== group_misfit_task
)
10072 goto force_balance
;
10075 * If the local group is busier than the selected busiest group
10076 * don't try and pull any tasks.
10078 if (local
->avg_load
>= busiest
->avg_load
)
10082 * Don't pull any tasks if this group is already above the domain
10085 if (local
->avg_load
>= sds
.avg_load
)
10088 if (env
->idle
== CPU_IDLE
) {
10090 * This cpu is idle. If the busiest group is not overloaded
10091 * and there is no imbalance between this and busiest group
10092 * wrt idle cpus, it is balanced. The imbalance becomes
10093 * significant if the diff is greater than 1 otherwise we
10094 * might end up to just move the imbalance on another group
10096 if ((busiest
->group_type
!= group_overloaded
) &&
10097 (local
->idle_cpus
<= (busiest
->idle_cpus
+ 1)))
10101 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
10102 * imbalance_pct to be conservative.
10104 if (100 * busiest
->avg_load
<=
10105 env
->sd
->imbalance_pct
* local
->avg_load
)
10110 /* Looks like there is an imbalance. Compute it */
10111 env
->src_grp_type
= busiest
->group_type
;
10112 calculate_imbalance(env
, &sds
);
10113 return sds
.busiest
;
10116 env
->imbalance
= 0;
10121 * find_busiest_queue - find the busiest runqueue among the cpus in group.
10123 static struct rq
*find_busiest_queue(struct lb_env
*env
,
10124 struct sched_group
*group
)
10126 struct rq
*busiest
= NULL
, *rq
;
10127 unsigned long busiest_load
= 0, busiest_capacity
= 1;
10130 for_each_cpu_and(i
, sched_group_span(group
), env
->cpus
) {
10131 unsigned long capacity
, wl
;
10135 rt
= fbq_classify_rq(rq
);
10138 * We classify groups/runqueues into three groups:
10139 * - regular: there are !numa tasks
10140 * - remote: there are numa tasks that run on the 'wrong' node
10141 * - all: there is no distinction
10143 * In order to avoid migrating ideally placed numa tasks,
10144 * ignore those when there's better options.
10146 * If we ignore the actual busiest queue to migrate another
10147 * task, the next balance pass can still reduce the busiest
10148 * queue by moving tasks around inside the node.
10150 * If we cannot move enough load due to this classification
10151 * the next pass will adjust the group classification and
10152 * allow migration of more tasks.
10154 * Both cases only affect the total convergence complexity.
10156 if (rt
> env
->fbq_type
)
10160 * For ASYM_CPUCAPACITY domains with misfit tasks we simply
10161 * seek the "biggest" misfit task.
10163 if (env
->src_grp_type
== group_misfit_task
) {
10164 if (rq
->misfit_task_load
> busiest_load
) {
10165 busiest_load
= rq
->misfit_task_load
;
10171 capacity
= capacity_of(i
);
10174 * For ASYM_CPUCAPACITY domains, don't pick a cpu that could
10175 * eventually lead to active_balancing high->low capacity.
10176 * Higher per-cpu capacity is considered better than balancing
10179 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
10180 capacity_of(env
->dst_cpu
) < capacity
&&
10181 rq
->nr_running
== 1)
10184 wl
= weighted_cpuload(rq
);
10187 * When comparing with imbalance, use weighted_cpuload()
10188 * which is not scaled with the cpu capacity.
10191 if (rq
->nr_running
== 1 && wl
> env
->imbalance
&&
10192 !check_cpu_capacity(rq
, env
->sd
))
10196 * For the load comparisons with the other cpu's, consider
10197 * the weighted_cpuload() scaled with the cpu capacity, so
10198 * that the load can be moved away from the cpu that is
10199 * potentially running at a lower capacity.
10201 * Thus we're looking for max(wl_i / capacity_i), crosswise
10202 * multiplication to rid ourselves of the division works out
10203 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
10204 * our previous maximum.
10206 if (wl
* busiest_capacity
> busiest_load
* capacity
) {
10208 busiest_capacity
= capacity
;
10217 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
10218 * so long as it is large enough.
10220 #define MAX_PINNED_INTERVAL 512
10222 static int need_active_balance(struct lb_env
*env
)
10224 struct sched_domain
*sd
= env
->sd
;
10226 if (env
->idle
== CPU_NEWLY_IDLE
) {
10229 * ASYM_PACKING needs to force migrate tasks from busy but
10230 * lower priority CPUs in order to pack all tasks in the
10231 * highest priority CPUs.
10233 if ((sd
->flags
& SD_ASYM_PACKING
) &&
10234 sched_asym_prefer(env
->dst_cpu
, env
->src_cpu
))
10239 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
10240 * It's worth migrating the task if the src_cpu's capacity is reduced
10241 * because of other sched_class or IRQs if more capacity stays
10242 * available on dst_cpu.
10244 if ((env
->idle
!= CPU_NOT_IDLE
) &&
10245 (env
->src_rq
->cfs
.h_nr_running
== 1)) {
10246 if ((check_cpu_capacity(env
->src_rq
, sd
)) &&
10247 (capacity_of(env
->src_cpu
)*sd
->imbalance_pct
< capacity_of(env
->dst_cpu
)*100))
10251 if ((capacity_of(env
->src_cpu
) < capacity_of(env
->dst_cpu
)) &&
10252 ((capacity_orig_of(env
->src_cpu
) < capacity_orig_of(env
->dst_cpu
))) &&
10253 env
->src_rq
->cfs
.h_nr_running
== 1 &&
10254 cpu_overutilized(env
->src_cpu
) &&
10255 !cpu_overutilized(env
->dst_cpu
)) {
10259 if (env
->src_grp_type
== group_misfit_task
)
10262 if (env
->src_grp_type
== group_overloaded
&&
10263 env
->src_rq
->misfit_task_load
)
10266 return unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2);
10269 static int active_load_balance_cpu_stop(void *data
);
10271 static int should_we_balance(struct lb_env
*env
)
10273 struct sched_group
*sg
= env
->sd
->groups
;
10274 int cpu
, balance_cpu
= -1;
10277 * Ensure the balancing environment is consistent; can happen
10278 * when the softirq triggers 'during' hotplug.
10280 if (!cpumask_test_cpu(env
->dst_cpu
, env
->cpus
))
10284 * In the newly idle case, we will allow all the cpu's
10285 * to do the newly idle load balance.
10287 if (env
->idle
== CPU_NEWLY_IDLE
)
10290 /* Try to find first idle cpu */
10291 for_each_cpu_and(cpu
, group_balance_mask(sg
), env
->cpus
) {
10292 if (!idle_cpu(cpu
))
10299 if (balance_cpu
== -1)
10300 balance_cpu
= group_balance_cpu(sg
);
10303 * First idle cpu or the first cpu(busiest) in this sched group
10304 * is eligible for doing load balancing at this and above domains.
10306 return balance_cpu
== env
->dst_cpu
;
10310 * Check this_cpu to ensure it is balanced within domain. Attempt to move
10311 * tasks if there is an imbalance.
10313 static int load_balance(int this_cpu
, struct rq
*this_rq
,
10314 struct sched_domain
*sd
, enum cpu_idle_type idle
,
10315 int *continue_balancing
)
10317 int ld_moved
, cur_ld_moved
, active_balance
= 0;
10318 struct sched_domain
*sd_parent
= lb_sd_parent(sd
) ? sd
->parent
: NULL
;
10319 struct sched_group
*group
;
10320 struct rq
*busiest
;
10321 struct rq_flags rf
;
10322 struct cpumask
*cpus
= this_cpu_cpumask_var_ptr(load_balance_mask
);
10324 struct lb_env env
= {
10326 .dst_cpu
= this_cpu
,
10328 .dst_grpmask
= sched_group_span(sd
->groups
),
10330 .loop_break
= sched_nr_migrate_break
,
10333 .tasks
= LIST_HEAD_INIT(env
.tasks
),
10336 cpumask_and(cpus
, sched_domain_span(sd
), cpu_active_mask
);
10338 schedstat_inc(sd
->lb_count
[idle
]);
10341 if (!should_we_balance(&env
)) {
10342 *continue_balancing
= 0;
10346 group
= find_busiest_group(&env
);
10348 schedstat_inc(sd
->lb_nobusyg
[idle
]);
10352 busiest
= find_busiest_queue(&env
, group
);
10354 schedstat_inc(sd
->lb_nobusyq
[idle
]);
10358 BUG_ON(busiest
== env
.dst_rq
);
10360 schedstat_add(sd
->lb_imbalance
[idle
], env
.imbalance
);
10362 env
.src_cpu
= busiest
->cpu
;
10363 env
.src_rq
= busiest
;
10366 if (busiest
->nr_running
> 1) {
10368 * Attempt to move tasks. If find_busiest_group has found
10369 * an imbalance but busiest->nr_running <= 1, the group is
10370 * still unbalanced. ld_moved simply stays zero, so it is
10371 * correctly treated as an imbalance.
10373 env
.flags
|= LBF_ALL_PINNED
;
10374 env
.loop_max
= min(sysctl_sched_nr_migrate
, busiest
->nr_running
);
10377 rq_lock_irqsave(busiest
, &rf
);
10378 update_rq_clock(busiest
);
10381 * cur_ld_moved - load moved in current iteration
10382 * ld_moved - cumulative load moved across iterations
10384 cur_ld_moved
= detach_tasks(&env
);
10387 * We've detached some tasks from busiest_rq. Every
10388 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
10389 * unlock busiest->lock, and we are able to be sure
10390 * that nobody can manipulate the tasks in parallel.
10391 * See task_rq_lock() family for the details.
10394 rq_unlock(busiest
, &rf
);
10396 if (cur_ld_moved
) {
10397 attach_tasks(&env
);
10398 ld_moved
+= cur_ld_moved
;
10401 local_irq_restore(rf
.flags
);
10403 if (env
.flags
& LBF_NEED_BREAK
) {
10404 env
.flags
&= ~LBF_NEED_BREAK
;
10409 * Revisit (affine) tasks on src_cpu that couldn't be moved to
10410 * us and move them to an alternate dst_cpu in our sched_group
10411 * where they can run. The upper limit on how many times we
10412 * iterate on same src_cpu is dependent on number of cpus in our
10415 * This changes load balance semantics a bit on who can move
10416 * load to a given_cpu. In addition to the given_cpu itself
10417 * (or a ilb_cpu acting on its behalf where given_cpu is
10418 * nohz-idle), we now have balance_cpu in a position to move
10419 * load to given_cpu. In rare situations, this may cause
10420 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
10421 * _independently_ and at _same_ time to move some load to
10422 * given_cpu) causing exceess load to be moved to given_cpu.
10423 * This however should not happen so much in practice and
10424 * moreover subsequent load balance cycles should correct the
10425 * excess load moved.
10427 if ((env
.flags
& LBF_DST_PINNED
) && env
.imbalance
> 0) {
10429 /* Prevent to re-select dst_cpu via env's cpus */
10430 cpumask_clear_cpu(env
.dst_cpu
, env
.cpus
);
10432 env
.dst_rq
= cpu_rq(env
.new_dst_cpu
);
10433 env
.dst_cpu
= env
.new_dst_cpu
;
10434 env
.flags
&= ~LBF_DST_PINNED
;
10436 env
.loop_break
= sched_nr_migrate_break
;
10439 * Go back to "more_balance" rather than "redo" since we
10440 * need to continue with same src_cpu.
10446 * We failed to reach balance because of affinity.
10449 int *group_imbalance
= &sd_parent
->groups
->sgc
->imbalance
;
10451 if ((env
.flags
& LBF_SOME_PINNED
) && env
.imbalance
> 0)
10452 *group_imbalance
= 1;
10455 /* All tasks on this runqueue were pinned by CPU affinity */
10456 if (unlikely(env
.flags
& LBF_ALL_PINNED
)) {
10457 cpumask_clear_cpu(cpu_of(busiest
), cpus
);
10459 * Attempting to continue load balancing at the current
10460 * sched_domain level only makes sense if there are
10461 * active CPUs remaining as possible busiest CPUs to
10462 * pull load from which are not contained within the
10463 * destination group that is receiving any migrated
10466 if (!cpumask_subset(cpus
, env
.dst_grpmask
)) {
10468 env
.loop_break
= sched_nr_migrate_break
;
10471 goto out_all_pinned
;
10476 schedstat_inc(sd
->lb_failed
[idle
]);
10478 * Increment the failure counter only on periodic balance.
10479 * We do not want newidle balance, which can be very
10480 * frequent, pollute the failure counter causing
10481 * excessive cache_hot migrations and active balances.
10483 if (idle
!= CPU_NEWLY_IDLE
)
10484 if (env
.src_grp_nr_running
> 1)
10485 sd
->nr_balance_failed
++;
10487 if (need_active_balance(&env
)) {
10488 unsigned long flags
;
10490 raw_spin_lock_irqsave(&busiest
->lock
, flags
);
10492 /* don't kick the active_load_balance_cpu_stop,
10493 * if the curr task on busiest cpu can't be
10494 * moved to this_cpu
10496 if (!cpumask_test_cpu(this_cpu
, &busiest
->curr
->cpus_allowed
)) {
10497 raw_spin_unlock_irqrestore(&busiest
->lock
,
10499 env
.flags
|= LBF_ALL_PINNED
;
10500 goto out_one_pinned
;
10504 * ->active_balance synchronizes accesses to
10505 * ->active_balance_work. Once set, it's cleared
10506 * only after active load balance is finished.
10508 if (!busiest
->active_balance
) {
10509 busiest
->active_balance
= 1;
10510 busiest
->push_cpu
= this_cpu
;
10511 active_balance
= 1;
10513 raw_spin_unlock_irqrestore(&busiest
->lock
, flags
);
10515 if (active_balance
) {
10516 stop_one_cpu_nowait(cpu_of(busiest
),
10517 active_load_balance_cpu_stop
, busiest
,
10518 &busiest
->active_balance_work
);
10521 /* We've kicked active balancing, force task migration. */
10522 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
10525 sd
->nr_balance_failed
= 0;
10527 if (likely(!active_balance
)) {
10528 /* We were unbalanced, so reset the balancing interval */
10529 sd
->balance_interval
= sd
->min_interval
;
10532 * If we've begun active balancing, start to back off. This
10533 * case may not be covered by the all_pinned logic if there
10534 * is only 1 task on the busy runqueue (because we don't call
10537 if (sd
->balance_interval
< sd
->max_interval
)
10538 sd
->balance_interval
*= 2;
10545 * We reach balance although we may have faced some affinity
10546 * constraints. Clear the imbalance flag if it was set.
10549 int *group_imbalance
= &sd_parent
->groups
->sgc
->imbalance
;
10551 if (*group_imbalance
)
10552 *group_imbalance
= 0;
10557 * We reach balance because all tasks are pinned at this level so
10558 * we can't migrate them. Let the imbalance flag set so parent level
10559 * can try to migrate them.
10561 schedstat_inc(sd
->lb_balanced
[idle
]);
10563 sd
->nr_balance_failed
= 0;
10566 /* tune up the balancing interval */
10567 if (((env
.flags
& LBF_ALL_PINNED
) &&
10568 sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
10569 (sd
->balance_interval
< sd
->max_interval
))
10570 sd
->balance_interval
*= 2;
10577 static inline unsigned long
10578 get_sd_balance_interval(struct sched_domain
*sd
, int cpu_busy
)
10580 unsigned long interval
= sd
->balance_interval
;
10584 interval
*= sd
->busy_factor
;
10586 /* scale ms to jiffies */
10587 interval
= msecs_to_jiffies(interval
);
10588 interval
= clamp(interval
, 1UL, max_load_balance_interval
);
10591 * check if sched domain is marked as overutilized
10592 * we ought to only do this on systems which have SD_ASYMCAPACITY
10593 * but we want to do it for all sched domains in those systems
10594 * So for now, just check if overutilized as a proxy.
10597 * If we are overutilized and we have a misfit task, then
10598 * we want to balance as soon as practically possible, so
10599 * we return an interval of zero.
10601 if (energy_aware() && sd_overutilized(sd
)) {
10602 /* we know the root is overutilized, let's check for a misfit task */
10603 for_each_cpu(cpu
, sched_domain_span(sd
)) {
10604 if (cpu_rq(cpu
)->misfit_task_load
)
10612 update_next_balance(struct sched_domain
*sd
, unsigned long *next_balance
)
10614 unsigned long interval
, next
;
10616 /* used by idle balance, so cpu_busy = 0 */
10617 interval
= get_sd_balance_interval(sd
, 0);
10618 next
= sd
->last_balance
+ interval
;
10620 if (time_after(*next_balance
, next
))
10621 *next_balance
= next
;
10625 * idle_balance is called by schedule() if this_cpu is about to become
10626 * idle. Attempts to pull tasks from other CPUs.
10628 static int idle_balance(struct rq
*this_rq
, struct rq_flags
*rf
)
10630 unsigned long next_balance
= jiffies
+ HZ
;
10631 int this_cpu
= this_rq
->cpu
;
10632 struct sched_domain
*sd
;
10633 int pulled_task
= 0;
10637 * We must set idle_stamp _before_ calling idle_balance(), such that we
10638 * measure the duration of idle_balance() as idle time.
10640 this_rq
->idle_stamp
= rq_clock(this_rq
);
10643 * Do not pull tasks towards !active CPUs...
10645 if (!cpu_active(this_cpu
))
10649 * This is OK, because current is on_cpu, which avoids it being picked
10650 * for load-balance and preemption/IRQs are still disabled avoiding
10651 * further scheduler activity on it and we're being very careful to
10652 * re-start the picking loop.
10654 rq_unpin_lock(this_rq
, rf
);
10656 if (this_rq
->avg_idle
< sysctl_sched_migration_cost
||
10657 !READ_ONCE(this_rq
->rd
->overload
)) {
10659 sd
= rcu_dereference_check_sched_domain(this_rq
->sd
);
10661 update_next_balance(sd
, &next_balance
);
10667 raw_spin_unlock(&this_rq
->lock
);
10669 update_blocked_averages(this_cpu
);
10671 for_each_domain(this_cpu
, sd
) {
10672 int continue_balancing
= 1;
10673 u64 t0
, domain_cost
;
10675 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
10676 if (time_after_eq(jiffies
,
10677 sd
->groups
->sgc
->next_update
))
10678 update_group_capacity(sd
, this_cpu
);
10682 if (this_rq
->avg_idle
< curr_cost
+ sd
->max_newidle_lb_cost
) {
10683 update_next_balance(sd
, &next_balance
);
10687 if (sd
->flags
& SD_BALANCE_NEWIDLE
) {
10688 t0
= sched_clock_cpu(this_cpu
);
10690 pulled_task
= load_balance(this_cpu
, this_rq
,
10691 sd
, CPU_NEWLY_IDLE
,
10692 &continue_balancing
);
10694 domain_cost
= sched_clock_cpu(this_cpu
) - t0
;
10695 if (domain_cost
> sd
->max_newidle_lb_cost
)
10696 sd
->max_newidle_lb_cost
= domain_cost
;
10698 curr_cost
+= domain_cost
;
10701 update_next_balance(sd
, &next_balance
);
10704 * Stop searching for tasks to pull if there are
10705 * now runnable tasks on this rq.
10707 if (pulled_task
|| this_rq
->nr_running
> 0)
10712 raw_spin_lock(&this_rq
->lock
);
10714 if (curr_cost
> this_rq
->max_idle_balance_cost
)
10715 this_rq
->max_idle_balance_cost
= curr_cost
;
10718 * While browsing the domains, we released the rq lock, a task could
10719 * have been enqueued in the meantime. Since we're not going idle,
10720 * pretend we pulled a task.
10722 if (this_rq
->cfs
.h_nr_running
&& !pulled_task
)
10726 /* Move the next balance forward */
10727 if (time_after(this_rq
->next_balance
, next_balance
))
10728 this_rq
->next_balance
= next_balance
;
10730 /* Is there a task of a high priority class? */
10731 if (this_rq
->nr_running
!= this_rq
->cfs
.h_nr_running
)
10735 this_rq
->idle_stamp
= 0;
10737 rq_repin_lock(this_rq
, rf
);
10739 return pulled_task
;
10743 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
10744 * running tasks off the busiest CPU onto idle CPUs. It requires at
10745 * least 1 task to be running on each physical CPU where possible, and
10746 * avoids physical / logical imbalances.
10748 static int active_load_balance_cpu_stop(void *data
)
10750 struct rq
*busiest_rq
= data
;
10751 int busiest_cpu
= cpu_of(busiest_rq
);
10752 int target_cpu
= busiest_rq
->push_cpu
;
10753 struct rq
*target_rq
= cpu_rq(target_cpu
);
10754 struct sched_domain
*sd
;
10755 struct task_struct
*p
= NULL
;
10756 struct rq_flags rf
;
10758 rq_lock_irq(busiest_rq
, &rf
);
10760 * Between queueing the stop-work and running it is a hole in which
10761 * CPUs can become inactive. We should not move tasks from or to
10764 if (!cpu_active(busiest_cpu
) || !cpu_active(target_cpu
))
10767 /* make sure the requested cpu hasn't gone down in the meantime */
10768 if (unlikely(busiest_cpu
!= smp_processor_id() ||
10769 !busiest_rq
->active_balance
))
10772 /* Is there any task to move? */
10773 if (busiest_rq
->nr_running
<= 1)
10777 * This condition is "impossible", if it occurs
10778 * we need to fix it. Originally reported by
10779 * Bjorn Helgaas on a 128-cpu setup.
10781 BUG_ON(busiest_rq
== target_rq
);
10783 /* Search for an sd spanning us and the target CPU. */
10785 for_each_domain(target_cpu
, sd
) {
10786 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
10787 cpumask_test_cpu(busiest_cpu
, sched_domain_span(sd
)))
10792 struct lb_env env
= {
10794 .dst_cpu
= target_cpu
,
10795 .dst_rq
= target_rq
,
10796 .src_cpu
= busiest_rq
->cpu
,
10797 .src_rq
= busiest_rq
,
10800 * can_migrate_task() doesn't need to compute new_dst_cpu
10801 * for active balancing. Since we have CPU_IDLE, but no
10802 * @dst_grpmask we need to make that test go away with lying
10803 * about DST_PINNED.
10805 .flags
= LBF_DST_PINNED
,
10808 schedstat_inc(sd
->alb_count
);
10809 update_rq_clock(busiest_rq
);
10811 p
= detach_one_task(&env
);
10813 schedstat_inc(sd
->alb_pushed
);
10814 /* Active balancing done, reset the failure counter. */
10815 sd
->nr_balance_failed
= 0;
10817 schedstat_inc(sd
->alb_failed
);
10822 busiest_rq
->active_balance
= 0;
10823 rq_unlock(busiest_rq
, &rf
);
10826 attach_one_task(target_rq
, p
);
10828 local_irq_enable();
10833 static inline int on_null_domain(struct rq
*rq
)
10835 return unlikely(!rcu_dereference_sched(rq
->sd
));
10838 #ifdef CONFIG_NO_HZ_COMMON
10840 * idle load balancing details
10841 * - When one of the busy CPUs notice that there may be an idle rebalancing
10842 * needed, they will kick the idle load balancer, which then does idle
10843 * load balancing for all the idle CPUs.
10846 static inline int find_new_ilb(void)
10848 int ilb
= cpumask_first(nohz
.idle_cpus_mask
);
10850 if (ilb
< nr_cpu_ids
&& idle_cpu(ilb
))
10857 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
10858 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
10859 * CPU (if there is one).
10861 static void nohz_balancer_kick(bool only_update
)
10865 nohz
.next_balance
++;
10867 ilb_cpu
= find_new_ilb();
10869 if (ilb_cpu
>= nr_cpu_ids
)
10872 if (test_and_set_bit(NOHZ_BALANCE_KICK
, nohz_flags(ilb_cpu
)))
10876 set_bit(NOHZ_STATS_KICK
, nohz_flags(ilb_cpu
));
10879 * Use smp_send_reschedule() instead of resched_cpu().
10880 * This way we generate a sched IPI on the target cpu which
10881 * is idle. And the softirq performing nohz idle load balance
10882 * will be run before returning from the IPI.
10884 smp_send_reschedule(ilb_cpu
);
10888 void nohz_balance_exit_idle(unsigned int cpu
)
10890 if (unlikely(test_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
)))) {
10892 * Completely isolated CPUs don't ever set, so we must test.
10894 if (likely(cpumask_test_cpu(cpu
, nohz
.idle_cpus_mask
))) {
10895 cpumask_clear_cpu(cpu
, nohz
.idle_cpus_mask
);
10896 atomic_dec(&nohz
.nr_cpus
);
10898 clear_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
));
10902 static inline void set_cpu_sd_state_busy(void)
10904 struct sched_domain
*sd
;
10905 int cpu
= smp_processor_id();
10908 sd
= rcu_dereference(per_cpu(sd_llc
, cpu
));
10910 if (!sd
|| !sd
->nohz_idle
)
10914 atomic_inc(&sd
->shared
->nr_busy_cpus
);
10919 void set_cpu_sd_state_idle(void)
10921 struct sched_domain
*sd
;
10922 int cpu
= smp_processor_id();
10925 sd
= rcu_dereference(per_cpu(sd_llc
, cpu
));
10927 if (!sd
|| sd
->nohz_idle
)
10931 atomic_dec(&sd
->shared
->nr_busy_cpus
);
10937 * This routine will record that the cpu is going idle with tick stopped.
10938 * This info will be used in performing idle load balancing in the future.
10940 void nohz_balance_enter_idle(int cpu
)
10943 * If this cpu is going down, then nothing needs to be done.
10945 if (!cpu_active(cpu
))
10948 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
10949 if (!is_housekeeping_cpu(cpu
))
10952 if (test_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
)))
10956 * If we're a completely isolated CPU, we don't play.
10958 if (on_null_domain(cpu_rq(cpu
)))
10961 cpumask_set_cpu(cpu
, nohz
.idle_cpus_mask
);
10962 atomic_inc(&nohz
.nr_cpus
);
10963 set_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
));
10966 static inline void nohz_balancer_kick(bool only_update
) {}
10969 static DEFINE_SPINLOCK(balancing
);
10972 * Scale the max load_balance interval with the number of CPUs in the system.
10973 * This trades load-balance latency on larger machines for less cross talk.
10975 void update_max_interval(void)
10977 max_load_balance_interval
= HZ
*num_online_cpus()/10;
10981 * It checks each scheduling domain to see if it is due to be balanced,
10982 * and initiates a balancing operation if so.
10984 * Balancing parameters are set up in init_sched_domains.
10986 static void rebalance_domains(struct rq
*rq
, enum cpu_idle_type idle
)
10988 int continue_balancing
= 1;
10990 unsigned long interval
;
10991 struct sched_domain
*sd
;
10992 /* Earliest time when we have to do rebalance again */
10993 unsigned long next_balance
= jiffies
+ 60*HZ
;
10994 int update_next_balance
= 0;
10995 int need_serialize
, need_decay
= 0;
10999 for_each_domain(cpu
, sd
) {
11001 * Decay the newidle max times here because this is a regular
11002 * visit to all the domains. Decay ~1% per second.
11004 if (time_after(jiffies
, sd
->next_decay_max_lb_cost
)) {
11005 sd
->max_newidle_lb_cost
=
11006 (sd
->max_newidle_lb_cost
* 253) / 256;
11007 sd
->next_decay_max_lb_cost
= jiffies
+ HZ
;
11010 max_cost
+= sd
->max_newidle_lb_cost
;
11012 if (energy_aware() && !sd_overutilized(sd
))
11015 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
11016 if (time_after_eq(jiffies
,
11017 sd
->groups
->sgc
->next_update
))
11018 update_group_capacity(sd
, cpu
);
11023 * Stop the load balance at this level. There is another
11024 * CPU in our sched group which is doing load balancing more
11027 if (!continue_balancing
) {
11033 interval
= get_sd_balance_interval(sd
, idle
!= CPU_IDLE
);
11035 need_serialize
= sd
->flags
& SD_SERIALIZE
;
11036 if (need_serialize
) {
11037 if (!spin_trylock(&balancing
))
11041 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
11042 if (load_balance(cpu
, rq
, sd
, idle
, &continue_balancing
)) {
11044 * The LBF_DST_PINNED logic could have changed
11045 * env->dst_cpu, so we can't know our idle
11046 * state even if we migrated tasks. Update it.
11048 idle
= idle_cpu(cpu
) ? CPU_IDLE
: CPU_NOT_IDLE
;
11050 sd
->last_balance
= jiffies
;
11051 interval
= get_sd_balance_interval(sd
, idle
!= CPU_IDLE
);
11053 if (need_serialize
)
11054 spin_unlock(&balancing
);
11056 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
11057 next_balance
= sd
->last_balance
+ interval
;
11058 update_next_balance
= 1;
11063 * Ensure the rq-wide value also decays but keep it at a
11064 * reasonable floor to avoid funnies with rq->avg_idle.
11066 rq
->max_idle_balance_cost
=
11067 max((u64
)sysctl_sched_migration_cost
, max_cost
);
11072 * next_balance will be updated only when there is a need.
11073 * When the cpu is attached to null domain for ex, it will not be
11076 if (likely(update_next_balance
)) {
11077 rq
->next_balance
= next_balance
;
11079 #ifdef CONFIG_NO_HZ_COMMON
11081 * If this CPU has been elected to perform the nohz idle
11082 * balance. Other idle CPUs have already rebalanced with
11083 * nohz_idle_balance() and nohz.next_balance has been
11084 * updated accordingly. This CPU is now running the idle load
11085 * balance for itself and we need to update the
11086 * nohz.next_balance accordingly.
11088 if ((idle
== CPU_IDLE
) && time_after(nohz
.next_balance
, rq
->next_balance
))
11089 nohz
.next_balance
= rq
->next_balance
;
11094 #ifdef CONFIG_NO_HZ_COMMON
11096 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
11097 * rebalancing for all the cpus for whom scheduler ticks are stopped.
11099 static void nohz_idle_balance(struct rq
*this_rq
, enum cpu_idle_type idle
)
11101 int this_cpu
= this_rq
->cpu
;
11103 struct sched_domain
*sd
;
11105 /* Earliest time when we have to do rebalance again */
11106 unsigned long next_balance
= jiffies
+ 60*HZ
;
11107 int update_next_balance
= 0;
11109 if (idle
!= CPU_IDLE
||
11110 !test_bit(NOHZ_BALANCE_KICK
, nohz_flags(this_cpu
)))
11114 * This cpu is going to update the blocked load of idle CPUs either
11115 * before doing a rebalancing or just to keep metrics up to date. we
11116 * can safely update the next update timestamp
11119 sd
= rcu_dereference(this_rq
->sd
);
11121 * Check whether there is a sched_domain available for this cpu.
11122 * The last other cpu can have been unplugged since the ILB has been
11123 * triggered and the sched_domain can now be null. The idle balance
11124 * sequence will quickly be aborted as there is no more idle CPUs
11127 nohz
.next_update
= jiffies
+ msecs_to_jiffies(LOAD_AVG_PERIOD
);
11130 for_each_cpu(balance_cpu
, nohz
.idle_cpus_mask
) {
11131 if (balance_cpu
== this_cpu
|| !idle_cpu(balance_cpu
))
11135 * If this cpu gets work to do, stop the load balancing
11136 * work being done for other cpus. Next load
11137 * balancing owner will pick it up.
11139 if (need_resched())
11142 rq
= cpu_rq(balance_cpu
);
11145 * If time for next balance is due,
11148 if (time_after_eq(jiffies
, rq
->next_balance
)) {
11149 struct rq_flags rf
;
11151 rq_lock_irq(rq
, &rf
);
11152 update_rq_clock(rq
);
11153 cpu_load_update_idle(rq
);
11154 rq_unlock_irq(rq
, &rf
);
11156 update_blocked_averages(balance_cpu
);
11158 * This idle load balance softirq may have been
11159 * triggered only to update the blocked load and shares
11160 * of idle CPUs (which we have just done for
11161 * balance_cpu). In that case skip the actual balance.
11163 if (!test_bit(NOHZ_STATS_KICK
, nohz_flags(this_cpu
)))
11164 rebalance_domains(rq
, idle
);
11167 if (time_after(next_balance
, rq
->next_balance
)) {
11168 next_balance
= rq
->next_balance
;
11169 update_next_balance
= 1;
11174 * next_balance will be updated only when there is a need.
11175 * When the CPU is attached to null domain for ex, it will not be
11178 if (likely(update_next_balance
))
11179 nohz
.next_balance
= next_balance
;
11181 clear_bit(NOHZ_BALANCE_KICK
, nohz_flags(this_cpu
));
11185 * Current heuristic for kicking the idle load balancer in the presence
11186 * of an idle cpu in the system.
11187 * - This rq has more than one task.
11188 * - This rq has at least one CFS task and the capacity of the CPU is
11189 * significantly reduced because of RT tasks or IRQs.
11190 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
11191 * multiple busy cpu.
11192 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
11193 * domain span are idle.
11195 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
)
11197 unsigned long now
= jiffies
;
11198 struct sched_domain_shared
*sds
;
11199 struct sched_domain
*sd
;
11200 int nr_busy
, i
, cpu
= rq
->cpu
;
11203 if (unlikely(rq
->idle_balance
) && !only_update
)
11207 * We may be recently in ticked or tickless idle mode. At the first
11208 * busy tick after returning from idle, we will update the busy stats.
11210 set_cpu_sd_state_busy();
11211 nohz_balance_exit_idle(cpu
);
11214 * None are in tickless mode and hence no need for NOHZ idle load
11217 if (likely(!atomic_read(&nohz
.nr_cpus
)))
11221 if (time_before(now
, nohz
.next_update
))
11227 if (time_before(now
, nohz
.next_balance
))
11230 if (rq
->nr_running
>= 2 &&
11231 (!energy_aware() || cpu_overutilized(cpu
)))
11234 /* Do idle load balance if there have misfit task */
11235 if (energy_aware())
11236 return rq
->misfit_task_load
;
11239 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
11240 if (sds
&& !energy_aware()) {
11242 * XXX: write a coherent comment on why we do this.
11243 * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
11245 nr_busy
= atomic_read(&sds
->nr_busy_cpus
);
11253 sd
= rcu_dereference(rq
->sd
);
11255 if ((rq
->cfs
.h_nr_running
>= 1) &&
11256 check_cpu_capacity(rq
, sd
)) {
11262 sd
= rcu_dereference(per_cpu(sd_asym
, cpu
));
11264 for_each_cpu(i
, sched_domain_span(sd
)) {
11266 !cpumask_test_cpu(i
, nohz
.idle_cpus_mask
))
11269 if (sched_asym_prefer(i
, cpu
)) {
11280 static void nohz_idle_balance(struct rq
*this_rq
, enum cpu_idle_type idle
) { }
11281 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
) { return false; }
11285 * run_rebalance_domains is triggered when needed from the scheduler tick.
11286 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
11288 static __latent_entropy
void run_rebalance_domains(struct softirq_action
*h
)
11290 struct rq
*this_rq
= this_rq();
11291 enum cpu_idle_type idle
= this_rq
->idle_balance
?
11292 CPU_IDLE
: CPU_NOT_IDLE
;
11295 * If this cpu has a pending nohz_balance_kick, then do the
11296 * balancing on behalf of the other idle cpus whose ticks are
11297 * stopped. Do nohz_idle_balance *before* rebalance_domains to
11298 * give the idle cpus a chance to load balance. Else we may
11299 * load balance only within the local sched_domain hierarchy
11300 * and abort nohz_idle_balance altogether if we pull some load.
11302 nohz_idle_balance(this_rq
, idle
);
11303 update_blocked_averages(this_rq
->cpu
);
11304 #ifdef CONFIG_NO_HZ_COMMON
11305 if (!test_bit(NOHZ_STATS_KICK
, nohz_flags(this_rq
->cpu
)))
11306 rebalance_domains(this_rq
, idle
);
11307 clear_bit(NOHZ_STATS_KICK
, nohz_flags(this_rq
->cpu
));
11309 rebalance_domains(this_rq
, idle
);
11314 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
11316 void trigger_load_balance(struct rq
*rq
)
11318 /* Don't need to rebalance while attached to NULL domain */
11319 if (unlikely(on_null_domain(rq
)))
11322 if (time_after_eq(jiffies
, rq
->next_balance
))
11323 raise_softirq(SCHED_SOFTIRQ
);
11324 #ifdef CONFIG_NO_HZ_COMMON
11325 if (nohz_kick_needed(rq
, false))
11326 nohz_balancer_kick(false);
11330 static void rq_online_fair(struct rq
*rq
)
11334 update_runtime_enabled(rq
);
11337 static void rq_offline_fair(struct rq
*rq
)
11341 /* Ensure any throttled groups are reachable by pick_next_task */
11342 unthrottle_offline_cfs_rqs(rq
);
11345 #endif /* CONFIG_SMP */
11348 * scheduler tick hitting a task of our scheduling class:
11350 static void task_tick_fair(struct rq
*rq
, struct task_struct
*curr
, int queued
)
11352 struct cfs_rq
*cfs_rq
;
11353 struct sched_entity
*se
= &curr
->se
;
11355 for_each_sched_entity(se
) {
11356 cfs_rq
= cfs_rq_of(se
);
11357 entity_tick(cfs_rq
, se
, queued
);
11360 if (static_branch_unlikely(&sched_numa_balancing
))
11361 task_tick_numa(rq
, curr
);
11363 update_misfit_status(curr
, rq
);
11365 update_overutilized_status(rq
);
11369 * called on fork with the child task as argument from the parent's context
11370 * - child not yet on the tasklist
11371 * - preemption disabled
11373 static void task_fork_fair(struct task_struct
*p
)
11375 struct cfs_rq
*cfs_rq
;
11376 struct sched_entity
*se
= &p
->se
, *curr
;
11377 struct rq
*rq
= this_rq();
11378 struct rq_flags rf
;
11381 update_rq_clock(rq
);
11383 cfs_rq
= task_cfs_rq(current
);
11384 curr
= cfs_rq
->curr
;
11386 update_curr(cfs_rq
);
11387 se
->vruntime
= curr
->vruntime
;
11389 place_entity(cfs_rq
, se
, 1);
11391 if (sysctl_sched_child_runs_first
&& curr
&& entity_before(curr
, se
)) {
11393 * Upon rescheduling, sched_class::put_prev_task() will place
11394 * 'current' within the tree based on its new key value.
11396 swap(curr
->vruntime
, se
->vruntime
);
11400 se
->vruntime
-= cfs_rq
->min_vruntime
;
11401 rq_unlock(rq
, &rf
);
11405 * Priority of the task has changed. Check to see if we preempt
11406 * the current task.
11409 prio_changed_fair(struct rq
*rq
, struct task_struct
*p
, int oldprio
)
11411 if (!task_on_rq_queued(p
))
11415 * Reschedule if we are currently running on this runqueue and
11416 * our priority decreased, or if we are not currently running on
11417 * this runqueue and our priority is higher than the current's
11419 if (rq
->curr
== p
) {
11420 if (p
->prio
> oldprio
)
11423 check_preempt_curr(rq
, p
, 0);
11426 static inline bool vruntime_normalized(struct task_struct
*p
)
11428 struct sched_entity
*se
= &p
->se
;
11431 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
11432 * the dequeue_entity(.flags=0) will already have normalized the
11439 * When !on_rq, vruntime of the task has usually NOT been normalized.
11440 * But there are some cases where it has already been normalized:
11442 * - A forked child which is waiting for being woken up by
11443 * wake_up_new_task().
11444 * - A task which has been woken up by try_to_wake_up() and
11445 * waiting for actually being woken up by sched_ttwu_pending().
11447 if (!se
->sum_exec_runtime
||
11448 (p
->state
== TASK_WAKING
&& p
->sched_remote_wakeup
))
11454 #ifdef CONFIG_FAIR_GROUP_SCHED
11456 * Propagate the changes of the sched_entity across the tg tree to make it
11457 * visible to the root
11459 static void propagate_entity_cfs_rq(struct sched_entity
*se
)
11461 struct cfs_rq
*cfs_rq
;
11463 /* Start to propagate at parent */
11466 for_each_sched_entity(se
) {
11467 cfs_rq
= cfs_rq_of(se
);
11469 if (cfs_rq_throttled(cfs_rq
))
11472 update_load_avg(se
, UPDATE_TG
);
11476 static void propagate_entity_cfs_rq(struct sched_entity
*se
) { }
11479 static void detach_entity_cfs_rq(struct sched_entity
*se
)
11481 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11483 /* Catch up with the cfs_rq and remove our load when we leave */
11484 update_load_avg(se
, 0);
11485 detach_entity_load_avg(cfs_rq
, se
);
11486 update_tg_load_avg(cfs_rq
, false);
11487 propagate_entity_cfs_rq(se
);
11490 static void attach_entity_cfs_rq(struct sched_entity
*se
)
11492 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11494 #ifdef CONFIG_FAIR_GROUP_SCHED
11496 * Since the real-depth could have been changed (only FAIR
11497 * class maintain depth value), reset depth properly.
11499 se
->depth
= se
->parent
? se
->parent
->depth
+ 1 : 0;
11502 /* Synchronize entity with its cfs_rq */
11503 update_load_avg(se
, sched_feat(ATTACH_AGE_LOAD
) ? 0 : SKIP_AGE_LOAD
);
11504 attach_entity_load_avg(cfs_rq
, se
);
11505 update_tg_load_avg(cfs_rq
, false);
11506 propagate_entity_cfs_rq(se
);
11509 static void detach_task_cfs_rq(struct task_struct
*p
)
11511 struct sched_entity
*se
= &p
->se
;
11512 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11514 if (!vruntime_normalized(p
)) {
11516 * Fix up our vruntime so that the current sleep doesn't
11517 * cause 'unlimited' sleep bonus.
11519 place_entity(cfs_rq
, se
, 0);
11520 se
->vruntime
-= cfs_rq
->min_vruntime
;
11523 detach_entity_cfs_rq(se
);
11526 static void attach_task_cfs_rq(struct task_struct
*p
)
11528 struct sched_entity
*se
= &p
->se
;
11529 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11531 attach_entity_cfs_rq(se
);
11533 if (!vruntime_normalized(p
))
11534 se
->vruntime
+= cfs_rq
->min_vruntime
;
11537 static void switched_from_fair(struct rq
*rq
, struct task_struct
*p
)
11539 detach_task_cfs_rq(p
);
11542 static void switched_to_fair(struct rq
*rq
, struct task_struct
*p
)
11544 attach_task_cfs_rq(p
);
11546 if (task_on_rq_queued(p
)) {
11548 * We were most likely switched from sched_rt, so
11549 * kick off the schedule if running, otherwise just see
11550 * if we can still preempt the current task.
11555 check_preempt_curr(rq
, p
, 0);
11559 /* Account for a task changing its policy or group.
11561 * This routine is mostly called to set cfs_rq->curr field when a task
11562 * migrates between groups/classes.
11564 static void set_curr_task_fair(struct rq
*rq
)
11566 struct sched_entity
*se
= &rq
->curr
->se
;
11568 for_each_sched_entity(se
) {
11569 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11571 set_next_entity(cfs_rq
, se
);
11572 /* ensure bandwidth has been allocated on our new cfs_rq */
11573 account_cfs_rq_runtime(cfs_rq
, 0);
11577 void init_cfs_rq(struct cfs_rq
*cfs_rq
)
11579 cfs_rq
->tasks_timeline
= RB_ROOT_CACHED
;
11580 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
11581 #ifndef CONFIG_64BIT
11582 cfs_rq
->min_vruntime_copy
= cfs_rq
->min_vruntime
;
11585 #ifdef CONFIG_FAIR_GROUP_SCHED
11586 cfs_rq
->propagate_avg
= 0;
11588 atomic_long_set(&cfs_rq
->removed_load_avg
, 0);
11589 atomic_long_set(&cfs_rq
->removed_util_avg
, 0);
11593 #ifdef CONFIG_FAIR_GROUP_SCHED
11594 static void task_set_group_fair(struct task_struct
*p
)
11596 struct sched_entity
*se
= &p
->se
;
11598 set_task_rq(p
, task_cpu(p
));
11599 se
->depth
= se
->parent
? se
->parent
->depth
+ 1 : 0;
11602 static void task_move_group_fair(struct task_struct
*p
)
11604 detach_task_cfs_rq(p
);
11605 set_task_rq(p
, task_cpu(p
));
11608 /* Tell se's cfs_rq has been changed -- migrated */
11609 p
->se
.avg
.last_update_time
= 0;
11611 attach_task_cfs_rq(p
);
11614 static void task_change_group_fair(struct task_struct
*p
, int type
)
11617 case TASK_SET_GROUP
:
11618 task_set_group_fair(p
);
11621 case TASK_MOVE_GROUP
:
11622 task_move_group_fair(p
);
11627 void free_fair_sched_group(struct task_group
*tg
)
11631 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg
));
11633 for_each_possible_cpu(i
) {
11635 kfree(tg
->cfs_rq
[i
]);
11644 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
11646 struct sched_entity
*se
;
11647 struct cfs_rq
*cfs_rq
;
11650 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
11653 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
11657 tg
->shares
= NICE_0_LOAD
;
11659 init_cfs_bandwidth(tg_cfs_bandwidth(tg
));
11661 for_each_possible_cpu(i
) {
11662 cfs_rq
= kzalloc_node(sizeof(struct cfs_rq
),
11663 GFP_KERNEL
, cpu_to_node(i
));
11667 se
= kzalloc_node(sizeof(struct sched_entity
),
11668 GFP_KERNEL
, cpu_to_node(i
));
11672 init_cfs_rq(cfs_rq
);
11673 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, parent
->se
[i
]);
11674 init_entity_runnable_average(se
);
11685 void online_fair_sched_group(struct task_group
*tg
)
11687 struct sched_entity
*se
;
11691 for_each_possible_cpu(i
) {
11695 raw_spin_lock_irq(&rq
->lock
);
11696 update_rq_clock(rq
);
11697 attach_entity_cfs_rq(se
);
11698 sync_throttle(tg
, i
);
11699 raw_spin_unlock_irq(&rq
->lock
);
11703 void unregister_fair_sched_group(struct task_group
*tg
)
11705 unsigned long flags
;
11709 for_each_possible_cpu(cpu
) {
11711 remove_entity_load_avg(tg
->se
[cpu
]);
11714 * Only empty task groups can be destroyed; so we can speculatively
11715 * check on_list without danger of it being re-added.
11717 if (!tg
->cfs_rq
[cpu
]->on_list
)
11722 raw_spin_lock_irqsave(&rq
->lock
, flags
);
11723 list_del_leaf_cfs_rq(tg
->cfs_rq
[cpu
]);
11724 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
11728 void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
11729 struct sched_entity
*se
, int cpu
,
11730 struct sched_entity
*parent
)
11732 struct rq
*rq
= cpu_rq(cpu
);
11736 init_cfs_rq_runtime(cfs_rq
);
11738 tg
->cfs_rq
[cpu
] = cfs_rq
;
11741 /* se could be NULL for root_task_group */
11746 se
->cfs_rq
= &rq
->cfs
;
11749 se
->cfs_rq
= parent
->my_q
;
11750 se
->depth
= parent
->depth
+ 1;
11754 /* guarantee group entities always have weight */
11755 update_load_set(&se
->load
, NICE_0_LOAD
);
11756 se
->parent
= parent
;
11759 static DEFINE_MUTEX(shares_mutex
);
11761 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
11766 * We can't change the weight of the root cgroup.
11771 shares
= clamp(shares
, scale_load(MIN_SHARES
), scale_load(MAX_SHARES
));
11773 mutex_lock(&shares_mutex
);
11774 if (tg
->shares
== shares
)
11777 tg
->shares
= shares
;
11778 for_each_possible_cpu(i
) {
11779 struct rq
*rq
= cpu_rq(i
);
11780 struct sched_entity
*se
= tg
->se
[i
];
11781 struct rq_flags rf
;
11783 /* Propagate contribution to hierarchy */
11784 rq_lock_irqsave(rq
, &rf
);
11785 update_rq_clock(rq
);
11786 for_each_sched_entity(se
) {
11787 update_load_avg(se
, UPDATE_TG
);
11788 update_cfs_shares(se
);
11790 rq_unlock_irqrestore(rq
, &rf
);
11794 mutex_unlock(&shares_mutex
);
11797 #else /* CONFIG_FAIR_GROUP_SCHED */
11799 void free_fair_sched_group(struct task_group
*tg
) { }
11801 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
11806 void online_fair_sched_group(struct task_group
*tg
) { }
11808 void unregister_fair_sched_group(struct task_group
*tg
) { }
11810 #endif /* CONFIG_FAIR_GROUP_SCHED */
11813 static unsigned int get_rr_interval_fair(struct rq
*rq
, struct task_struct
*task
)
11815 struct sched_entity
*se
= &task
->se
;
11816 unsigned int rr_interval
= 0;
11819 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11822 if (rq
->cfs
.load
.weight
)
11823 rr_interval
= NS_TO_JIFFIES(sched_slice(cfs_rq_of(se
), se
));
11825 return rr_interval
;
11829 * All the scheduling class methods:
11831 const struct sched_class fair_sched_class
= {
11832 .next
= &idle_sched_class
,
11833 .enqueue_task
= enqueue_task_fair
,
11834 .dequeue_task
= dequeue_task_fair
,
11835 .yield_task
= yield_task_fair
,
11836 .yield_to_task
= yield_to_task_fair
,
11838 .check_preempt_curr
= check_preempt_wakeup
,
11840 .pick_next_task
= pick_next_task_fair
,
11841 .put_prev_task
= put_prev_task_fair
,
11844 .select_task_rq
= select_task_rq_fair
,
11845 .migrate_task_rq
= migrate_task_rq_fair
,
11847 .rq_online
= rq_online_fair
,
11848 .rq_offline
= rq_offline_fair
,
11850 .task_dead
= task_dead_fair
,
11851 .set_cpus_allowed
= set_cpus_allowed_common
,
11854 .set_curr_task
= set_curr_task_fair
,
11855 .task_tick
= task_tick_fair
,
11856 .task_fork
= task_fork_fair
,
11858 .prio_changed
= prio_changed_fair
,
11859 .switched_from
= switched_from_fair
,
11860 .switched_to
= switched_to_fair
,
11862 .get_rr_interval
= get_rr_interval_fair
,
11864 .update_curr
= update_curr_fair
,
11866 #ifdef CONFIG_FAIR_GROUP_SCHED
11867 .task_change_group
= task_change_group_fair
,
11871 #ifdef CONFIG_SCHED_DEBUG
11872 void print_cfs_stats(struct seq_file
*m
, int cpu
)
11874 struct cfs_rq
*cfs_rq
, *pos
;
11877 for_each_leaf_cfs_rq_safe(cpu_rq(cpu
), cfs_rq
, pos
)
11878 print_cfs_rq(m
, cpu
, cfs_rq
);
11882 #ifdef CONFIG_NUMA_BALANCING
11883 void show_numa_stats(struct task_struct
*p
, struct seq_file
*m
)
11886 unsigned long tsf
= 0, tpf
= 0, gsf
= 0, gpf
= 0;
11888 for_each_online_node(node
) {
11889 if (p
->numa_faults
) {
11890 tsf
= p
->numa_faults
[task_faults_idx(NUMA_MEM
, node
, 0)];
11891 tpf
= p
->numa_faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
11893 if (p
->numa_group
) {
11894 gsf
= p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, node
, 0)],
11895 gpf
= p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
11897 print_numa_stats(m
, node
, tsf
, tpf
, gsf
, gpf
);
11900 #endif /* CONFIG_NUMA_BALANCING */
11901 #endif /* CONFIG_SCHED_DEBUG */
11903 __init
void init_sched_fair_class(void)
11906 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
);
11908 #ifdef CONFIG_NO_HZ_COMMON
11909 nohz
.next_balance
= jiffies
;
11910 nohz
.next_update
= jiffies
;
11911 zalloc_cpumask_var(&nohz
.idle_cpus_mask
, GFP_NOWAIT
);