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 = (1024 - cfs_rq->avg.util_avg) / 2^n
781 * where n denotes the nth task.
783 * For example, a simplest series from the beginning would be like:
785 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
786 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
788 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
789 * if util_avg > util_avg_cap.
791 void post_init_entity_util_avg(struct sched_entity
*se
)
793 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
794 struct sched_avg
*sa
= &se
->avg
;
795 long cap
= (long)(SCHED_CAPACITY_SCALE
- cfs_rq
->avg
.util_avg
) / 2;
798 if (cfs_rq
->avg
.util_avg
!= 0) {
799 sa
->util_avg
= cfs_rq
->avg
.util_avg
* se
->load
.weight
;
800 sa
->util_avg
/= (cfs_rq
->avg
.load_avg
+ 1);
802 if (sa
->util_avg
> cap
)
807 sa
->util_sum
= sa
->util_avg
* LOAD_AVG_MAX
;
810 if (entity_is_task(se
)) {
811 struct task_struct
*p
= task_of(se
);
812 if (p
->sched_class
!= &fair_sched_class
) {
814 * For !fair tasks do:
816 update_cfs_rq_load_avg(now, cfs_rq);
817 attach_entity_load_avg(cfs_rq, se);
818 switched_from_fair(rq, p);
820 * such that the next switched_to_fair() has the
823 se
->avg
.last_update_time
= cfs_rq_clock_task(cfs_rq
);
828 attach_entity_cfs_rq(se
);
831 #else /* !CONFIG_SMP */
832 void init_entity_runnable_average(struct sched_entity
*se
)
835 void post_init_entity_util_avg(struct sched_entity
*se
)
838 static void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
)
841 #endif /* CONFIG_SMP */
844 * Update the current task's runtime statistics.
846 static void update_curr(struct cfs_rq
*cfs_rq
)
848 struct sched_entity
*curr
= cfs_rq
->curr
;
849 u64 now
= rq_clock_task(rq_of(cfs_rq
));
855 delta_exec
= now
- curr
->exec_start
;
856 if (unlikely((s64
)delta_exec
<= 0))
859 curr
->exec_start
= now
;
861 schedstat_set(curr
->statistics
.exec_max
,
862 max(delta_exec
, curr
->statistics
.exec_max
));
864 curr
->sum_exec_runtime
+= delta_exec
;
865 schedstat_add(cfs_rq
->exec_clock
, delta_exec
);
867 curr
->vruntime
+= calc_delta_fair(delta_exec
, curr
);
868 update_min_vruntime(cfs_rq
);
870 if (entity_is_task(curr
)) {
871 struct task_struct
*curtask
= task_of(curr
);
873 trace_sched_stat_runtime(curtask
, delta_exec
, curr
->vruntime
);
874 cpuacct_charge(curtask
, delta_exec
);
875 account_group_exec_runtime(curtask
, delta_exec
);
878 account_cfs_rq_runtime(cfs_rq
, delta_exec
);
881 static void update_curr_fair(struct rq
*rq
)
883 update_curr(cfs_rq_of(&rq
->curr
->se
));
887 update_stats_wait_start(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
889 u64 wait_start
, prev_wait_start
;
891 if (!schedstat_enabled())
894 wait_start
= rq_clock(rq_of(cfs_rq
));
895 prev_wait_start
= schedstat_val(se
->statistics
.wait_start
);
897 if (entity_is_task(se
) && task_on_rq_migrating(task_of(se
)) &&
898 likely(wait_start
> prev_wait_start
))
899 wait_start
-= prev_wait_start
;
901 schedstat_set(se
->statistics
.wait_start
, wait_start
);
905 update_stats_wait_end(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
907 struct task_struct
*p
;
910 if (!schedstat_enabled())
913 delta
= rq_clock(rq_of(cfs_rq
)) - schedstat_val(se
->statistics
.wait_start
);
915 if (entity_is_task(se
)) {
917 if (task_on_rq_migrating(p
)) {
919 * Preserve migrating task's wait time so wait_start
920 * time stamp can be adjusted to accumulate wait time
921 * prior to migration.
923 schedstat_set(se
->statistics
.wait_start
, delta
);
926 trace_sched_stat_wait(p
, delta
);
929 schedstat_set(se
->statistics
.wait_max
,
930 max(schedstat_val(se
->statistics
.wait_max
), delta
));
931 schedstat_inc(se
->statistics
.wait_count
);
932 schedstat_add(se
->statistics
.wait_sum
, delta
);
933 schedstat_set(se
->statistics
.wait_start
, 0);
937 update_stats_enqueue_sleeper(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
939 struct task_struct
*tsk
= NULL
;
940 u64 sleep_start
, block_start
;
942 if (!schedstat_enabled())
945 sleep_start
= schedstat_val(se
->statistics
.sleep_start
);
946 block_start
= schedstat_val(se
->statistics
.block_start
);
948 if (entity_is_task(se
))
952 u64 delta
= rq_clock(rq_of(cfs_rq
)) - sleep_start
;
957 if (unlikely(delta
> schedstat_val(se
->statistics
.sleep_max
)))
958 schedstat_set(se
->statistics
.sleep_max
, delta
);
960 schedstat_set(se
->statistics
.sleep_start
, 0);
961 schedstat_add(se
->statistics
.sum_sleep_runtime
, delta
);
964 account_scheduler_latency(tsk
, delta
>> 10, 1);
965 trace_sched_stat_sleep(tsk
, delta
);
969 u64 delta
= rq_clock(rq_of(cfs_rq
)) - block_start
;
974 if (unlikely(delta
> schedstat_val(se
->statistics
.block_max
)))
975 schedstat_set(se
->statistics
.block_max
, delta
);
977 schedstat_set(se
->statistics
.block_start
, 0);
978 schedstat_add(se
->statistics
.sum_sleep_runtime
, delta
);
981 if (tsk
->in_iowait
) {
982 schedstat_add(se
->statistics
.iowait_sum
, delta
);
983 schedstat_inc(se
->statistics
.iowait_count
);
984 trace_sched_stat_iowait(tsk
, delta
);
987 trace_sched_stat_blocked(tsk
, delta
);
988 trace_sched_blocked_reason(tsk
);
991 * Blocking time is in units of nanosecs, so shift by
992 * 20 to get a milliseconds-range estimation of the
993 * amount of time that the task spent sleeping:
995 if (unlikely(prof_on
== SLEEP_PROFILING
)) {
996 profile_hits(SLEEP_PROFILING
,
997 (void *)get_wchan(tsk
),
1000 account_scheduler_latency(tsk
, delta
>> 10, 0);
1006 * Task is being enqueued - update stats:
1009 update_stats_enqueue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
1011 if (!schedstat_enabled())
1015 * Are we enqueueing a waiting task? (for current tasks
1016 * a dequeue/enqueue event is a NOP)
1018 if (se
!= cfs_rq
->curr
)
1019 update_stats_wait_start(cfs_rq
, se
);
1021 if (flags
& ENQUEUE_WAKEUP
)
1022 update_stats_enqueue_sleeper(cfs_rq
, se
);
1026 update_stats_dequeue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
1029 if (!schedstat_enabled())
1033 * Mark the end of the wait period if dequeueing a
1036 if (se
!= cfs_rq
->curr
)
1037 update_stats_wait_end(cfs_rq
, se
);
1039 if ((flags
& DEQUEUE_SLEEP
) && entity_is_task(se
)) {
1040 struct task_struct
*tsk
= task_of(se
);
1042 if (tsk
->state
& TASK_INTERRUPTIBLE
)
1043 schedstat_set(se
->statistics
.sleep_start
,
1044 rq_clock(rq_of(cfs_rq
)));
1045 if (tsk
->state
& TASK_UNINTERRUPTIBLE
)
1046 schedstat_set(se
->statistics
.block_start
,
1047 rq_clock(rq_of(cfs_rq
)));
1052 * We are picking a new current task - update its stats:
1055 update_stats_curr_start(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
1058 * We are starting a new run period:
1060 se
->exec_start
= rq_clock_task(rq_of(cfs_rq
));
1063 /**************************************************
1064 * Scheduling class queueing methods:
1067 #ifdef CONFIG_NUMA_BALANCING
1069 * Approximate time to scan a full NUMA task in ms. The task scan period is
1070 * calculated based on the tasks virtual memory size and
1071 * numa_balancing_scan_size.
1073 unsigned int sysctl_numa_balancing_scan_period_min
= 1000;
1074 unsigned int sysctl_numa_balancing_scan_period_max
= 60000;
1076 /* Portion of address space to scan in MB */
1077 unsigned int sysctl_numa_balancing_scan_size
= 256;
1079 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1080 unsigned int sysctl_numa_balancing_scan_delay
= 1000;
1085 spinlock_t lock
; /* nr_tasks, tasks */
1090 struct rcu_head rcu
;
1091 unsigned long total_faults
;
1092 unsigned long max_faults_cpu
;
1094 * Faults_cpu is used to decide whether memory should move
1095 * towards the CPU. As a consequence, these stats are weighted
1096 * more by CPU use than by memory faults.
1098 unsigned long *faults_cpu
;
1099 unsigned long faults
[0];
1102 static inline unsigned long group_faults_priv(struct numa_group
*ng
);
1103 static inline unsigned long group_faults_shared(struct numa_group
*ng
);
1105 static unsigned int task_nr_scan_windows(struct task_struct
*p
)
1107 unsigned long rss
= 0;
1108 unsigned long nr_scan_pages
;
1111 * Calculations based on RSS as non-present and empty pages are skipped
1112 * by the PTE scanner and NUMA hinting faults should be trapped based
1115 nr_scan_pages
= sysctl_numa_balancing_scan_size
<< (20 - PAGE_SHIFT
);
1116 rss
= get_mm_rss(p
->mm
);
1118 rss
= nr_scan_pages
;
1120 rss
= round_up(rss
, nr_scan_pages
);
1121 return rss
/ nr_scan_pages
;
1124 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1125 #define MAX_SCAN_WINDOW 2560
1127 static unsigned int task_scan_min(struct task_struct
*p
)
1129 unsigned int scan_size
= READ_ONCE(sysctl_numa_balancing_scan_size
);
1130 unsigned int scan
, floor
;
1131 unsigned int windows
= 1;
1133 if (scan_size
< MAX_SCAN_WINDOW
)
1134 windows
= MAX_SCAN_WINDOW
/ scan_size
;
1135 floor
= 1000 / windows
;
1137 scan
= sysctl_numa_balancing_scan_period_min
/ task_nr_scan_windows(p
);
1138 return max_t(unsigned int, floor
, scan
);
1141 static unsigned int task_scan_start(struct task_struct
*p
)
1143 unsigned long smin
= task_scan_min(p
);
1144 unsigned long period
= smin
;
1146 /* Scale the maximum scan period with the amount of shared memory. */
1147 if (p
->numa_group
) {
1148 struct numa_group
*ng
= p
->numa_group
;
1149 unsigned long shared
= group_faults_shared(ng
);
1150 unsigned long private = group_faults_priv(ng
);
1152 period
*= atomic_read(&ng
->refcount
);
1153 period
*= shared
+ 1;
1154 period
/= private + shared
+ 1;
1157 return max(smin
, period
);
1160 static unsigned int task_scan_max(struct task_struct
*p
)
1162 unsigned long smin
= task_scan_min(p
);
1165 /* Watch for min being lower than max due to floor calculations */
1166 smax
= sysctl_numa_balancing_scan_period_max
/ task_nr_scan_windows(p
);
1168 /* Scale the maximum scan period with the amount of shared memory. */
1169 if (p
->numa_group
) {
1170 struct numa_group
*ng
= p
->numa_group
;
1171 unsigned long shared
= group_faults_shared(ng
);
1172 unsigned long private = group_faults_priv(ng
);
1173 unsigned long period
= smax
;
1175 period
*= atomic_read(&ng
->refcount
);
1176 period
*= shared
+ 1;
1177 period
/= private + shared
+ 1;
1179 smax
= max(smax
, period
);
1182 return max(smin
, smax
);
1185 static void account_numa_enqueue(struct rq
*rq
, struct task_struct
*p
)
1187 rq
->nr_numa_running
+= (p
->numa_preferred_nid
!= -1);
1188 rq
->nr_preferred_running
+= (p
->numa_preferred_nid
== task_node(p
));
1191 static void account_numa_dequeue(struct rq
*rq
, struct task_struct
*p
)
1193 rq
->nr_numa_running
-= (p
->numa_preferred_nid
!= -1);
1194 rq
->nr_preferred_running
-= (p
->numa_preferred_nid
== task_node(p
));
1197 /* Shared or private faults. */
1198 #define NR_NUMA_HINT_FAULT_TYPES 2
1200 /* Memory and CPU locality */
1201 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1203 /* Averaged statistics, and temporary buffers. */
1204 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1206 pid_t
task_numa_group_id(struct task_struct
*p
)
1208 return p
->numa_group
? p
->numa_group
->gid
: 0;
1212 * The averaged statistics, shared & private, memory & cpu,
1213 * occupy the first half of the array. The second half of the
1214 * array is for current counters, which are averaged into the
1215 * first set by task_numa_placement.
1217 static inline int task_faults_idx(enum numa_faults_stats s
, int nid
, int priv
)
1219 return NR_NUMA_HINT_FAULT_TYPES
* (s
* nr_node_ids
+ nid
) + priv
;
1222 static inline unsigned long task_faults(struct task_struct
*p
, int nid
)
1224 if (!p
->numa_faults
)
1227 return p
->numa_faults
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1228 p
->numa_faults
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1231 static inline unsigned long group_faults(struct task_struct
*p
, int nid
)
1236 return p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1237 p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1240 static inline unsigned long group_faults_cpu(struct numa_group
*group
, int nid
)
1242 return group
->faults_cpu
[task_faults_idx(NUMA_MEM
, nid
, 0)] +
1243 group
->faults_cpu
[task_faults_idx(NUMA_MEM
, nid
, 1)];
1246 static inline unsigned long group_faults_priv(struct numa_group
*ng
)
1248 unsigned long faults
= 0;
1251 for_each_online_node(node
) {
1252 faults
+= ng
->faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
1258 static inline unsigned long group_faults_shared(struct numa_group
*ng
)
1260 unsigned long faults
= 0;
1263 for_each_online_node(node
) {
1264 faults
+= ng
->faults
[task_faults_idx(NUMA_MEM
, node
, 0)];
1271 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1272 * considered part of a numa group's pseudo-interleaving set. Migrations
1273 * between these nodes are slowed down, to allow things to settle down.
1275 #define ACTIVE_NODE_FRACTION 3
1277 static bool numa_is_active_node(int nid
, struct numa_group
*ng
)
1279 return group_faults_cpu(ng
, nid
) * ACTIVE_NODE_FRACTION
> ng
->max_faults_cpu
;
1282 /* Handle placement on systems where not all nodes are directly connected. */
1283 static unsigned long score_nearby_nodes(struct task_struct
*p
, int nid
,
1284 int maxdist
, bool task
)
1286 unsigned long score
= 0;
1290 * All nodes are directly connected, and the same distance
1291 * from each other. No need for fancy placement algorithms.
1293 if (sched_numa_topology_type
== NUMA_DIRECT
)
1297 * This code is called for each node, introducing N^2 complexity,
1298 * which should be ok given the number of nodes rarely exceeds 8.
1300 for_each_online_node(node
) {
1301 unsigned long faults
;
1302 int dist
= node_distance(nid
, node
);
1305 * The furthest away nodes in the system are not interesting
1306 * for placement; nid was already counted.
1308 if (dist
== sched_max_numa_distance
|| node
== nid
)
1312 * On systems with a backplane NUMA topology, compare groups
1313 * of nodes, and move tasks towards the group with the most
1314 * memory accesses. When comparing two nodes at distance
1315 * "hoplimit", only nodes closer by than "hoplimit" are part
1316 * of each group. Skip other nodes.
1318 if (sched_numa_topology_type
== NUMA_BACKPLANE
&&
1322 /* Add up the faults from nearby nodes. */
1324 faults
= task_faults(p
, node
);
1326 faults
= group_faults(p
, node
);
1329 * On systems with a glueless mesh NUMA topology, there are
1330 * no fixed "groups of nodes". Instead, nodes that are not
1331 * directly connected bounce traffic through intermediate
1332 * nodes; a numa_group can occupy any set of nodes.
1333 * The further away a node is, the less the faults count.
1334 * This seems to result in good task placement.
1336 if (sched_numa_topology_type
== NUMA_GLUELESS_MESH
) {
1337 faults
*= (sched_max_numa_distance
- dist
);
1338 faults
/= (sched_max_numa_distance
- LOCAL_DISTANCE
);
1348 * These return the fraction of accesses done by a particular task, or
1349 * task group, on a particular numa node. The group weight is given a
1350 * larger multiplier, in order to group tasks together that are almost
1351 * evenly spread out between numa nodes.
1353 static inline unsigned long task_weight(struct task_struct
*p
, int nid
,
1356 unsigned long faults
, total_faults
;
1358 if (!p
->numa_faults
)
1361 total_faults
= p
->total_numa_faults
;
1366 faults
= task_faults(p
, nid
);
1367 faults
+= score_nearby_nodes(p
, nid
, dist
, true);
1369 return 1000 * faults
/ total_faults
;
1372 static inline unsigned long group_weight(struct task_struct
*p
, int nid
,
1375 unsigned long faults
, total_faults
;
1380 total_faults
= p
->numa_group
->total_faults
;
1385 faults
= group_faults(p
, nid
);
1386 faults
+= score_nearby_nodes(p
, nid
, dist
, false);
1388 return 1000 * faults
/ total_faults
;
1391 bool should_numa_migrate_memory(struct task_struct
*p
, struct page
* page
,
1392 int src_nid
, int dst_cpu
)
1394 struct numa_group
*ng
= p
->numa_group
;
1395 int dst_nid
= cpu_to_node(dst_cpu
);
1396 int last_cpupid
, this_cpupid
;
1398 this_cpupid
= cpu_pid_to_cpupid(dst_cpu
, current
->pid
);
1401 * Multi-stage node selection is used in conjunction with a periodic
1402 * migration fault to build a temporal task<->page relation. By using
1403 * a two-stage filter we remove short/unlikely relations.
1405 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1406 * a task's usage of a particular page (n_p) per total usage of this
1407 * page (n_t) (in a given time-span) to a probability.
1409 * Our periodic faults will sample this probability and getting the
1410 * same result twice in a row, given these samples are fully
1411 * independent, is then given by P(n)^2, provided our sample period
1412 * is sufficiently short compared to the usage pattern.
1414 * This quadric squishes small probabilities, making it less likely we
1415 * act on an unlikely task<->page relation.
1417 last_cpupid
= page_cpupid_xchg_last(page
, this_cpupid
);
1418 if (!cpupid_pid_unset(last_cpupid
) &&
1419 cpupid_to_nid(last_cpupid
) != dst_nid
)
1422 /* Always allow migrate on private faults */
1423 if (cpupid_match_pid(p
, last_cpupid
))
1426 /* A shared fault, but p->numa_group has not been set up yet. */
1431 * Destination node is much more heavily used than the source
1432 * node? Allow migration.
1434 if (group_faults_cpu(ng
, dst_nid
) > group_faults_cpu(ng
, src_nid
) *
1435 ACTIVE_NODE_FRACTION
)
1439 * Distribute memory according to CPU & memory use on each node,
1440 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1442 * faults_cpu(dst) 3 faults_cpu(src)
1443 * --------------- * - > ---------------
1444 * faults_mem(dst) 4 faults_mem(src)
1446 return group_faults_cpu(ng
, dst_nid
) * group_faults(p
, src_nid
) * 3 >
1447 group_faults_cpu(ng
, src_nid
) * group_faults(p
, dst_nid
) * 4;
1450 static unsigned long weighted_cpuload(struct rq
*rq
);
1451 static unsigned long source_load(int cpu
, int type
);
1452 static unsigned long target_load(int cpu
, int type
);
1454 /* Cached statistics for all CPUs within a node */
1456 unsigned long nr_running
;
1459 /* Total compute capacity of CPUs on a node */
1460 unsigned long compute_capacity
;
1462 /* Approximate capacity in terms of runnable tasks on a node */
1463 unsigned long task_capacity
;
1464 int has_free_capacity
;
1468 * XXX borrowed from update_sg_lb_stats
1470 static void update_numa_stats(struct numa_stats
*ns
, int nid
)
1472 int smt
, cpu
, cpus
= 0;
1473 unsigned long capacity
;
1475 memset(ns
, 0, sizeof(*ns
));
1476 for_each_cpu(cpu
, cpumask_of_node(nid
)) {
1477 struct rq
*rq
= cpu_rq(cpu
);
1479 ns
->nr_running
+= rq
->nr_running
;
1480 ns
->load
+= weighted_cpuload(rq
);
1481 ns
->compute_capacity
+= capacity_of(cpu
);
1487 * If we raced with hotplug and there are no CPUs left in our mask
1488 * the @ns structure is NULL'ed and task_numa_compare() will
1489 * not find this node attractive.
1491 * We'll either bail at !has_free_capacity, or we'll detect a huge
1492 * imbalance and bail there.
1497 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1498 smt
= DIV_ROUND_UP(SCHED_CAPACITY_SCALE
* cpus
, ns
->compute_capacity
);
1499 capacity
= cpus
/ smt
; /* cores */
1501 ns
->task_capacity
= min_t(unsigned, capacity
,
1502 DIV_ROUND_CLOSEST(ns
->compute_capacity
, SCHED_CAPACITY_SCALE
));
1503 ns
->has_free_capacity
= (ns
->nr_running
< ns
->task_capacity
);
1506 struct task_numa_env
{
1507 struct task_struct
*p
;
1509 int src_cpu
, src_nid
;
1510 int dst_cpu
, dst_nid
;
1512 struct numa_stats src_stats
, dst_stats
;
1517 struct task_struct
*best_task
;
1522 static void task_numa_assign(struct task_numa_env
*env
,
1523 struct task_struct
*p
, long imp
)
1526 put_task_struct(env
->best_task
);
1531 env
->best_imp
= imp
;
1532 env
->best_cpu
= env
->dst_cpu
;
1535 static bool load_too_imbalanced(long src_load
, long dst_load
,
1536 struct task_numa_env
*env
)
1539 long orig_src_load
, orig_dst_load
;
1540 long src_capacity
, dst_capacity
;
1543 * The load is corrected for the CPU capacity available on each node.
1546 * ------------ vs ---------
1547 * src_capacity dst_capacity
1549 src_capacity
= env
->src_stats
.compute_capacity
;
1550 dst_capacity
= env
->dst_stats
.compute_capacity
;
1552 /* We care about the slope of the imbalance, not the direction. */
1553 if (dst_load
< src_load
)
1554 swap(dst_load
, src_load
);
1556 /* Is the difference below the threshold? */
1557 imb
= dst_load
* src_capacity
* 100 -
1558 src_load
* dst_capacity
* env
->imbalance_pct
;
1563 * The imbalance is above the allowed threshold.
1564 * Compare it with the old imbalance.
1566 orig_src_load
= env
->src_stats
.load
;
1567 orig_dst_load
= env
->dst_stats
.load
;
1569 if (orig_dst_load
< orig_src_load
)
1570 swap(orig_dst_load
, orig_src_load
);
1572 old_imb
= orig_dst_load
* src_capacity
* 100 -
1573 orig_src_load
* dst_capacity
* env
->imbalance_pct
;
1575 /* Would this change make things worse? */
1576 return (imb
> old_imb
);
1580 * This checks if the overall compute and NUMA accesses of the system would
1581 * be improved if the source tasks was migrated to the target dst_cpu taking
1582 * into account that it might be best if task running on the dst_cpu should
1583 * be exchanged with the source task
1585 static void task_numa_compare(struct task_numa_env
*env
,
1586 long taskimp
, long groupimp
)
1588 struct rq
*src_rq
= cpu_rq(env
->src_cpu
);
1589 struct rq
*dst_rq
= cpu_rq(env
->dst_cpu
);
1590 struct task_struct
*cur
;
1591 long src_load
, dst_load
;
1593 long imp
= env
->p
->numa_group
? groupimp
: taskimp
;
1595 int dist
= env
->dist
;
1598 cur
= task_rcu_dereference(&dst_rq
->curr
);
1599 if (cur
&& ((cur
->flags
& PF_EXITING
) || is_idle_task(cur
)))
1603 * Because we have preemption enabled we can get migrated around and
1604 * end try selecting ourselves (current == env->p) as a swap candidate.
1610 * "imp" is the fault differential for the source task between the
1611 * source and destination node. Calculate the total differential for
1612 * the source task and potential destination task. The more negative
1613 * the value is, the more rmeote accesses that would be expected to
1614 * be incurred if the tasks were swapped.
1617 /* Skip this swap candidate if cannot move to the source cpu */
1618 if (!cpumask_test_cpu(env
->src_cpu
, &cur
->cpus_allowed
))
1622 * If dst and source tasks are in the same NUMA group, or not
1623 * in any group then look only at task weights.
1625 if (cur
->numa_group
== env
->p
->numa_group
) {
1626 imp
= taskimp
+ task_weight(cur
, env
->src_nid
, dist
) -
1627 task_weight(cur
, env
->dst_nid
, dist
);
1629 * Add some hysteresis to prevent swapping the
1630 * tasks within a group over tiny differences.
1632 if (cur
->numa_group
)
1636 * Compare the group weights. If a task is all by
1637 * itself (not part of a group), use the task weight
1640 if (cur
->numa_group
)
1641 imp
+= group_weight(cur
, env
->src_nid
, dist
) -
1642 group_weight(cur
, env
->dst_nid
, dist
);
1644 imp
+= task_weight(cur
, env
->src_nid
, dist
) -
1645 task_weight(cur
, env
->dst_nid
, dist
);
1649 if (imp
<= env
->best_imp
&& moveimp
<= env
->best_imp
)
1653 /* Is there capacity at our destination? */
1654 if (env
->src_stats
.nr_running
<= env
->src_stats
.task_capacity
&&
1655 !env
->dst_stats
.has_free_capacity
)
1661 /* Balance doesn't matter much if we're running a task per cpu */
1662 if (imp
> env
->best_imp
&& src_rq
->nr_running
== 1 &&
1663 dst_rq
->nr_running
== 1)
1667 * In the overloaded case, try and keep the load balanced.
1670 load
= task_h_load(env
->p
);
1671 dst_load
= env
->dst_stats
.load
+ load
;
1672 src_load
= env
->src_stats
.load
- load
;
1674 if (moveimp
> imp
&& moveimp
> env
->best_imp
) {
1676 * If the improvement from just moving env->p direction is
1677 * better than swapping tasks around, check if a move is
1678 * possible. Store a slightly smaller score than moveimp,
1679 * so an actually idle CPU will win.
1681 if (!load_too_imbalanced(src_load
, dst_load
, env
)) {
1688 if (imp
<= env
->best_imp
)
1692 load
= task_h_load(cur
);
1697 if (load_too_imbalanced(src_load
, dst_load
, env
))
1701 * One idle CPU per node is evaluated for a task numa move.
1702 * Call select_idle_sibling to maybe find a better one.
1706 * select_idle_siblings() uses an per-cpu cpumask that
1707 * can be used from IRQ context.
1709 local_irq_disable();
1710 env
->dst_cpu
= select_idle_sibling(env
->p
, env
->src_cpu
,
1716 task_numa_assign(env
, cur
, imp
);
1721 static void task_numa_find_cpu(struct task_numa_env
*env
,
1722 long taskimp
, long groupimp
)
1726 for_each_cpu(cpu
, cpumask_of_node(env
->dst_nid
)) {
1727 /* Skip this CPU if the source task cannot migrate */
1728 if (!cpumask_test_cpu(cpu
, &env
->p
->cpus_allowed
))
1732 task_numa_compare(env
, taskimp
, groupimp
);
1736 /* Only move tasks to a NUMA node less busy than the current node. */
1737 static bool numa_has_capacity(struct task_numa_env
*env
)
1739 struct numa_stats
*src
= &env
->src_stats
;
1740 struct numa_stats
*dst
= &env
->dst_stats
;
1742 if (src
->has_free_capacity
&& !dst
->has_free_capacity
)
1746 * Only consider a task move if the source has a higher load
1747 * than the destination, corrected for CPU capacity on each node.
1749 * src->load dst->load
1750 * --------------------- vs ---------------------
1751 * src->compute_capacity dst->compute_capacity
1753 if (src
->load
* dst
->compute_capacity
* env
->imbalance_pct
>
1755 dst
->load
* src
->compute_capacity
* 100)
1761 static int task_numa_migrate(struct task_struct
*p
)
1763 struct task_numa_env env
= {
1766 .src_cpu
= task_cpu(p
),
1767 .src_nid
= task_node(p
),
1769 .imbalance_pct
= 112,
1775 struct sched_domain
*sd
;
1776 unsigned long taskweight
, groupweight
;
1778 long taskimp
, groupimp
;
1781 * Pick the lowest SD_NUMA domain, as that would have the smallest
1782 * imbalance and would be the first to start moving tasks about.
1784 * And we want to avoid any moving of tasks about, as that would create
1785 * random movement of tasks -- counter the numa conditions we're trying
1789 sd
= rcu_dereference(per_cpu(sd_numa
, env
.src_cpu
));
1791 env
.imbalance_pct
= 100 + (sd
->imbalance_pct
- 100) / 2;
1795 * Cpusets can break the scheduler domain tree into smaller
1796 * balance domains, some of which do not cross NUMA boundaries.
1797 * Tasks that are "trapped" in such domains cannot be migrated
1798 * elsewhere, so there is no point in (re)trying.
1800 if (unlikely(!sd
)) {
1801 p
->numa_preferred_nid
= task_node(p
);
1805 env
.dst_nid
= p
->numa_preferred_nid
;
1806 dist
= env
.dist
= node_distance(env
.src_nid
, env
.dst_nid
);
1807 taskweight
= task_weight(p
, env
.src_nid
, dist
);
1808 groupweight
= group_weight(p
, env
.src_nid
, dist
);
1809 update_numa_stats(&env
.src_stats
, env
.src_nid
);
1810 taskimp
= task_weight(p
, env
.dst_nid
, dist
) - taskweight
;
1811 groupimp
= group_weight(p
, env
.dst_nid
, dist
) - groupweight
;
1812 update_numa_stats(&env
.dst_stats
, env
.dst_nid
);
1814 /* Try to find a spot on the preferred nid. */
1815 if (numa_has_capacity(&env
))
1816 task_numa_find_cpu(&env
, taskimp
, groupimp
);
1819 * Look at other nodes in these cases:
1820 * - there is no space available on the preferred_nid
1821 * - the task is part of a numa_group that is interleaved across
1822 * multiple NUMA nodes; in order to better consolidate the group,
1823 * we need to check other locations.
1825 if (env
.best_cpu
== -1 || (p
->numa_group
&& p
->numa_group
->active_nodes
> 1)) {
1826 for_each_online_node(nid
) {
1827 if (nid
== env
.src_nid
|| nid
== p
->numa_preferred_nid
)
1830 dist
= node_distance(env
.src_nid
, env
.dst_nid
);
1831 if (sched_numa_topology_type
== NUMA_BACKPLANE
&&
1833 taskweight
= task_weight(p
, env
.src_nid
, dist
);
1834 groupweight
= group_weight(p
, env
.src_nid
, dist
);
1837 /* Only consider nodes where both task and groups benefit */
1838 taskimp
= task_weight(p
, nid
, dist
) - taskweight
;
1839 groupimp
= group_weight(p
, nid
, dist
) - groupweight
;
1840 if (taskimp
< 0 && groupimp
< 0)
1845 update_numa_stats(&env
.dst_stats
, env
.dst_nid
);
1846 if (numa_has_capacity(&env
))
1847 task_numa_find_cpu(&env
, taskimp
, groupimp
);
1852 * If the task is part of a workload that spans multiple NUMA nodes,
1853 * and is migrating into one of the workload's active nodes, remember
1854 * this node as the task's preferred numa node, so the workload can
1856 * A task that migrated to a second choice node will be better off
1857 * trying for a better one later. Do not set the preferred node here.
1859 if (p
->numa_group
) {
1860 struct numa_group
*ng
= p
->numa_group
;
1862 if (env
.best_cpu
== -1)
1867 if (ng
->active_nodes
> 1 && numa_is_active_node(env
.dst_nid
, ng
))
1868 sched_setnuma(p
, env
.dst_nid
);
1871 /* No better CPU than the current one was found. */
1872 if (env
.best_cpu
== -1)
1876 * Reset the scan period if the task is being rescheduled on an
1877 * alternative node to recheck if the tasks is now properly placed.
1879 p
->numa_scan_period
= task_scan_start(p
);
1881 if (env
.best_task
== NULL
) {
1882 ret
= migrate_task_to(p
, env
.best_cpu
);
1884 trace_sched_stick_numa(p
, env
.src_cpu
, env
.best_cpu
);
1888 ret
= migrate_swap(p
, env
.best_task
);
1890 trace_sched_stick_numa(p
, env
.src_cpu
, task_cpu(env
.best_task
));
1891 put_task_struct(env
.best_task
);
1895 /* Attempt to migrate a task to a CPU on the preferred node. */
1896 static void numa_migrate_preferred(struct task_struct
*p
)
1898 unsigned long interval
= HZ
;
1900 /* This task has no NUMA fault statistics yet */
1901 if (unlikely(p
->numa_preferred_nid
== -1 || !p
->numa_faults
))
1904 /* Periodically retry migrating the task to the preferred node */
1905 interval
= min(interval
, msecs_to_jiffies(p
->numa_scan_period
) / 16);
1906 p
->numa_migrate_retry
= jiffies
+ interval
;
1908 /* Success if task is already running on preferred CPU */
1909 if (task_node(p
) == p
->numa_preferred_nid
)
1912 /* Otherwise, try migrate to a CPU on the preferred node */
1913 task_numa_migrate(p
);
1917 * Find out how many nodes on the workload is actively running on. Do this by
1918 * tracking the nodes from which NUMA hinting faults are triggered. This can
1919 * be different from the set of nodes where the workload's memory is currently
1922 static void numa_group_count_active_nodes(struct numa_group
*numa_group
)
1924 unsigned long faults
, max_faults
= 0;
1925 int nid
, active_nodes
= 0;
1927 for_each_online_node(nid
) {
1928 faults
= group_faults_cpu(numa_group
, nid
);
1929 if (faults
> max_faults
)
1930 max_faults
= faults
;
1933 for_each_online_node(nid
) {
1934 faults
= group_faults_cpu(numa_group
, nid
);
1935 if (faults
* ACTIVE_NODE_FRACTION
> max_faults
)
1939 numa_group
->max_faults_cpu
= max_faults
;
1940 numa_group
->active_nodes
= active_nodes
;
1944 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1945 * increments. The more local the fault statistics are, the higher the scan
1946 * period will be for the next scan window. If local/(local+remote) ratio is
1947 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1948 * the scan period will decrease. Aim for 70% local accesses.
1950 #define NUMA_PERIOD_SLOTS 10
1951 #define NUMA_PERIOD_THRESHOLD 7
1954 * Increase the scan period (slow down scanning) if the majority of
1955 * our memory is already on our local node, or if the majority of
1956 * the page accesses are shared with other processes.
1957 * Otherwise, decrease the scan period.
1959 static void update_task_scan_period(struct task_struct
*p
,
1960 unsigned long shared
, unsigned long private)
1962 unsigned int period_slot
;
1963 int lr_ratio
, ps_ratio
;
1966 unsigned long remote
= p
->numa_faults_locality
[0];
1967 unsigned long local
= p
->numa_faults_locality
[1];
1970 * If there were no record hinting faults then either the task is
1971 * completely idle or all activity is areas that are not of interest
1972 * to automatic numa balancing. Related to that, if there were failed
1973 * migration then it implies we are migrating too quickly or the local
1974 * node is overloaded. In either case, scan slower
1976 if (local
+ shared
== 0 || p
->numa_faults_locality
[2]) {
1977 p
->numa_scan_period
= min(p
->numa_scan_period_max
,
1978 p
->numa_scan_period
<< 1);
1980 p
->mm
->numa_next_scan
= jiffies
+
1981 msecs_to_jiffies(p
->numa_scan_period
);
1987 * Prepare to scale scan period relative to the current period.
1988 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1989 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1990 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1992 period_slot
= DIV_ROUND_UP(p
->numa_scan_period
, NUMA_PERIOD_SLOTS
);
1993 lr_ratio
= (local
* NUMA_PERIOD_SLOTS
) / (local
+ remote
);
1994 ps_ratio
= (private * NUMA_PERIOD_SLOTS
) / (private + shared
);
1996 if (ps_ratio
>= NUMA_PERIOD_THRESHOLD
) {
1998 * Most memory accesses are local. There is no need to
1999 * do fast NUMA scanning, since memory is already local.
2001 int slot
= ps_ratio
- NUMA_PERIOD_THRESHOLD
;
2004 diff
= slot
* period_slot
;
2005 } else if (lr_ratio
>= NUMA_PERIOD_THRESHOLD
) {
2007 * Most memory accesses are shared with other tasks.
2008 * There is no point in continuing fast NUMA scanning,
2009 * since other tasks may just move the memory elsewhere.
2011 int slot
= lr_ratio
- NUMA_PERIOD_THRESHOLD
;
2014 diff
= slot
* period_slot
;
2017 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2018 * yet they are not on the local NUMA node. Speed up
2019 * NUMA scanning to get the memory moved over.
2021 int ratio
= max(lr_ratio
, ps_ratio
);
2022 diff
= -(NUMA_PERIOD_THRESHOLD
- ratio
) * period_slot
;
2025 p
->numa_scan_period
= clamp(p
->numa_scan_period
+ diff
,
2026 task_scan_min(p
), task_scan_max(p
));
2027 memset(p
->numa_faults_locality
, 0, sizeof(p
->numa_faults_locality
));
2031 * Get the fraction of time the task has been running since the last
2032 * NUMA placement cycle. The scheduler keeps similar statistics, but
2033 * decays those on a 32ms period, which is orders of magnitude off
2034 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2035 * stats only if the task is so new there are no NUMA statistics yet.
2037 static u64
numa_get_avg_runtime(struct task_struct
*p
, u64
*period
)
2039 u64 runtime
, delta
, now
;
2040 /* Use the start of this time slice to avoid calculations. */
2041 now
= p
->se
.exec_start
;
2042 runtime
= p
->se
.sum_exec_runtime
;
2044 if (p
->last_task_numa_placement
) {
2045 delta
= runtime
- p
->last_sum_exec_runtime
;
2046 *period
= now
- p
->last_task_numa_placement
;
2048 delta
= p
->se
.avg
.load_sum
/ p
->se
.load
.weight
;
2049 *period
= LOAD_AVG_MAX
;
2052 p
->last_sum_exec_runtime
= runtime
;
2053 p
->last_task_numa_placement
= now
;
2059 * Determine the preferred nid for a task in a numa_group. This needs to
2060 * be done in a way that produces consistent results with group_weight,
2061 * otherwise workloads might not converge.
2063 static int preferred_group_nid(struct task_struct
*p
, int nid
)
2068 /* Direct connections between all NUMA nodes. */
2069 if (sched_numa_topology_type
== NUMA_DIRECT
)
2073 * On a system with glueless mesh NUMA topology, group_weight
2074 * scores nodes according to the number of NUMA hinting faults on
2075 * both the node itself, and on nearby nodes.
2077 if (sched_numa_topology_type
== NUMA_GLUELESS_MESH
) {
2078 unsigned long score
, max_score
= 0;
2079 int node
, max_node
= nid
;
2081 dist
= sched_max_numa_distance
;
2083 for_each_online_node(node
) {
2084 score
= group_weight(p
, node
, dist
);
2085 if (score
> max_score
) {
2094 * Finding the preferred nid in a system with NUMA backplane
2095 * interconnect topology is more involved. The goal is to locate
2096 * tasks from numa_groups near each other in the system, and
2097 * untangle workloads from different sides of the system. This requires
2098 * searching down the hierarchy of node groups, recursively searching
2099 * inside the highest scoring group of nodes. The nodemask tricks
2100 * keep the complexity of the search down.
2102 nodes
= node_online_map
;
2103 for (dist
= sched_max_numa_distance
; dist
> LOCAL_DISTANCE
; dist
--) {
2104 unsigned long max_faults
= 0;
2105 nodemask_t max_group
= NODE_MASK_NONE
;
2108 /* Are there nodes at this distance from each other? */
2109 if (!find_numa_distance(dist
))
2112 for_each_node_mask(a
, nodes
) {
2113 unsigned long faults
= 0;
2114 nodemask_t this_group
;
2115 nodes_clear(this_group
);
2117 /* Sum group's NUMA faults; includes a==b case. */
2118 for_each_node_mask(b
, nodes
) {
2119 if (node_distance(a
, b
) < dist
) {
2120 faults
+= group_faults(p
, b
);
2121 node_set(b
, this_group
);
2122 node_clear(b
, nodes
);
2126 /* Remember the top group. */
2127 if (faults
> max_faults
) {
2128 max_faults
= faults
;
2129 max_group
= this_group
;
2131 * subtle: at the smallest distance there is
2132 * just one node left in each "group", the
2133 * winner is the preferred nid.
2138 /* Next round, evaluate the nodes within max_group. */
2146 static void task_numa_placement(struct task_struct
*p
)
2148 int seq
, nid
, max_nid
= -1, max_group_nid
= -1;
2149 unsigned long max_faults
= 0, max_group_faults
= 0;
2150 unsigned long fault_types
[2] = { 0, 0 };
2151 unsigned long total_faults
;
2152 u64 runtime
, period
;
2153 spinlock_t
*group_lock
= NULL
;
2156 * The p->mm->numa_scan_seq field gets updated without
2157 * exclusive access. Use READ_ONCE() here to ensure
2158 * that the field is read in a single access:
2160 seq
= READ_ONCE(p
->mm
->numa_scan_seq
);
2161 if (p
->numa_scan_seq
== seq
)
2163 p
->numa_scan_seq
= seq
;
2164 p
->numa_scan_period_max
= task_scan_max(p
);
2166 total_faults
= p
->numa_faults_locality
[0] +
2167 p
->numa_faults_locality
[1];
2168 runtime
= numa_get_avg_runtime(p
, &period
);
2170 /* If the task is part of a group prevent parallel updates to group stats */
2171 if (p
->numa_group
) {
2172 group_lock
= &p
->numa_group
->lock
;
2173 spin_lock_irq(group_lock
);
2176 /* Find the node with the highest number of faults */
2177 for_each_online_node(nid
) {
2178 /* Keep track of the offsets in numa_faults array */
2179 int mem_idx
, membuf_idx
, cpu_idx
, cpubuf_idx
;
2180 unsigned long faults
= 0, group_faults
= 0;
2183 for (priv
= 0; priv
< NR_NUMA_HINT_FAULT_TYPES
; priv
++) {
2184 long diff
, f_diff
, f_weight
;
2186 mem_idx
= task_faults_idx(NUMA_MEM
, nid
, priv
);
2187 membuf_idx
= task_faults_idx(NUMA_MEMBUF
, nid
, priv
);
2188 cpu_idx
= task_faults_idx(NUMA_CPU
, nid
, priv
);
2189 cpubuf_idx
= task_faults_idx(NUMA_CPUBUF
, nid
, priv
);
2191 /* Decay existing window, copy faults since last scan */
2192 diff
= p
->numa_faults
[membuf_idx
] - p
->numa_faults
[mem_idx
] / 2;
2193 fault_types
[priv
] += p
->numa_faults
[membuf_idx
];
2194 p
->numa_faults
[membuf_idx
] = 0;
2197 * Normalize the faults_from, so all tasks in a group
2198 * count according to CPU use, instead of by the raw
2199 * number of faults. Tasks with little runtime have
2200 * little over-all impact on throughput, and thus their
2201 * faults are less important.
2203 f_weight
= div64_u64(runtime
<< 16, period
+ 1);
2204 f_weight
= (f_weight
* p
->numa_faults
[cpubuf_idx
]) /
2206 f_diff
= f_weight
- p
->numa_faults
[cpu_idx
] / 2;
2207 p
->numa_faults
[cpubuf_idx
] = 0;
2209 p
->numa_faults
[mem_idx
] += diff
;
2210 p
->numa_faults
[cpu_idx
] += f_diff
;
2211 faults
+= p
->numa_faults
[mem_idx
];
2212 p
->total_numa_faults
+= diff
;
2213 if (p
->numa_group
) {
2215 * safe because we can only change our own group
2217 * mem_idx represents the offset for a given
2218 * nid and priv in a specific region because it
2219 * is at the beginning of the numa_faults array.
2221 p
->numa_group
->faults
[mem_idx
] += diff
;
2222 p
->numa_group
->faults_cpu
[mem_idx
] += f_diff
;
2223 p
->numa_group
->total_faults
+= diff
;
2224 group_faults
+= p
->numa_group
->faults
[mem_idx
];
2228 if (faults
> max_faults
) {
2229 max_faults
= faults
;
2233 if (group_faults
> max_group_faults
) {
2234 max_group_faults
= group_faults
;
2235 max_group_nid
= nid
;
2239 update_task_scan_period(p
, fault_types
[0], fault_types
[1]);
2241 if (p
->numa_group
) {
2242 numa_group_count_active_nodes(p
->numa_group
);
2243 spin_unlock_irq(group_lock
);
2244 max_nid
= preferred_group_nid(p
, max_group_nid
);
2248 /* Set the new preferred node */
2249 if (max_nid
!= p
->numa_preferred_nid
)
2250 sched_setnuma(p
, max_nid
);
2252 if (task_node(p
) != p
->numa_preferred_nid
)
2253 numa_migrate_preferred(p
);
2257 static inline int get_numa_group(struct numa_group
*grp
)
2259 return atomic_inc_not_zero(&grp
->refcount
);
2262 static inline void put_numa_group(struct numa_group
*grp
)
2264 if (atomic_dec_and_test(&grp
->refcount
))
2265 kfree_rcu(grp
, rcu
);
2268 static void task_numa_group(struct task_struct
*p
, int cpupid
, int flags
,
2271 struct numa_group
*grp
, *my_grp
;
2272 struct task_struct
*tsk
;
2274 int cpu
= cpupid_to_cpu(cpupid
);
2277 if (unlikely(!p
->numa_group
)) {
2278 unsigned int size
= sizeof(struct numa_group
) +
2279 4*nr_node_ids
*sizeof(unsigned long);
2281 grp
= kzalloc(size
, GFP_KERNEL
| __GFP_NOWARN
);
2285 atomic_set(&grp
->refcount
, 1);
2286 grp
->active_nodes
= 1;
2287 grp
->max_faults_cpu
= 0;
2288 spin_lock_init(&grp
->lock
);
2290 /* Second half of the array tracks nids where faults happen */
2291 grp
->faults_cpu
= grp
->faults
+ NR_NUMA_HINT_FAULT_TYPES
*
2294 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++)
2295 grp
->faults
[i
] = p
->numa_faults
[i
];
2297 grp
->total_faults
= p
->total_numa_faults
;
2300 rcu_assign_pointer(p
->numa_group
, grp
);
2304 tsk
= READ_ONCE(cpu_rq(cpu
)->curr
);
2306 if (!cpupid_match_pid(tsk
, cpupid
))
2309 grp
= rcu_dereference(tsk
->numa_group
);
2313 my_grp
= p
->numa_group
;
2318 * Only join the other group if its bigger; if we're the bigger group,
2319 * the other task will join us.
2321 if (my_grp
->nr_tasks
> grp
->nr_tasks
)
2325 * Tie-break on the grp address.
2327 if (my_grp
->nr_tasks
== grp
->nr_tasks
&& my_grp
> grp
)
2330 /* Always join threads in the same process. */
2331 if (tsk
->mm
== current
->mm
)
2334 /* Simple filter to avoid false positives due to PID collisions */
2335 if (flags
& TNF_SHARED
)
2338 /* Update priv based on whether false sharing was detected */
2341 if (join
&& !get_numa_group(grp
))
2349 BUG_ON(irqs_disabled());
2350 double_lock_irq(&my_grp
->lock
, &grp
->lock
);
2352 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++) {
2353 my_grp
->faults
[i
] -= p
->numa_faults
[i
];
2354 grp
->faults
[i
] += p
->numa_faults
[i
];
2356 my_grp
->total_faults
-= p
->total_numa_faults
;
2357 grp
->total_faults
+= p
->total_numa_faults
;
2362 spin_unlock(&my_grp
->lock
);
2363 spin_unlock_irq(&grp
->lock
);
2365 rcu_assign_pointer(p
->numa_group
, grp
);
2367 put_numa_group(my_grp
);
2375 void task_numa_free(struct task_struct
*p
)
2377 struct numa_group
*grp
= p
->numa_group
;
2378 void *numa_faults
= p
->numa_faults
;
2379 unsigned long flags
;
2383 spin_lock_irqsave(&grp
->lock
, flags
);
2384 for (i
= 0; i
< NR_NUMA_HINT_FAULT_STATS
* nr_node_ids
; i
++)
2385 grp
->faults
[i
] -= p
->numa_faults
[i
];
2386 grp
->total_faults
-= p
->total_numa_faults
;
2389 spin_unlock_irqrestore(&grp
->lock
, flags
);
2390 RCU_INIT_POINTER(p
->numa_group
, NULL
);
2391 put_numa_group(grp
);
2394 p
->numa_faults
= NULL
;
2399 * Got a PROT_NONE fault for a page on @node.
2401 void task_numa_fault(int last_cpupid
, int mem_node
, int pages
, int flags
)
2403 struct task_struct
*p
= current
;
2404 bool migrated
= flags
& TNF_MIGRATED
;
2405 int cpu_node
= task_node(current
);
2406 int local
= !!(flags
& TNF_FAULT_LOCAL
);
2407 struct numa_group
*ng
;
2410 if (!static_branch_likely(&sched_numa_balancing
))
2413 /* for example, ksmd faulting in a user's mm */
2417 /* Allocate buffer to track faults on a per-node basis */
2418 if (unlikely(!p
->numa_faults
)) {
2419 int size
= sizeof(*p
->numa_faults
) *
2420 NR_NUMA_HINT_FAULT_BUCKETS
* nr_node_ids
;
2422 p
->numa_faults
= kzalloc(size
, GFP_KERNEL
|__GFP_NOWARN
);
2423 if (!p
->numa_faults
)
2426 p
->total_numa_faults
= 0;
2427 memset(p
->numa_faults_locality
, 0, sizeof(p
->numa_faults_locality
));
2431 * First accesses are treated as private, otherwise consider accesses
2432 * to be private if the accessing pid has not changed
2434 if (unlikely(last_cpupid
== (-1 & LAST_CPUPID_MASK
))) {
2437 priv
= cpupid_match_pid(p
, last_cpupid
);
2438 if (!priv
&& !(flags
& TNF_NO_GROUP
))
2439 task_numa_group(p
, last_cpupid
, flags
, &priv
);
2443 * If a workload spans multiple NUMA nodes, a shared fault that
2444 * occurs wholly within the set of nodes that the workload is
2445 * actively using should be counted as local. This allows the
2446 * scan rate to slow down when a workload has settled down.
2449 if (!priv
&& !local
&& ng
&& ng
->active_nodes
> 1 &&
2450 numa_is_active_node(cpu_node
, ng
) &&
2451 numa_is_active_node(mem_node
, ng
))
2454 task_numa_placement(p
);
2457 * Retry task to preferred node migration periodically, in case it
2458 * case it previously failed, or the scheduler moved us.
2460 if (time_after(jiffies
, p
->numa_migrate_retry
))
2461 numa_migrate_preferred(p
);
2464 p
->numa_pages_migrated
+= pages
;
2465 if (flags
& TNF_MIGRATE_FAIL
)
2466 p
->numa_faults_locality
[2] += pages
;
2468 p
->numa_faults
[task_faults_idx(NUMA_MEMBUF
, mem_node
, priv
)] += pages
;
2469 p
->numa_faults
[task_faults_idx(NUMA_CPUBUF
, cpu_node
, priv
)] += pages
;
2470 p
->numa_faults_locality
[local
] += pages
;
2473 static void reset_ptenuma_scan(struct task_struct
*p
)
2476 * We only did a read acquisition of the mmap sem, so
2477 * p->mm->numa_scan_seq is written to without exclusive access
2478 * and the update is not guaranteed to be atomic. That's not
2479 * much of an issue though, since this is just used for
2480 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2481 * expensive, to avoid any form of compiler optimizations:
2483 WRITE_ONCE(p
->mm
->numa_scan_seq
, READ_ONCE(p
->mm
->numa_scan_seq
) + 1);
2484 p
->mm
->numa_scan_offset
= 0;
2488 * The expensive part of numa migration is done from task_work context.
2489 * Triggered from task_tick_numa().
2491 void task_numa_work(struct callback_head
*work
)
2493 unsigned long migrate
, next_scan
, now
= jiffies
;
2494 struct task_struct
*p
= current
;
2495 struct mm_struct
*mm
= p
->mm
;
2496 u64 runtime
= p
->se
.sum_exec_runtime
;
2497 struct vm_area_struct
*vma
;
2498 unsigned long start
, end
;
2499 unsigned long nr_pte_updates
= 0;
2500 long pages
, virtpages
;
2502 SCHED_WARN_ON(p
!= container_of(work
, struct task_struct
, numa_work
));
2504 work
->next
= work
; /* protect against double add */
2506 * Who cares about NUMA placement when they're dying.
2508 * NOTE: make sure not to dereference p->mm before this check,
2509 * exit_task_work() happens _after_ exit_mm() so we could be called
2510 * without p->mm even though we still had it when we enqueued this
2513 if (p
->flags
& PF_EXITING
)
2516 if (!mm
->numa_next_scan
) {
2517 mm
->numa_next_scan
= now
+
2518 msecs_to_jiffies(sysctl_numa_balancing_scan_delay
);
2522 * Enforce maximal scan/migration frequency..
2524 migrate
= mm
->numa_next_scan
;
2525 if (time_before(now
, migrate
))
2528 if (p
->numa_scan_period
== 0) {
2529 p
->numa_scan_period_max
= task_scan_max(p
);
2530 p
->numa_scan_period
= task_scan_start(p
);
2533 next_scan
= now
+ msecs_to_jiffies(p
->numa_scan_period
);
2534 if (cmpxchg(&mm
->numa_next_scan
, migrate
, next_scan
) != migrate
)
2538 * Delay this task enough that another task of this mm will likely win
2539 * the next time around.
2541 p
->node_stamp
+= 2 * TICK_NSEC
;
2543 start
= mm
->numa_scan_offset
;
2544 pages
= sysctl_numa_balancing_scan_size
;
2545 pages
<<= 20 - PAGE_SHIFT
; /* MB in pages */
2546 virtpages
= pages
* 8; /* Scan up to this much virtual space */
2551 if (!down_read_trylock(&mm
->mmap_sem
))
2553 vma
= find_vma(mm
, start
);
2555 reset_ptenuma_scan(p
);
2559 for (; vma
; vma
= vma
->vm_next
) {
2560 if (!vma_migratable(vma
) || !vma_policy_mof(vma
) ||
2561 is_vm_hugetlb_page(vma
) || (vma
->vm_flags
& VM_MIXEDMAP
)) {
2566 * Shared library pages mapped by multiple processes are not
2567 * migrated as it is expected they are cache replicated. Avoid
2568 * hinting faults in read-only file-backed mappings or the vdso
2569 * as migrating the pages will be of marginal benefit.
2572 (vma
->vm_file
&& (vma
->vm_flags
& (VM_READ
|VM_WRITE
)) == (VM_READ
)))
2576 * Skip inaccessible VMAs to avoid any confusion between
2577 * PROT_NONE and NUMA hinting ptes
2579 if (!(vma
->vm_flags
& (VM_READ
| VM_EXEC
| VM_WRITE
)))
2583 start
= max(start
, vma
->vm_start
);
2584 end
= ALIGN(start
+ (pages
<< PAGE_SHIFT
), HPAGE_SIZE
);
2585 end
= min(end
, vma
->vm_end
);
2586 nr_pte_updates
= change_prot_numa(vma
, start
, end
);
2589 * Try to scan sysctl_numa_balancing_size worth of
2590 * hpages that have at least one present PTE that
2591 * is not already pte-numa. If the VMA contains
2592 * areas that are unused or already full of prot_numa
2593 * PTEs, scan up to virtpages, to skip through those
2597 pages
-= (end
- start
) >> PAGE_SHIFT
;
2598 virtpages
-= (end
- start
) >> PAGE_SHIFT
;
2601 if (pages
<= 0 || virtpages
<= 0)
2605 } while (end
!= vma
->vm_end
);
2610 * It is possible to reach the end of the VMA list but the last few
2611 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2612 * would find the !migratable VMA on the next scan but not reset the
2613 * scanner to the start so check it now.
2616 mm
->numa_scan_offset
= start
;
2618 reset_ptenuma_scan(p
);
2619 up_read(&mm
->mmap_sem
);
2622 * Make sure tasks use at least 32x as much time to run other code
2623 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2624 * Usually update_task_scan_period slows down scanning enough; on an
2625 * overloaded system we need to limit overhead on a per task basis.
2627 if (unlikely(p
->se
.sum_exec_runtime
!= runtime
)) {
2628 u64 diff
= p
->se
.sum_exec_runtime
- runtime
;
2629 p
->node_stamp
+= 32 * diff
;
2634 * Drive the periodic memory faults..
2636 void task_tick_numa(struct rq
*rq
, struct task_struct
*curr
)
2638 struct callback_head
*work
= &curr
->numa_work
;
2642 * We don't care about NUMA placement if we don't have memory.
2644 if (!curr
->mm
|| (curr
->flags
& PF_EXITING
) || work
->next
!= work
)
2648 * Using runtime rather than walltime has the dual advantage that
2649 * we (mostly) drive the selection from busy threads and that the
2650 * task needs to have done some actual work before we bother with
2653 now
= curr
->se
.sum_exec_runtime
;
2654 period
= (u64
)curr
->numa_scan_period
* NSEC_PER_MSEC
;
2656 if (now
> curr
->node_stamp
+ period
) {
2657 if (!curr
->node_stamp
)
2658 curr
->numa_scan_period
= task_scan_start(curr
);
2659 curr
->node_stamp
+= period
;
2661 if (!time_before(jiffies
, curr
->mm
->numa_next_scan
)) {
2662 init_task_work(work
, task_numa_work
); /* TODO: move this into sched_fork() */
2663 task_work_add(curr
, work
, true);
2669 static void task_tick_numa(struct rq
*rq
, struct task_struct
*curr
)
2673 static inline void account_numa_enqueue(struct rq
*rq
, struct task_struct
*p
)
2677 static inline void account_numa_dequeue(struct rq
*rq
, struct task_struct
*p
)
2681 #endif /* CONFIG_NUMA_BALANCING */
2684 account_entity_enqueue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
2686 update_load_add(&cfs_rq
->load
, se
->load
.weight
);
2687 if (!parent_entity(se
))
2688 update_load_add(&rq_of(cfs_rq
)->load
, se
->load
.weight
);
2690 if (entity_is_task(se
)) {
2691 struct rq
*rq
= rq_of(cfs_rq
);
2693 account_numa_enqueue(rq
, task_of(se
));
2694 list_add(&se
->group_node
, &rq
->cfs_tasks
);
2697 cfs_rq
->nr_running
++;
2701 account_entity_dequeue(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
2703 update_load_sub(&cfs_rq
->load
, se
->load
.weight
);
2704 if (!parent_entity(se
))
2705 update_load_sub(&rq_of(cfs_rq
)->load
, se
->load
.weight
);
2707 if (entity_is_task(se
)) {
2708 account_numa_dequeue(rq_of(cfs_rq
), task_of(se
));
2709 list_del_init(&se
->group_node
);
2712 cfs_rq
->nr_running
--;
2715 #ifdef CONFIG_FAIR_GROUP_SCHED
2717 static long calc_cfs_shares(struct cfs_rq
*cfs_rq
, struct task_group
*tg
)
2719 long tg_weight
, load
, shares
;
2722 * This really should be: cfs_rq->avg.load_avg, but instead we use
2723 * cfs_rq->load.weight, which is its upper bound. This helps ramp up
2724 * the shares for small weight interactive tasks.
2726 load
= scale_load_down(cfs_rq
->load
.weight
);
2728 tg_weight
= atomic_long_read(&tg
->load_avg
);
2730 /* Ensure tg_weight >= load */
2731 tg_weight
-= cfs_rq
->tg_load_avg_contrib
;
2734 shares
= (tg
->shares
* load
);
2736 shares
/= tg_weight
;
2739 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
2740 * of a group with small tg->shares value. It is a floor value which is
2741 * assigned as a minimum load.weight to the sched_entity representing
2742 * the group on a CPU.
2744 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
2745 * on an 8-core system with 8 tasks each runnable on one CPU shares has
2746 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
2747 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
2750 if (shares
< MIN_SHARES
)
2751 shares
= MIN_SHARES
;
2752 if (shares
> tg
->shares
)
2753 shares
= tg
->shares
;
2757 # else /* CONFIG_SMP */
2758 static inline long calc_cfs_shares(struct cfs_rq
*cfs_rq
, struct task_group
*tg
)
2762 # endif /* CONFIG_SMP */
2764 static void reweight_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
2765 unsigned long weight
)
2768 /* commit outstanding execution time */
2769 if (cfs_rq
->curr
== se
)
2770 update_curr(cfs_rq
);
2771 account_entity_dequeue(cfs_rq
, se
);
2774 update_load_set(&se
->load
, weight
);
2777 account_entity_enqueue(cfs_rq
, se
);
2780 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
);
2782 static void update_cfs_shares(struct sched_entity
*se
)
2784 struct cfs_rq
*cfs_rq
= group_cfs_rq(se
);
2785 struct task_group
*tg
;
2791 if (throttled_hierarchy(cfs_rq
))
2797 if (likely(se
->load
.weight
== tg
->shares
))
2800 shares
= calc_cfs_shares(cfs_rq
, tg
);
2802 reweight_entity(cfs_rq_of(se
), se
, shares
);
2805 #else /* CONFIG_FAIR_GROUP_SCHED */
2806 static inline void update_cfs_shares(struct sched_entity
*se
)
2809 #endif /* CONFIG_FAIR_GROUP_SCHED */
2811 static inline void cfs_rq_util_change(struct cfs_rq
*cfs_rq
)
2813 struct rq
*rq
= rq_of(cfs_rq
);
2815 if (&rq
->cfs
== cfs_rq
) {
2817 * There are a few boundary cases this might miss but it should
2818 * get called often enough that that should (hopefully) not be
2819 * a real problem -- added to that it only calls on the local
2820 * CPU, so if we enqueue remotely we'll miss an update, but
2821 * the next tick/schedule should update.
2823 * It will not get called when we go idle, because the idle
2824 * thread is a different class (!fair), nor will the utilization
2825 * number include things like RT tasks.
2827 * As is, the util number is not freq-invariant (we'd have to
2828 * implement arch_scale_freq_capacity() for that).
2832 cpufreq_update_util(rq
, 0);
2834 trace_sched_load_avg_cpu(cpu_of(rq
), cfs_rq
);
2842 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2844 static u64
decay_load(u64 val
, u64 n
)
2846 unsigned int local_n
;
2848 if (unlikely(n
> LOAD_AVG_PERIOD
* 63))
2851 /* after bounds checking we can collapse to 32-bit */
2855 * As y^PERIOD = 1/2, we can combine
2856 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2857 * With a look-up table which covers y^n (n<PERIOD)
2859 * To achieve constant time decay_load.
2861 if (unlikely(local_n
>= LOAD_AVG_PERIOD
)) {
2862 val
>>= local_n
/ LOAD_AVG_PERIOD
;
2863 local_n
%= LOAD_AVG_PERIOD
;
2866 val
= mul_u64_u32_shr(val
, runnable_avg_yN_inv
[local_n
], 32);
2870 static u32
__accumulate_pelt_segments(u64 periods
, u32 d1
, u32 d3
)
2872 u32 c1
, c2
, c3
= d3
; /* y^0 == 1 */
2877 c1
= decay_load((u64
)d1
, periods
);
2881 * c2 = 1024 \Sum y^n
2885 * = 1024 ( \Sum y^n - \Sum y^n - y^0 )
2888 c2
= LOAD_AVG_MAX
- decay_load(LOAD_AVG_MAX
, periods
) - 1024;
2890 return c1
+ c2
+ c3
;
2893 #define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)
2896 * Accumulate the three separate parts of the sum; d1 the remainder
2897 * of the last (incomplete) period, d2 the span of full periods and d3
2898 * the remainder of the (incomplete) current period.
2903 * |<->|<----------------->|<--->|
2904 * ... |---x---|------| ... |------|-----x (now)
2907 * u' = (u + d1) y^p + 1024 \Sum y^n + d3 y^0
2910 * = u y^p + (Step 1)
2913 * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2)
2916 static __always_inline u32
2917 accumulate_sum(u64 delta
, int cpu
, struct sched_avg
*sa
,
2918 unsigned long weight
, int running
, struct cfs_rq
*cfs_rq
)
2920 unsigned long scale_freq
, scale_cpu
;
2921 u32 contrib
= (u32
)delta
; /* p == 0 -> delta < 1024 */
2924 scale_freq
= arch_scale_freq_capacity(NULL
, cpu
);
2925 scale_cpu
= arch_scale_cpu_capacity(NULL
, cpu
);
2927 delta
+= sa
->period_contrib
;
2928 periods
= delta
/ 1024; /* A period is 1024us (~1ms) */
2931 * Step 1: decay old *_sum if we crossed period boundaries.
2934 sa
->load_sum
= decay_load(sa
->load_sum
, periods
);
2936 cfs_rq
->runnable_load_sum
=
2937 decay_load(cfs_rq
->runnable_load_sum
, periods
);
2939 sa
->util_sum
= decay_load((u64
)(sa
->util_sum
), periods
);
2945 contrib
= __accumulate_pelt_segments(periods
,
2946 1024 - sa
->period_contrib
, delta
);
2948 sa
->period_contrib
= delta
;
2950 contrib
= cap_scale(contrib
, scale_freq
);
2952 sa
->load_sum
+= weight
* contrib
;
2954 cfs_rq
->runnable_load_sum
+= weight
* contrib
;
2957 sa
->util_sum
+= contrib
* scale_cpu
;
2963 * We can represent the historical contribution to runnable average as the
2964 * coefficients of a geometric series. To do this we sub-divide our runnable
2965 * history into segments of approximately 1ms (1024us); label the segment that
2966 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2968 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2970 * (now) (~1ms ago) (~2ms ago)
2972 * Let u_i denote the fraction of p_i that the entity was runnable.
2974 * We then designate the fractions u_i as our co-efficients, yielding the
2975 * following representation of historical load:
2976 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2978 * We choose y based on the with of a reasonably scheduling period, fixing:
2981 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2982 * approximately half as much as the contribution to load within the last ms
2985 * When a period "rolls over" and we have new u_0`, multiplying the previous
2986 * sum again by y is sufficient to update:
2987 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2988 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2990 static __always_inline
int
2991 ___update_load_avg(u64 now
, int cpu
, struct sched_avg
*sa
,
2992 unsigned long weight
, int running
, struct cfs_rq
*cfs_rq
,
2993 struct rt_rq
*rt_rq
)
2997 delta
= now
- sa
->last_update_time
;
2999 * This should only happen when time goes backwards, which it
3000 * unfortunately does during sched clock init when we swap over to TSC.
3002 if ((s64
)delta
< 0) {
3003 sa
->last_update_time
= now
;
3008 * Use 1024ns as the unit of measurement since it's a reasonable
3009 * approximation of 1us and fast to compute.
3015 sa
->last_update_time
+= delta
<< 10;
3018 * running is a subset of runnable (weight) so running can't be set if
3019 * runnable is clear. But there are some corner cases where the current
3020 * se has been already dequeued but cfs_rq->curr still points to it.
3021 * This means that weight will be 0 but not running for a sched_entity
3022 * but also for a cfs_rq if the latter becomes idle. As an example,
3023 * this happens during idle_balance() which calls
3024 * update_blocked_averages()
3030 * Now we know we crossed measurement unit boundaries. The *_avg
3031 * accrues by two steps:
3033 * Step 1: accumulate *_sum since last_update_time. If we haven't
3034 * crossed period boundaries, finish.
3036 if (!accumulate_sum(delta
, cpu
, sa
, weight
, running
, cfs_rq
))
3040 * Step 2: update *_avg.
3042 sa
->load_avg
= div_u64(sa
->load_sum
, LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3044 cfs_rq
->runnable_load_avg
=
3045 div_u64(cfs_rq
->runnable_load_sum
, LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3047 sa
->util_avg
= sa
->util_sum
/ (LOAD_AVG_MAX
- 1024 + sa
->period_contrib
);
3050 trace_sched_load_cfs_rq(cfs_rq
);
3053 trace_sched_load_se(container_of(sa
, struct sched_entity
, avg
));
3055 trace_sched_load_rt_rq(cpu
, rt_rq
);
3062 __update_load_avg_blocked_se(u64 now
, int cpu
, struct sched_entity
*se
)
3064 return ___update_load_avg(now
, cpu
, &se
->avg
, 0, 0, NULL
, NULL
);
3068 __update_load_avg_se(u64 now
, int cpu
, struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3070 return ___update_load_avg(now
, cpu
, &se
->avg
,
3071 se
->on_rq
* scale_load_down(se
->load
.weight
),
3072 cfs_rq
->curr
== se
, NULL
, NULL
);
3076 __update_load_avg_cfs_rq(u64 now
, int cpu
, struct cfs_rq
*cfs_rq
)
3078 return ___update_load_avg(now
, cpu
, &cfs_rq
->avg
,
3079 scale_load_down(cfs_rq
->load
.weight
),
3080 cfs_rq
->curr
!= NULL
, cfs_rq
, NULL
);
3084 * Signed add and clamp on underflow.
3086 * Explicitly do a load-store to ensure the intermediate value never hits
3087 * memory. This allows lockless observations without ever seeing the negative
3090 #define add_positive(_ptr, _val) do { \
3091 typeof(_ptr) ptr = (_ptr); \
3092 typeof(_val) val = (_val); \
3093 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3097 if (val < 0 && res > var) \
3100 WRITE_ONCE(*ptr, res); \
3103 #ifdef CONFIG_FAIR_GROUP_SCHED
3105 * update_tg_load_avg - update the tg's load avg
3106 * @cfs_rq: the cfs_rq whose avg changed
3107 * @force: update regardless of how small the difference
3109 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3110 * However, because tg->load_avg is a global value there are performance
3113 * In order to avoid having to look at the other cfs_rq's, we use a
3114 * differential update where we store the last value we propagated. This in
3115 * turn allows skipping updates if the differential is 'small'.
3117 * Updating tg's load_avg is necessary before update_cfs_share().
3119 static inline void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
)
3121 long delta
= cfs_rq
->avg
.load_avg
- cfs_rq
->tg_load_avg_contrib
;
3124 * No need to update load_avg for root_task_group as it is not used.
3126 if (cfs_rq
->tg
== &root_task_group
)
3129 if (force
|| abs(delta
) > cfs_rq
->tg_load_avg_contrib
/ 64) {
3130 atomic_long_add(delta
, &cfs_rq
->tg
->load_avg
);
3131 cfs_rq
->tg_load_avg_contrib
= cfs_rq
->avg
.load_avg
;
3134 trace_sched_load_tg(cfs_rq
);
3138 * Called within set_task_rq() right before setting a task's cpu. The
3139 * caller only guarantees p->pi_lock is held; no other assumptions,
3140 * including the state of rq->lock, should be made.
3142 void set_task_rq_fair(struct sched_entity
*se
,
3143 struct cfs_rq
*prev
, struct cfs_rq
*next
)
3145 u64 p_last_update_time
;
3146 u64 n_last_update_time
;
3148 if (!sched_feat(ATTACH_AGE_LOAD
))
3152 * We are supposed to update the task to "current" time, then its up to
3153 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3154 * getting what current time is, so simply throw away the out-of-date
3155 * time. This will result in the wakee task is less decayed, but giving
3156 * the wakee more load sounds not bad.
3158 if (!(se
->avg
.last_update_time
&& prev
))
3161 #ifndef CONFIG_64BIT
3163 u64 p_last_update_time_copy
;
3164 u64 n_last_update_time_copy
;
3167 p_last_update_time_copy
= prev
->load_last_update_time_copy
;
3168 n_last_update_time_copy
= next
->load_last_update_time_copy
;
3172 p_last_update_time
= prev
->avg
.last_update_time
;
3173 n_last_update_time
= next
->avg
.last_update_time
;
3175 } while (p_last_update_time
!= p_last_update_time_copy
||
3176 n_last_update_time
!= n_last_update_time_copy
);
3179 p_last_update_time
= prev
->avg
.last_update_time
;
3180 n_last_update_time
= next
->avg
.last_update_time
;
3182 __update_load_avg_blocked_se(p_last_update_time
, cpu_of(rq_of(prev
)), se
);
3183 se
->avg
.last_update_time
= n_last_update_time
;
3186 /* Take into account change of utilization of a child task group */
3188 update_tg_cfs_util(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3190 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3191 long delta
= gcfs_rq
->avg
.util_avg
- se
->avg
.util_avg
;
3193 /* Nothing to update */
3197 /* Set new sched_entity's utilization */
3198 se
->avg
.util_avg
= gcfs_rq
->avg
.util_avg
;
3199 se
->avg
.util_sum
= se
->avg
.util_avg
* LOAD_AVG_MAX
;
3201 /* Update parent cfs_rq utilization */
3202 add_positive(&cfs_rq
->avg
.util_avg
, delta
);
3203 cfs_rq
->avg
.util_sum
= cfs_rq
->avg
.util_avg
* LOAD_AVG_MAX
;
3206 /* Take into account change of load of a child task group */
3208 update_tg_cfs_load(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3210 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3211 long delta
, load
= gcfs_rq
->avg
.load_avg
;
3214 * If the load of group cfs_rq is null, the load of the
3215 * sched_entity will also be null so we can skip the formula
3220 /* Get tg's load and ensure tg_load > 0 */
3221 tg_load
= atomic_long_read(&gcfs_rq
->tg
->load_avg
) + 1;
3223 /* Ensure tg_load >= load and updated with current load*/
3224 tg_load
-= gcfs_rq
->tg_load_avg_contrib
;
3228 * We need to compute a correction term in the case that the
3229 * task group is consuming more CPU than a task of equal
3230 * weight. A task with a weight equals to tg->shares will have
3231 * a load less or equal to scale_load_down(tg->shares).
3232 * Similarly, the sched_entities that represent the task group
3233 * at parent level, can't have a load higher than
3234 * scale_load_down(tg->shares). And the Sum of sched_entities'
3235 * load must be <= scale_load_down(tg->shares).
3237 if (tg_load
> scale_load_down(gcfs_rq
->tg
->shares
)) {
3238 /* scale gcfs_rq's load into tg's shares*/
3239 load
*= scale_load_down(gcfs_rq
->tg
->shares
);
3244 delta
= load
- se
->avg
.load_avg
;
3246 /* Nothing to update */
3250 /* Set new sched_entity's load */
3251 se
->avg
.load_avg
= load
;
3252 se
->avg
.load_sum
= se
->avg
.load_avg
* LOAD_AVG_MAX
;
3254 /* Update parent cfs_rq load */
3255 add_positive(&cfs_rq
->avg
.load_avg
, delta
);
3256 cfs_rq
->avg
.load_sum
= cfs_rq
->avg
.load_avg
* LOAD_AVG_MAX
;
3259 * If the sched_entity is already enqueued, we also have to update the
3260 * runnable load avg.
3263 /* Update parent cfs_rq runnable_load_avg */
3264 add_positive(&cfs_rq
->runnable_load_avg
, delta
);
3265 cfs_rq
->runnable_load_sum
= cfs_rq
->runnable_load_avg
* LOAD_AVG_MAX
;
3269 static inline void set_tg_cfs_propagate(struct cfs_rq
*cfs_rq
)
3271 cfs_rq
->propagate_avg
= 1;
3274 static inline int test_and_clear_tg_cfs_propagate(struct sched_entity
*se
)
3276 struct cfs_rq
*cfs_rq
= group_cfs_rq(se
);
3278 if (!cfs_rq
->propagate_avg
)
3281 cfs_rq
->propagate_avg
= 0;
3285 /* Update task and its cfs_rq load average */
3286 static inline int propagate_entity_load_avg(struct sched_entity
*se
)
3288 struct cfs_rq
*cfs_rq
;
3290 if (entity_is_task(se
))
3293 if (!test_and_clear_tg_cfs_propagate(se
))
3296 cfs_rq
= cfs_rq_of(se
);
3298 set_tg_cfs_propagate(cfs_rq
);
3300 update_tg_cfs_util(cfs_rq
, se
);
3301 update_tg_cfs_load(cfs_rq
, se
);
3303 trace_sched_load_cfs_rq(cfs_rq
);
3304 trace_sched_load_se(se
);
3310 * Check if we need to update the load and the utilization of a blocked
3313 static inline bool skip_blocked_update(struct sched_entity
*se
)
3315 struct cfs_rq
*gcfs_rq
= group_cfs_rq(se
);
3318 * If sched_entity still have not zero load or utilization, we have to
3321 if (se
->avg
.load_avg
|| se
->avg
.util_avg
)
3325 * If there is a pending propagation, we have to update the load and
3326 * the utilization of the sched_entity:
3328 if (gcfs_rq
->propagate_avg
)
3332 * Otherwise, the load and the utilization of the sched_entity is
3333 * already zero and there is no pending propagation, so it will be a
3334 * waste of time to try to decay it:
3339 #else /* CONFIG_FAIR_GROUP_SCHED */
3341 static inline void update_tg_load_avg(struct cfs_rq
*cfs_rq
, int force
) {}
3343 static inline int propagate_entity_load_avg(struct sched_entity
*se
)
3348 static inline void set_tg_cfs_propagate(struct cfs_rq
*cfs_rq
) {}
3350 #endif /* CONFIG_FAIR_GROUP_SCHED */
3353 * Unsigned subtract and clamp on underflow.
3355 * Explicitly do a load-store to ensure the intermediate value never hits
3356 * memory. This allows lockless observations without ever seeing the negative
3359 #define sub_positive(_ptr, _val) do { \
3360 typeof(_ptr) ptr = (_ptr); \
3361 typeof(*ptr) val = (_val); \
3362 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3366 WRITE_ONCE(*ptr, res); \
3370 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3371 * @now: current time, as per cfs_rq_clock_task()
3372 * @cfs_rq: cfs_rq to update
3374 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3375 * avg. The immediate corollary is that all (fair) tasks must be attached, see
3376 * post_init_entity_util_avg().
3378 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3380 * Returns true if the load decayed or we removed load.
3382 * Since both these conditions indicate a changed cfs_rq->avg.load we should
3383 * call update_tg_load_avg() when this function returns true.
3386 update_cfs_rq_load_avg(u64 now
, struct cfs_rq
*cfs_rq
)
3388 struct sched_avg
*sa
= &cfs_rq
->avg
;
3389 int decayed
, removed_load
= 0, removed_util
= 0;
3391 if (atomic_long_read(&cfs_rq
->removed_load_avg
)) {
3392 s64 r
= atomic_long_xchg(&cfs_rq
->removed_load_avg
, 0);
3393 sub_positive(&sa
->load_avg
, r
);
3394 sub_positive(&sa
->load_sum
, r
* LOAD_AVG_MAX
);
3396 set_tg_cfs_propagate(cfs_rq
);
3399 if (atomic_long_read(&cfs_rq
->removed_util_avg
)) {
3400 long r
= atomic_long_xchg(&cfs_rq
->removed_util_avg
, 0);
3401 sub_positive(&sa
->util_avg
, r
);
3402 sub_positive(&sa
->util_sum
, r
* LOAD_AVG_MAX
);
3404 set_tg_cfs_propagate(cfs_rq
);
3407 decayed
= __update_load_avg_cfs_rq(now
, cpu_of(rq_of(cfs_rq
)), cfs_rq
);
3409 #ifndef CONFIG_64BIT
3411 cfs_rq
->load_last_update_time_copy
= sa
->last_update_time
;
3414 if (decayed
|| removed_util
)
3415 cfs_rq_util_change(cfs_rq
);
3417 return decayed
|| removed_load
;
3420 int update_rt_rq_load_avg(u64 now
, int cpu
, struct rt_rq
*rt_rq
, int running
)
3424 ret
= ___update_load_avg(now
, cpu
, &rt_rq
->avg
, 0, running
, NULL
, rt_rq
);
3429 unsigned long sched_get_rt_rq_util(int cpu
)
3431 struct rt_rq
*rt_rq
= &(cpu_rq(cpu
)->rt
);
3432 return rt_rq
->avg
.util_avg
;
3436 * Optional action to be done while updating the load average
3438 #define UPDATE_TG 0x1
3439 #define SKIP_AGE_LOAD 0x2
3441 /* Update task and its cfs_rq load average */
3442 static inline void update_load_avg(struct sched_entity
*se
, int flags
)
3444 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3445 u64 now
= cfs_rq_clock_task(cfs_rq
);
3446 struct rq
*rq
= rq_of(cfs_rq
);
3447 int cpu
= cpu_of(rq
);
3451 * Track task load average for carrying it to new CPU after migrated, and
3452 * track group sched_entity load average for task_h_load calc in migration
3454 if (se
->avg
.last_update_time
&& !(flags
& SKIP_AGE_LOAD
))
3455 __update_load_avg_se(now
, cpu
, cfs_rq
, se
);
3457 decayed
= update_cfs_rq_load_avg(now
, cfs_rq
);
3458 decayed
|= propagate_entity_load_avg(se
);
3460 if (decayed
&& (flags
& UPDATE_TG
))
3461 update_tg_load_avg(cfs_rq
, 0);
3465 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3466 * @cfs_rq: cfs_rq to attach to
3467 * @se: sched_entity to attach
3469 * Must call update_cfs_rq_load_avg() before this, since we rely on
3470 * cfs_rq->avg.last_update_time being current.
3472 static void attach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3474 se
->avg
.last_update_time
= cfs_rq
->avg
.last_update_time
;
3475 cfs_rq
->avg
.load_avg
+= se
->avg
.load_avg
;
3476 cfs_rq
->avg
.load_sum
+= se
->avg
.load_sum
;
3477 cfs_rq
->avg
.util_avg
+= se
->avg
.util_avg
;
3478 cfs_rq
->avg
.util_sum
+= se
->avg
.util_sum
;
3479 set_tg_cfs_propagate(cfs_rq
);
3481 cfs_rq_util_change(cfs_rq
);
3483 trace_sched_load_cfs_rq(cfs_rq
);
3487 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3488 * @cfs_rq: cfs_rq to detach from
3489 * @se: sched_entity to detach
3491 * Must call update_cfs_rq_load_avg() before this, since we rely on
3492 * cfs_rq->avg.last_update_time being current.
3494 static void detach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3497 sub_positive(&cfs_rq
->avg
.load_avg
, se
->avg
.load_avg
);
3498 sub_positive(&cfs_rq
->avg
.load_sum
, se
->avg
.load_sum
);
3499 sub_positive(&cfs_rq
->avg
.util_avg
, se
->avg
.util_avg
);
3500 sub_positive(&cfs_rq
->avg
.util_sum
, se
->avg
.util_sum
);
3501 set_tg_cfs_propagate(cfs_rq
);
3503 cfs_rq_util_change(cfs_rq
);
3505 trace_sched_load_cfs_rq(cfs_rq
);
3508 /* Add the load generated by se into cfs_rq's load average */
3510 enqueue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3512 struct sched_avg
*sa
= &se
->avg
;
3514 cfs_rq
->runnable_load_avg
+= sa
->load_avg
;
3515 cfs_rq
->runnable_load_sum
+= sa
->load_sum
;
3517 if (!sa
->last_update_time
) {
3518 attach_entity_load_avg(cfs_rq
, se
);
3519 update_tg_load_avg(cfs_rq
, 0);
3523 /* Remove the runnable load generated by se from cfs_rq's runnable load average */
3525 dequeue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3527 cfs_rq
->runnable_load_avg
=
3528 max_t(long, cfs_rq
->runnable_load_avg
- se
->avg
.load_avg
, 0);
3529 cfs_rq
->runnable_load_sum
=
3530 max_t(s64
, cfs_rq
->runnable_load_sum
- se
->avg
.load_sum
, 0);
3533 #ifndef CONFIG_64BIT
3534 static inline u64
cfs_rq_last_update_time(struct cfs_rq
*cfs_rq
)
3536 u64 last_update_time_copy
;
3537 u64 last_update_time
;
3540 last_update_time_copy
= cfs_rq
->load_last_update_time_copy
;
3542 last_update_time
= cfs_rq
->avg
.last_update_time
;
3543 } while (last_update_time
!= last_update_time_copy
);
3545 return last_update_time
;
3548 static inline u64
cfs_rq_last_update_time(struct cfs_rq
*cfs_rq
)
3550 return cfs_rq
->avg
.last_update_time
;
3555 * Synchronize entity load avg of dequeued entity without locking
3558 void sync_entity_load_avg(struct sched_entity
*se
)
3560 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3561 u64 last_update_time
;
3563 last_update_time
= cfs_rq_last_update_time(cfs_rq
);
3564 __update_load_avg_blocked_se(last_update_time
, cpu_of(rq_of(cfs_rq
)), se
);
3568 * Task first catches up with cfs_rq, and then subtract
3569 * itself from the cfs_rq (task must be off the queue now).
3571 void remove_entity_load_avg(struct sched_entity
*se
)
3573 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3576 * tasks cannot exit without having gone through wake_up_new_task() ->
3577 * post_init_entity_util_avg() which will have added things to the
3578 * cfs_rq, so we can remove unconditionally.
3580 * Similarly for groups, they will have passed through
3581 * post_init_entity_util_avg() before unregister_sched_fair_group()
3585 sync_entity_load_avg(se
);
3586 atomic_long_add(se
->avg
.load_avg
, &cfs_rq
->removed_load_avg
);
3587 atomic_long_add(se
->avg
.util_avg
, &cfs_rq
->removed_util_avg
);
3590 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq
*cfs_rq
)
3592 return cfs_rq
->runnable_load_avg
;
3595 static inline unsigned long cfs_rq_load_avg(struct cfs_rq
*cfs_rq
)
3597 return cfs_rq
->avg
.load_avg
;
3600 static int idle_balance(struct rq
*this_rq
, struct rq_flags
*rf
);
3602 static inline int task_fits_capacity(struct task_struct
*p
, long capacity
);
3604 static inline void update_misfit_status(struct task_struct
*p
, struct rq
*rq
)
3606 if (!static_branch_unlikely(&sched_asym_cpucapacity
))
3610 rq
->misfit_task_load
= 0;
3614 if (task_fits_capacity(p
, capacity_of(cpu_of(rq
)))) {
3615 rq
->misfit_task_load
= 0;
3619 rq
->misfit_task_load
= task_h_load(p
);
3622 #else /* CONFIG_SMP */
3625 update_cfs_rq_load_avg(u64 now
, struct cfs_rq
*cfs_rq
)
3630 int update_rt_rq_load_avg(u64 now
, int cpu
, struct rt_rq
*rt_rq
, int running
)
3635 #define UPDATE_TG 0x0
3636 #define SKIP_AGE_LOAD 0x0
3638 static inline void update_load_avg(struct sched_entity
*se
, int not_used1
)
3640 cfs_rq_util_change(cfs_rq_of(se
));
3644 enqueue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3646 dequeue_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3647 static inline void remove_entity_load_avg(struct sched_entity
*se
) {}
3650 attach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3652 detach_entity_load_avg(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
) {}
3654 static inline int idle_balance(struct rq
*rq
, struct rq_flags
*rf
)
3659 static inline void update_misfit_status(struct task_struct
*p
, struct rq
*rq
) {}
3661 #endif /* CONFIG_SMP */
3663 static void check_spread(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3665 #ifdef CONFIG_SCHED_DEBUG
3666 s64 d
= se
->vruntime
- cfs_rq
->min_vruntime
;
3671 if (d
> 3*sysctl_sched_latency
)
3672 schedstat_inc(cfs_rq
->nr_spread_over
);
3677 place_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int initial
)
3679 u64 vruntime
= cfs_rq
->min_vruntime
;
3682 * The 'current' period is already promised to the current tasks,
3683 * however the extra weight of the new task will slow them down a
3684 * little, place the new task so that it fits in the slot that
3685 * stays open at the end.
3687 if (initial
&& sched_feat(START_DEBIT
))
3688 vruntime
+= sched_vslice(cfs_rq
, se
);
3690 /* sleeps up to a single latency don't count. */
3692 unsigned long thresh
= sysctl_sched_latency
;
3695 * Halve their sleep time's effect, to allow
3696 * for a gentler effect of sleepers:
3698 if (sched_feat(GENTLE_FAIR_SLEEPERS
))
3704 /* ensure we never gain time by being placed backwards. */
3705 se
->vruntime
= max_vruntime(se
->vruntime
, vruntime
);
3708 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
);
3710 static inline void check_schedstat_required(void)
3712 #ifdef CONFIG_SCHEDSTATS
3713 if (schedstat_enabled())
3716 /* Force schedstat enabled if a dependent tracepoint is active */
3717 if (trace_sched_stat_wait_enabled() ||
3718 trace_sched_stat_sleep_enabled() ||
3719 trace_sched_stat_iowait_enabled() ||
3720 trace_sched_stat_blocked_enabled() ||
3721 trace_sched_stat_runtime_enabled()) {
3722 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
3723 "stat_blocked and stat_runtime require the "
3724 "kernel parameter schedstats=enable or "
3725 "kernel.sched_schedstats=1\n");
3736 * update_min_vruntime()
3737 * vruntime -= min_vruntime
3741 * update_min_vruntime()
3742 * vruntime += min_vruntime
3744 * this way the vruntime transition between RQs is done when both
3745 * min_vruntime are up-to-date.
3749 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
3750 * vruntime -= min_vruntime
3754 * update_min_vruntime()
3755 * vruntime += min_vruntime
3757 * this way we don't have the most up-to-date min_vruntime on the originating
3758 * CPU and an up-to-date min_vruntime on the destination CPU.
3762 enqueue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
3764 bool renorm
= !(flags
& ENQUEUE_WAKEUP
) || (flags
& ENQUEUE_MIGRATED
);
3765 bool curr
= cfs_rq
->curr
== se
;
3768 * If we're the current task, we must renormalise before calling
3772 se
->vruntime
+= cfs_rq
->min_vruntime
;
3774 update_curr(cfs_rq
);
3777 * Otherwise, renormalise after, such that we're placed at the current
3778 * moment in time, instead of some random moment in the past. Being
3779 * placed in the past could significantly boost this task to the
3780 * fairness detriment of existing tasks.
3782 if (renorm
&& !curr
)
3783 se
->vruntime
+= cfs_rq
->min_vruntime
;
3786 * When enqueuing a sched_entity, we must:
3787 * - Update loads to have both entity and cfs_rq synced with now.
3788 * - Add its load to cfs_rq->runnable_avg
3789 * - For group_entity, update its weight to reflect the new share of
3791 * - Add its new weight to cfs_rq->load.weight
3793 update_load_avg(se
, UPDATE_TG
);
3794 enqueue_entity_load_avg(cfs_rq
, se
);
3795 update_cfs_shares(se
);
3796 account_entity_enqueue(cfs_rq
, se
);
3798 if (flags
& ENQUEUE_WAKEUP
)
3799 place_entity(cfs_rq
, se
, 0);
3801 check_schedstat_required();
3802 update_stats_enqueue(cfs_rq
, se
, flags
);
3803 check_spread(cfs_rq
, se
);
3805 __enqueue_entity(cfs_rq
, se
);
3808 if (cfs_rq
->nr_running
== 1) {
3809 list_add_leaf_cfs_rq(cfs_rq
);
3810 check_enqueue_throttle(cfs_rq
);
3814 static void __clear_buddies_last(struct sched_entity
*se
)
3816 for_each_sched_entity(se
) {
3817 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3818 if (cfs_rq
->last
!= se
)
3821 cfs_rq
->last
= NULL
;
3825 static void __clear_buddies_next(struct sched_entity
*se
)
3827 for_each_sched_entity(se
) {
3828 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3829 if (cfs_rq
->next
!= se
)
3832 cfs_rq
->next
= NULL
;
3836 static void __clear_buddies_skip(struct sched_entity
*se
)
3838 for_each_sched_entity(se
) {
3839 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
3840 if (cfs_rq
->skip
!= se
)
3843 cfs_rq
->skip
= NULL
;
3847 static void clear_buddies(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3849 if (cfs_rq
->last
== se
)
3850 __clear_buddies_last(se
);
3852 if (cfs_rq
->next
== se
)
3853 __clear_buddies_next(se
);
3855 if (cfs_rq
->skip
== se
)
3856 __clear_buddies_skip(se
);
3859 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
);
3862 dequeue_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
, int flags
)
3865 * Update run-time statistics of the 'current'.
3867 update_curr(cfs_rq
);
3870 * When dequeuing a sched_entity, we must:
3871 * - Update loads to have both entity and cfs_rq synced with now.
3872 * - Substract its load from the cfs_rq->runnable_avg.
3873 * - Substract its previous weight from cfs_rq->load.weight.
3874 * - For group entity, update its weight to reflect the new share
3875 * of its group cfs_rq.
3877 update_load_avg(se
, UPDATE_TG
);
3878 dequeue_entity_load_avg(cfs_rq
, se
);
3880 update_stats_dequeue(cfs_rq
, se
, flags
);
3882 clear_buddies(cfs_rq
, se
);
3884 if (se
!= cfs_rq
->curr
)
3885 __dequeue_entity(cfs_rq
, se
);
3887 account_entity_dequeue(cfs_rq
, se
);
3890 * Normalize after update_curr(); which will also have moved
3891 * min_vruntime if @se is the one holding it back. But before doing
3892 * update_min_vruntime() again, which will discount @se's position and
3893 * can move min_vruntime forward still more.
3895 if (!(flags
& DEQUEUE_SLEEP
))
3896 se
->vruntime
-= cfs_rq
->min_vruntime
;
3898 /* return excess runtime on last dequeue */
3899 return_cfs_rq_runtime(cfs_rq
);
3901 update_cfs_shares(se
);
3904 * Now advance min_vruntime if @se was the entity holding it back,
3905 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
3906 * put back on, and if we advance min_vruntime, we'll be placed back
3907 * further than we started -- ie. we'll be penalized.
3909 if ((flags
& (DEQUEUE_SAVE
| DEQUEUE_MOVE
)) == DEQUEUE_SAVE
)
3910 update_min_vruntime(cfs_rq
);
3914 * Preempt the current task with a newly woken task if needed:
3917 check_preempt_tick(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
)
3919 unsigned long ideal_runtime
, delta_exec
;
3920 struct sched_entity
*se
;
3923 ideal_runtime
= sched_slice(cfs_rq
, curr
);
3924 delta_exec
= curr
->sum_exec_runtime
- curr
->prev_sum_exec_runtime
;
3925 if (delta_exec
> ideal_runtime
) {
3926 resched_curr(rq_of(cfs_rq
));
3928 * The current task ran long enough, ensure it doesn't get
3929 * re-elected due to buddy favours.
3931 clear_buddies(cfs_rq
, curr
);
3936 * Ensure that a task that missed wakeup preemption by a
3937 * narrow margin doesn't have to wait for a full slice.
3938 * This also mitigates buddy induced latencies under load.
3940 if (delta_exec
< sysctl_sched_min_granularity
)
3943 se
= __pick_first_entity(cfs_rq
);
3944 delta
= curr
->vruntime
- se
->vruntime
;
3949 if (delta
> ideal_runtime
)
3950 resched_curr(rq_of(cfs_rq
));
3954 set_next_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*se
)
3956 /* 'current' is not kept within the tree. */
3959 * Any task has to be enqueued before it get to execute on
3960 * a CPU. So account for the time it spent waiting on the
3963 update_stats_wait_end(cfs_rq
, se
);
3964 __dequeue_entity(cfs_rq
, se
);
3965 update_load_avg(se
, UPDATE_TG
);
3968 update_stats_curr_start(cfs_rq
, se
);
3972 * Track our maximum slice length, if the CPU's load is at
3973 * least twice that of our own weight (i.e. dont track it
3974 * when there are only lesser-weight tasks around):
3976 if (schedstat_enabled() && rq_of(cfs_rq
)->load
.weight
>= 2*se
->load
.weight
) {
3977 schedstat_set(se
->statistics
.slice_max
,
3978 max((u64
)schedstat_val(se
->statistics
.slice_max
),
3979 se
->sum_exec_runtime
- se
->prev_sum_exec_runtime
));
3982 se
->prev_sum_exec_runtime
= se
->sum_exec_runtime
;
3986 wakeup_preempt_entity(struct sched_entity
*curr
, struct sched_entity
*se
);
3989 * Pick the next process, keeping these things in mind, in this order:
3990 * 1) keep things fair between processes/task groups
3991 * 2) pick the "next" process, since someone really wants that to run
3992 * 3) pick the "last" process, for cache locality
3993 * 4) do not run the "skip" process, if something else is available
3995 static struct sched_entity
*
3996 pick_next_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
)
3998 struct sched_entity
*left
= __pick_first_entity(cfs_rq
);
3999 struct sched_entity
*se
;
4002 * If curr is set we have to see if its left of the leftmost entity
4003 * still in the tree, provided there was anything in the tree at all.
4005 if (!left
|| (curr
&& entity_before(curr
, left
)))
4008 se
= left
; /* ideally we run the leftmost entity */
4011 * Avoid running the skip buddy, if running something else can
4012 * be done without getting too unfair.
4014 if (cfs_rq
->skip
== se
) {
4015 struct sched_entity
*second
;
4018 second
= __pick_first_entity(cfs_rq
);
4020 second
= __pick_next_entity(se
);
4021 if (!second
|| (curr
&& entity_before(curr
, second
)))
4025 if (second
&& wakeup_preempt_entity(second
, left
) < 1)
4030 * Prefer last buddy, try to return the CPU to a preempted task.
4032 if (cfs_rq
->last
&& wakeup_preempt_entity(cfs_rq
->last
, left
) < 1)
4036 * Someone really wants this to run. If it's not unfair, run it.
4038 if (cfs_rq
->next
&& wakeup_preempt_entity(cfs_rq
->next
, left
) < 1)
4041 clear_buddies(cfs_rq
, se
);
4046 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
);
4048 static void put_prev_entity(struct cfs_rq
*cfs_rq
, struct sched_entity
*prev
)
4051 * If still on the runqueue then deactivate_task()
4052 * was not called and update_curr() has to be done:
4055 update_curr(cfs_rq
);
4057 /* throttle cfs_rqs exceeding runtime */
4058 check_cfs_rq_runtime(cfs_rq
);
4060 check_spread(cfs_rq
, prev
);
4063 update_stats_wait_start(cfs_rq
, prev
);
4064 /* Put 'current' back into the tree. */
4065 __enqueue_entity(cfs_rq
, prev
);
4066 /* in !on_rq case, update occurred at dequeue */
4067 update_load_avg(prev
, 0);
4069 cfs_rq
->curr
= NULL
;
4073 entity_tick(struct cfs_rq
*cfs_rq
, struct sched_entity
*curr
, int queued
)
4076 * Update run-time statistics of the 'current'.
4078 update_curr(cfs_rq
);
4081 * Ensure that runnable average is periodically updated.
4083 update_load_avg(curr
, UPDATE_TG
);
4084 update_cfs_shares(curr
);
4086 #ifdef CONFIG_SCHED_HRTICK
4088 * queued ticks are scheduled to match the slice, so don't bother
4089 * validating it and just reschedule.
4092 resched_curr(rq_of(cfs_rq
));
4096 * don't let the period tick interfere with the hrtick preemption
4098 if (!sched_feat(DOUBLE_TICK
) &&
4099 hrtimer_active(&rq_of(cfs_rq
)->hrtick_timer
))
4103 if (cfs_rq
->nr_running
> 1)
4104 check_preempt_tick(cfs_rq
, curr
);
4108 /**************************************************
4109 * CFS bandwidth control machinery
4112 #ifdef CONFIG_CFS_BANDWIDTH
4114 #ifdef HAVE_JUMP_LABEL
4115 static struct static_key __cfs_bandwidth_used
;
4117 static inline bool cfs_bandwidth_used(void)
4119 return static_key_false(&__cfs_bandwidth_used
);
4122 void cfs_bandwidth_usage_inc(void)
4124 static_key_slow_inc(&__cfs_bandwidth_used
);
4127 void cfs_bandwidth_usage_dec(void)
4129 static_key_slow_dec(&__cfs_bandwidth_used
);
4131 #else /* HAVE_JUMP_LABEL */
4132 static bool cfs_bandwidth_used(void)
4137 void cfs_bandwidth_usage_inc(void) {}
4138 void cfs_bandwidth_usage_dec(void) {}
4139 #endif /* HAVE_JUMP_LABEL */
4142 * default period for cfs group bandwidth.
4143 * default: 0.1s, units: nanoseconds
4145 static inline u64
default_cfs_period(void)
4147 return 100000000ULL;
4150 static inline u64
sched_cfs_bandwidth_slice(void)
4152 return (u64
)sysctl_sched_cfs_bandwidth_slice
* NSEC_PER_USEC
;
4156 * Replenish runtime according to assigned quota and update expiration time.
4157 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
4158 * additional synchronization around rq->lock.
4160 * requires cfs_b->lock
4162 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth
*cfs_b
)
4166 if (cfs_b
->quota
== RUNTIME_INF
)
4169 now
= sched_clock_cpu(smp_processor_id());
4170 cfs_b
->runtime
= cfs_b
->quota
;
4171 cfs_b
->runtime_expires
= now
+ ktime_to_ns(cfs_b
->period
);
4174 static inline struct cfs_bandwidth
*tg_cfs_bandwidth(struct task_group
*tg
)
4176 return &tg
->cfs_bandwidth
;
4179 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
4180 static inline u64
cfs_rq_clock_task(struct cfs_rq
*cfs_rq
)
4182 if (unlikely(cfs_rq
->throttle_count
))
4183 return cfs_rq
->throttled_clock_task
- cfs_rq
->throttled_clock_task_time
;
4185 return rq_clock_task(rq_of(cfs_rq
)) - cfs_rq
->throttled_clock_task_time
;
4188 /* returns 0 on failure to allocate runtime */
4189 static int assign_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4191 struct task_group
*tg
= cfs_rq
->tg
;
4192 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(tg
);
4193 u64 amount
= 0, min_amount
, expires
;
4195 /* note: this is a positive sum as runtime_remaining <= 0 */
4196 min_amount
= sched_cfs_bandwidth_slice() - cfs_rq
->runtime_remaining
;
4198 raw_spin_lock(&cfs_b
->lock
);
4199 if (cfs_b
->quota
== RUNTIME_INF
)
4200 amount
= min_amount
;
4202 start_cfs_bandwidth(cfs_b
);
4204 if (cfs_b
->runtime
> 0) {
4205 amount
= min(cfs_b
->runtime
, min_amount
);
4206 cfs_b
->runtime
-= amount
;
4210 expires
= cfs_b
->runtime_expires
;
4211 raw_spin_unlock(&cfs_b
->lock
);
4213 cfs_rq
->runtime_remaining
+= amount
;
4215 * we may have advanced our local expiration to account for allowed
4216 * spread between our sched_clock and the one on which runtime was
4219 if ((s64
)(expires
- cfs_rq
->runtime_expires
) > 0)
4220 cfs_rq
->runtime_expires
= expires
;
4222 return cfs_rq
->runtime_remaining
> 0;
4226 * Note: This depends on the synchronization provided by sched_clock and the
4227 * fact that rq->clock snapshots this value.
4229 static void expire_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4231 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4233 /* if the deadline is ahead of our clock, nothing to do */
4234 if (likely((s64
)(rq_clock(rq_of(cfs_rq
)) - cfs_rq
->runtime_expires
) < 0))
4237 if (cfs_rq
->runtime_remaining
< 0)
4241 * If the local deadline has passed we have to consider the
4242 * possibility that our sched_clock is 'fast' and the global deadline
4243 * has not truly expired.
4245 * Fortunately we can check determine whether this the case by checking
4246 * whether the global deadline has advanced. It is valid to compare
4247 * cfs_b->runtime_expires without any locks since we only care about
4248 * exact equality, so a partial write will still work.
4251 if (cfs_rq
->runtime_expires
!= cfs_b
->runtime_expires
) {
4252 /* extend local deadline, drift is bounded above by 2 ticks */
4253 cfs_rq
->runtime_expires
+= TICK_NSEC
;
4255 /* global deadline is ahead, expiration has passed */
4256 cfs_rq
->runtime_remaining
= 0;
4260 static void __account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
)
4262 /* dock delta_exec before expiring quota (as it could span periods) */
4263 cfs_rq
->runtime_remaining
-= delta_exec
;
4264 expire_cfs_rq_runtime(cfs_rq
);
4266 if (likely(cfs_rq
->runtime_remaining
> 0))
4270 * if we're unable to extend our runtime we resched so that the active
4271 * hierarchy can be throttled
4273 if (!assign_cfs_rq_runtime(cfs_rq
) && likely(cfs_rq
->curr
))
4274 resched_curr(rq_of(cfs_rq
));
4277 static __always_inline
4278 void account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
)
4280 if (!cfs_bandwidth_used() || !cfs_rq
->runtime_enabled
)
4283 __account_cfs_rq_runtime(cfs_rq
, delta_exec
);
4286 static inline int cfs_rq_throttled(struct cfs_rq
*cfs_rq
)
4288 return cfs_bandwidth_used() && cfs_rq
->throttled
;
4291 /* check whether cfs_rq, or any parent, is throttled */
4292 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
)
4294 return cfs_bandwidth_used() && cfs_rq
->throttle_count
;
4298 * Ensure that neither of the group entities corresponding to src_cpu or
4299 * dest_cpu are members of a throttled hierarchy when performing group
4300 * load-balance operations.
4302 static inline int throttled_lb_pair(struct task_group
*tg
,
4303 int src_cpu
, int dest_cpu
)
4305 struct cfs_rq
*src_cfs_rq
, *dest_cfs_rq
;
4307 src_cfs_rq
= tg
->cfs_rq
[src_cpu
];
4308 dest_cfs_rq
= tg
->cfs_rq
[dest_cpu
];
4310 return throttled_hierarchy(src_cfs_rq
) ||
4311 throttled_hierarchy(dest_cfs_rq
);
4314 /* updated child weight may affect parent so we have to do this bottom up */
4315 static int tg_unthrottle_up(struct task_group
*tg
, void *data
)
4317 struct rq
*rq
= data
;
4318 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4320 cfs_rq
->throttle_count
--;
4321 if (!cfs_rq
->throttle_count
) {
4322 /* adjust cfs_rq_clock_task() */
4323 cfs_rq
->throttled_clock_task_time
+= rq_clock_task(rq
) -
4324 cfs_rq
->throttled_clock_task
;
4330 static int tg_throttle_down(struct task_group
*tg
, void *data
)
4332 struct rq
*rq
= data
;
4333 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4335 /* group is entering throttled state, stop time */
4336 if (!cfs_rq
->throttle_count
)
4337 cfs_rq
->throttled_clock_task
= rq_clock_task(rq
);
4338 cfs_rq
->throttle_count
++;
4343 static void throttle_cfs_rq(struct cfs_rq
*cfs_rq
)
4345 struct rq
*rq
= rq_of(cfs_rq
);
4346 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4347 struct sched_entity
*se
;
4348 long task_delta
, dequeue
= 1;
4351 se
= cfs_rq
->tg
->se
[cpu_of(rq_of(cfs_rq
))];
4353 /* freeze hierarchy runnable averages while throttled */
4355 walk_tg_tree_from(cfs_rq
->tg
, tg_throttle_down
, tg_nop
, (void *)rq
);
4358 task_delta
= cfs_rq
->h_nr_running
;
4359 for_each_sched_entity(se
) {
4360 struct cfs_rq
*qcfs_rq
= cfs_rq_of(se
);
4361 /* throttled entity or throttle-on-deactivate */
4366 dequeue_entity(qcfs_rq
, se
, DEQUEUE_SLEEP
);
4367 qcfs_rq
->h_nr_running
-= task_delta
;
4369 if (qcfs_rq
->load
.weight
)
4374 sub_nr_running(rq
, task_delta
);
4376 cfs_rq
->throttled
= 1;
4377 cfs_rq
->throttled_clock
= rq_clock(rq
);
4378 raw_spin_lock(&cfs_b
->lock
);
4379 empty
= list_empty(&cfs_b
->throttled_cfs_rq
);
4382 * Add to the _head_ of the list, so that an already-started
4383 * distribute_cfs_runtime will not see us
4385 list_add_rcu(&cfs_rq
->throttled_list
, &cfs_b
->throttled_cfs_rq
);
4388 * If we're the first throttled task, make sure the bandwidth
4392 start_cfs_bandwidth(cfs_b
);
4394 raw_spin_unlock(&cfs_b
->lock
);
4397 void unthrottle_cfs_rq(struct cfs_rq
*cfs_rq
)
4399 struct rq
*rq
= rq_of(cfs_rq
);
4400 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4401 struct sched_entity
*se
;
4405 se
= cfs_rq
->tg
->se
[cpu_of(rq
)];
4407 cfs_rq
->throttled
= 0;
4409 update_rq_clock(rq
);
4411 raw_spin_lock(&cfs_b
->lock
);
4412 cfs_b
->throttled_time
+= rq_clock(rq
) - cfs_rq
->throttled_clock
;
4413 list_del_rcu(&cfs_rq
->throttled_list
);
4414 raw_spin_unlock(&cfs_b
->lock
);
4416 /* update hierarchical throttle state */
4417 walk_tg_tree_from(cfs_rq
->tg
, tg_nop
, tg_unthrottle_up
, (void *)rq
);
4419 if (!cfs_rq
->load
.weight
)
4422 task_delta
= cfs_rq
->h_nr_running
;
4423 for_each_sched_entity(se
) {
4427 cfs_rq
= cfs_rq_of(se
);
4429 enqueue_entity(cfs_rq
, se
, ENQUEUE_WAKEUP
);
4430 cfs_rq
->h_nr_running
+= task_delta
;
4432 if (cfs_rq_throttled(cfs_rq
))
4437 add_nr_running(rq
, task_delta
);
4439 /* determine whether we need to wake up potentially idle cpu */
4440 if (rq
->curr
== rq
->idle
&& rq
->cfs
.nr_running
)
4444 static u64
distribute_cfs_runtime(struct cfs_bandwidth
*cfs_b
,
4445 u64 remaining
, u64 expires
)
4447 struct cfs_rq
*cfs_rq
;
4449 u64 starting_runtime
= remaining
;
4452 list_for_each_entry_rcu(cfs_rq
, &cfs_b
->throttled_cfs_rq
,
4454 struct rq
*rq
= rq_of(cfs_rq
);
4458 if (!cfs_rq_throttled(cfs_rq
))
4461 runtime
= -cfs_rq
->runtime_remaining
+ 1;
4462 if (runtime
> remaining
)
4463 runtime
= remaining
;
4464 remaining
-= runtime
;
4466 cfs_rq
->runtime_remaining
+= runtime
;
4467 cfs_rq
->runtime_expires
= expires
;
4469 /* we check whether we're throttled above */
4470 if (cfs_rq
->runtime_remaining
> 0)
4471 unthrottle_cfs_rq(cfs_rq
);
4481 return starting_runtime
- remaining
;
4485 * Responsible for refilling a task_group's bandwidth and unthrottling its
4486 * cfs_rqs as appropriate. If there has been no activity within the last
4487 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4488 * used to track this state.
4490 static int do_sched_cfs_period_timer(struct cfs_bandwidth
*cfs_b
, int overrun
)
4492 u64 runtime
, runtime_expires
;
4495 /* no need to continue the timer with no bandwidth constraint */
4496 if (cfs_b
->quota
== RUNTIME_INF
)
4497 goto out_deactivate
;
4499 throttled
= !list_empty(&cfs_b
->throttled_cfs_rq
);
4500 cfs_b
->nr_periods
+= overrun
;
4503 * idle depends on !throttled (for the case of a large deficit), and if
4504 * we're going inactive then everything else can be deferred
4506 if (cfs_b
->idle
&& !throttled
)
4507 goto out_deactivate
;
4509 __refill_cfs_bandwidth_runtime(cfs_b
);
4512 /* mark as potentially idle for the upcoming period */
4517 /* account preceding periods in which throttling occurred */
4518 cfs_b
->nr_throttled
+= overrun
;
4520 runtime_expires
= cfs_b
->runtime_expires
;
4523 * This check is repeated as we are holding onto the new bandwidth while
4524 * we unthrottle. This can potentially race with an unthrottled group
4525 * trying to acquire new bandwidth from the global pool. This can result
4526 * in us over-using our runtime if it is all used during this loop, but
4527 * only by limited amounts in that extreme case.
4529 while (throttled
&& cfs_b
->runtime
> 0) {
4530 runtime
= cfs_b
->runtime
;
4531 raw_spin_unlock(&cfs_b
->lock
);
4532 /* we can't nest cfs_b->lock while distributing bandwidth */
4533 runtime
= distribute_cfs_runtime(cfs_b
, runtime
,
4535 raw_spin_lock(&cfs_b
->lock
);
4537 throttled
= !list_empty(&cfs_b
->throttled_cfs_rq
);
4539 cfs_b
->runtime
-= min(runtime
, cfs_b
->runtime
);
4543 * While we are ensured activity in the period following an
4544 * unthrottle, this also covers the case in which the new bandwidth is
4545 * insufficient to cover the existing bandwidth deficit. (Forcing the
4546 * timer to remain active while there are any throttled entities.)
4556 /* a cfs_rq won't donate quota below this amount */
4557 static const u64 min_cfs_rq_runtime
= 1 * NSEC_PER_MSEC
;
4558 /* minimum remaining period time to redistribute slack quota */
4559 static const u64 min_bandwidth_expiration
= 2 * NSEC_PER_MSEC
;
4560 /* how long we wait to gather additional slack before distributing */
4561 static const u64 cfs_bandwidth_slack_period
= 5 * NSEC_PER_MSEC
;
4564 * Are we near the end of the current quota period?
4566 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4567 * hrtimer base being cleared by hrtimer_start. In the case of
4568 * migrate_hrtimers, base is never cleared, so we are fine.
4570 static int runtime_refresh_within(struct cfs_bandwidth
*cfs_b
, u64 min_expire
)
4572 struct hrtimer
*refresh_timer
= &cfs_b
->period_timer
;
4575 /* if the call-back is running a quota refresh is already occurring */
4576 if (hrtimer_callback_running(refresh_timer
))
4579 /* is a quota refresh about to occur? */
4580 remaining
= ktime_to_ns(hrtimer_expires_remaining(refresh_timer
));
4581 if (remaining
< min_expire
)
4587 static void start_cfs_slack_bandwidth(struct cfs_bandwidth
*cfs_b
)
4589 u64 min_left
= cfs_bandwidth_slack_period
+ min_bandwidth_expiration
;
4591 /* if there's a quota refresh soon don't bother with slack */
4592 if (runtime_refresh_within(cfs_b
, min_left
))
4595 hrtimer_start(&cfs_b
->slack_timer
,
4596 ns_to_ktime(cfs_bandwidth_slack_period
),
4600 /* we know any runtime found here is valid as update_curr() precedes return */
4601 static void __return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4603 struct cfs_bandwidth
*cfs_b
= tg_cfs_bandwidth(cfs_rq
->tg
);
4604 s64 slack_runtime
= cfs_rq
->runtime_remaining
- min_cfs_rq_runtime
;
4606 if (slack_runtime
<= 0)
4609 raw_spin_lock(&cfs_b
->lock
);
4610 if (cfs_b
->quota
!= RUNTIME_INF
&&
4611 cfs_rq
->runtime_expires
== cfs_b
->runtime_expires
) {
4612 cfs_b
->runtime
+= slack_runtime
;
4614 /* we are under rq->lock, defer unthrottling using a timer */
4615 if (cfs_b
->runtime
> sched_cfs_bandwidth_slice() &&
4616 !list_empty(&cfs_b
->throttled_cfs_rq
))
4617 start_cfs_slack_bandwidth(cfs_b
);
4619 raw_spin_unlock(&cfs_b
->lock
);
4621 /* even if it's not valid for return we don't want to try again */
4622 cfs_rq
->runtime_remaining
-= slack_runtime
;
4625 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4627 if (!cfs_bandwidth_used())
4630 if (!cfs_rq
->runtime_enabled
|| cfs_rq
->nr_running
)
4633 __return_cfs_rq_runtime(cfs_rq
);
4637 * This is done with a timer (instead of inline with bandwidth return) since
4638 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4640 static void do_sched_cfs_slack_timer(struct cfs_bandwidth
*cfs_b
)
4642 u64 runtime
= 0, slice
= sched_cfs_bandwidth_slice();
4645 /* confirm we're still not at a refresh boundary */
4646 raw_spin_lock(&cfs_b
->lock
);
4647 if (runtime_refresh_within(cfs_b
, min_bandwidth_expiration
)) {
4648 raw_spin_unlock(&cfs_b
->lock
);
4652 if (cfs_b
->quota
!= RUNTIME_INF
&& cfs_b
->runtime
> slice
)
4653 runtime
= cfs_b
->runtime
;
4655 expires
= cfs_b
->runtime_expires
;
4656 raw_spin_unlock(&cfs_b
->lock
);
4661 runtime
= distribute_cfs_runtime(cfs_b
, runtime
, expires
);
4663 raw_spin_lock(&cfs_b
->lock
);
4664 if (expires
== cfs_b
->runtime_expires
)
4665 cfs_b
->runtime
-= min(runtime
, cfs_b
->runtime
);
4666 raw_spin_unlock(&cfs_b
->lock
);
4670 * When a group wakes up we want to make sure that its quota is not already
4671 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4672 * runtime as update_curr() throttling can not not trigger until it's on-rq.
4674 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
)
4676 if (!cfs_bandwidth_used())
4679 /* an active group must be handled by the update_curr()->put() path */
4680 if (!cfs_rq
->runtime_enabled
|| cfs_rq
->curr
)
4683 /* ensure the group is not already throttled */
4684 if (cfs_rq_throttled(cfs_rq
))
4687 /* update runtime allocation */
4688 account_cfs_rq_runtime(cfs_rq
, 0);
4689 if (cfs_rq
->runtime_remaining
<= 0)
4690 throttle_cfs_rq(cfs_rq
);
4693 static void sync_throttle(struct task_group
*tg
, int cpu
)
4695 struct cfs_rq
*pcfs_rq
, *cfs_rq
;
4697 if (!cfs_bandwidth_used())
4703 cfs_rq
= tg
->cfs_rq
[cpu
];
4704 pcfs_rq
= tg
->parent
->cfs_rq
[cpu
];
4706 cfs_rq
->throttle_count
= pcfs_rq
->throttle_count
;
4707 cfs_rq
->throttled_clock_task
= rq_clock_task(cpu_rq(cpu
));
4710 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4711 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4713 if (!cfs_bandwidth_used())
4716 if (likely(!cfs_rq
->runtime_enabled
|| cfs_rq
->runtime_remaining
> 0))
4720 * it's possible for a throttled entity to be forced into a running
4721 * state (e.g. set_curr_task), in this case we're finished.
4723 if (cfs_rq_throttled(cfs_rq
))
4726 throttle_cfs_rq(cfs_rq
);
4730 static enum hrtimer_restart
sched_cfs_slack_timer(struct hrtimer
*timer
)
4732 struct cfs_bandwidth
*cfs_b
=
4733 container_of(timer
, struct cfs_bandwidth
, slack_timer
);
4735 do_sched_cfs_slack_timer(cfs_b
);
4737 return HRTIMER_NORESTART
;
4740 static enum hrtimer_restart
sched_cfs_period_timer(struct hrtimer
*timer
)
4742 struct cfs_bandwidth
*cfs_b
=
4743 container_of(timer
, struct cfs_bandwidth
, period_timer
);
4747 raw_spin_lock(&cfs_b
->lock
);
4749 overrun
= hrtimer_forward_now(timer
, cfs_b
->period
);
4753 idle
= do_sched_cfs_period_timer(cfs_b
, overrun
);
4756 cfs_b
->period_active
= 0;
4757 raw_spin_unlock(&cfs_b
->lock
);
4759 return idle
? HRTIMER_NORESTART
: HRTIMER_RESTART
;
4762 void init_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
4764 raw_spin_lock_init(&cfs_b
->lock
);
4766 cfs_b
->quota
= RUNTIME_INF
;
4767 cfs_b
->period
= ns_to_ktime(default_cfs_period());
4769 INIT_LIST_HEAD(&cfs_b
->throttled_cfs_rq
);
4770 hrtimer_init(&cfs_b
->period_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_ABS_PINNED
);
4771 cfs_b
->period_timer
.function
= sched_cfs_period_timer
;
4772 hrtimer_init(&cfs_b
->slack_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
4773 cfs_b
->slack_timer
.function
= sched_cfs_slack_timer
;
4776 static void init_cfs_rq_runtime(struct cfs_rq
*cfs_rq
)
4778 cfs_rq
->runtime_enabled
= 0;
4779 INIT_LIST_HEAD(&cfs_rq
->throttled_list
);
4782 void start_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
4784 lockdep_assert_held(&cfs_b
->lock
);
4786 if (!cfs_b
->period_active
) {
4787 cfs_b
->period_active
= 1;
4788 hrtimer_forward_now(&cfs_b
->period_timer
, cfs_b
->period
);
4789 hrtimer_start_expires(&cfs_b
->period_timer
, HRTIMER_MODE_ABS_PINNED
);
4793 static void destroy_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
)
4795 /* init_cfs_bandwidth() was not called */
4796 if (!cfs_b
->throttled_cfs_rq
.next
)
4799 hrtimer_cancel(&cfs_b
->period_timer
);
4800 hrtimer_cancel(&cfs_b
->slack_timer
);
4804 * Both these cpu hotplug callbacks race against unregister_fair_sched_group()
4806 * The race is harmless, since modifying bandwidth settings of unhooked group
4807 * bits doesn't do much.
4810 /* cpu online calback */
4811 static void __maybe_unused
update_runtime_enabled(struct rq
*rq
)
4813 struct task_group
*tg
;
4815 lockdep_assert_held(&rq
->lock
);
4818 list_for_each_entry_rcu(tg
, &task_groups
, list
) {
4819 struct cfs_bandwidth
*cfs_b
= &tg
->cfs_bandwidth
;
4820 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4822 raw_spin_lock(&cfs_b
->lock
);
4823 cfs_rq
->runtime_enabled
= cfs_b
->quota
!= RUNTIME_INF
;
4824 raw_spin_unlock(&cfs_b
->lock
);
4829 /* cpu offline callback */
4830 static void __maybe_unused
unthrottle_offline_cfs_rqs(struct rq
*rq
)
4832 struct task_group
*tg
;
4834 lockdep_assert_held(&rq
->lock
);
4837 list_for_each_entry_rcu(tg
, &task_groups
, list
) {
4838 struct cfs_rq
*cfs_rq
= tg
->cfs_rq
[cpu_of(rq
)];
4840 if (!cfs_rq
->runtime_enabled
)
4844 * clock_task is not advancing so we just need to make sure
4845 * there's some valid quota amount
4847 cfs_rq
->runtime_remaining
= 1;
4849 * Offline rq is schedulable till cpu is completely disabled
4850 * in take_cpu_down(), so we prevent new cfs throttling here.
4852 cfs_rq
->runtime_enabled
= 0;
4854 if (cfs_rq_throttled(cfs_rq
))
4855 unthrottle_cfs_rq(cfs_rq
);
4860 #else /* CONFIG_CFS_BANDWIDTH */
4861 static inline u64
cfs_rq_clock_task(struct cfs_rq
*cfs_rq
)
4863 return rq_clock_task(rq_of(cfs_rq
));
4866 static void account_cfs_rq_runtime(struct cfs_rq
*cfs_rq
, u64 delta_exec
) {}
4867 static bool check_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) { return false; }
4868 static void check_enqueue_throttle(struct cfs_rq
*cfs_rq
) {}
4869 static inline void sync_throttle(struct task_group
*tg
, int cpu
) {}
4870 static __always_inline
void return_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) {}
4872 static inline int cfs_rq_throttled(struct cfs_rq
*cfs_rq
)
4877 static inline int throttled_hierarchy(struct cfs_rq
*cfs_rq
)
4882 static inline int throttled_lb_pair(struct task_group
*tg
,
4883 int src_cpu
, int dest_cpu
)
4888 void init_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
) {}
4890 #ifdef CONFIG_FAIR_GROUP_SCHED
4891 static void init_cfs_rq_runtime(struct cfs_rq
*cfs_rq
) {}
4894 static inline struct cfs_bandwidth
*tg_cfs_bandwidth(struct task_group
*tg
)
4898 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth
*cfs_b
) {}
4899 static inline void update_runtime_enabled(struct rq
*rq
) {}
4900 static inline void unthrottle_offline_cfs_rqs(struct rq
*rq
) {}
4902 #endif /* CONFIG_CFS_BANDWIDTH */
4904 /**************************************************
4905 * CFS operations on tasks:
4908 #ifdef CONFIG_SCHED_HRTICK
4909 static void hrtick_start_fair(struct rq
*rq
, struct task_struct
*p
)
4911 struct sched_entity
*se
= &p
->se
;
4912 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
4914 SCHED_WARN_ON(task_rq(p
) != rq
);
4916 if (rq
->cfs
.h_nr_running
> 1) {
4917 u64 slice
= sched_slice(cfs_rq
, se
);
4918 u64 ran
= se
->sum_exec_runtime
- se
->prev_sum_exec_runtime
;
4919 s64 delta
= slice
- ran
;
4926 hrtick_start(rq
, delta
);
4931 * called from enqueue/dequeue and updates the hrtick when the
4932 * current task is from our class and nr_running is low enough
4935 static void hrtick_update(struct rq
*rq
)
4937 struct task_struct
*curr
= rq
->curr
;
4939 if (!hrtick_enabled(rq
) || curr
->sched_class
!= &fair_sched_class
)
4942 if (cfs_rq_of(&curr
->se
)->nr_running
< sched_nr_latency
)
4943 hrtick_start_fair(rq
, curr
);
4945 #else /* !CONFIG_SCHED_HRTICK */
4947 hrtick_start_fair(struct rq
*rq
, struct task_struct
*p
)
4951 static inline void hrtick_update(struct rq
*rq
)
4957 static bool cpu_overutilized(int cpu
);
4959 static unsigned long cpu_util(int cpu
);
4961 static bool sd_overutilized(struct sched_domain
*sd
)
4963 return sd
->shared
->overutilized
;
4966 static void set_sd_overutilized(struct sched_domain
*sd
)
4968 trace_sched_overutilized(sd
, sd
->shared
->overutilized
, true);
4969 sd
->shared
->overutilized
= true;
4972 static void clear_sd_overutilized(struct sched_domain
*sd
)
4974 trace_sched_overutilized(sd
, sd
->shared
->overutilized
, false);
4975 sd
->shared
->overutilized
= false;
4978 static inline void update_overutilized_status(struct rq
*rq
)
4980 struct sched_domain
*sd
;
4983 sd
= rcu_dereference(rq
->sd
);
4984 if (sd
&& !sd_overutilized(sd
) &&
4985 cpu_overutilized(rq
->cpu
))
4986 set_sd_overutilized(sd
);
4990 unsigned long boosted_cpu_util(int cpu
);
4993 #define update_overutilized_status(rq) do {} while (0)
4994 #define boosted_cpu_util(cpu) cpu_util_freq(cpu)
4996 #endif /* CONFIG_SMP */
4999 * The enqueue_task method is called before nr_running is
5000 * increased. Here we update the fair scheduling stats and
5001 * then put the task into the rbtree:
5004 enqueue_task_fair(struct rq
*rq
, struct task_struct
*p
, int flags
)
5006 struct cfs_rq
*cfs_rq
;
5007 struct sched_entity
*se
= &p
->se
;
5008 int task_new
= !(flags
& ENQUEUE_WAKEUP
);
5011 * If in_iowait is set, the code below may not trigger any cpufreq
5012 * utilization updates, so do it here explicitly with the IOWAIT flag
5016 cpufreq_update_util(rq
, SCHED_CPUFREQ_IOWAIT
);
5018 for_each_sched_entity(se
) {
5021 cfs_rq
= cfs_rq_of(se
);
5022 enqueue_entity(cfs_rq
, se
, flags
);
5025 * end evaluation on encountering a throttled cfs_rq
5027 * note: in the case of encountering a throttled cfs_rq we will
5028 * post the final h_nr_running increment below.
5030 if (cfs_rq_throttled(cfs_rq
))
5032 cfs_rq
->h_nr_running
++;
5033 walt_inc_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5035 flags
= ENQUEUE_WAKEUP
;
5038 for_each_sched_entity(se
) {
5039 cfs_rq
= cfs_rq_of(se
);
5040 cfs_rq
->h_nr_running
++;
5041 walt_inc_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5043 if (cfs_rq_throttled(cfs_rq
))
5046 update_load_avg(se
, UPDATE_TG
);
5047 update_cfs_shares(se
);
5051 * Update SchedTune accounting.
5053 * We do it before updating the CPU capacity to ensure the
5054 * boost value of the current task is accounted for in the
5055 * selection of the OPP.
5057 * We do it also in the case where we enqueue a throttled task;
5058 * we could argue that a throttled task should not boost a CPU,
5060 * a) properly implementing CPU boosting considering throttled
5061 * tasks will increase a lot the complexity of the solution
5062 * b) it's not easy to quantify the benefits introduced by
5063 * such a more complex solution.
5064 * Thus, for the time being we go for the simple solution and boost
5065 * also for throttled RQs.
5067 schedtune_enqueue_task(p
, cpu_of(rq
));
5070 add_nr_running(rq
, 1);
5072 update_overutilized_status(rq
);
5073 walt_inc_cumulative_runnable_avg(rq
, p
);
5079 static void set_next_buddy(struct sched_entity
*se
);
5082 * The dequeue_task method is called before nr_running is
5083 * decreased. We remove the task from the rbtree and
5084 * update the fair scheduling stats:
5086 static void dequeue_task_fair(struct rq
*rq
, struct task_struct
*p
, int flags
)
5088 struct cfs_rq
*cfs_rq
;
5089 struct sched_entity
*se
= &p
->se
;
5090 int task_sleep
= flags
& DEQUEUE_SLEEP
;
5092 for_each_sched_entity(se
) {
5093 cfs_rq
= cfs_rq_of(se
);
5094 dequeue_entity(cfs_rq
, se
, flags
);
5097 * end evaluation on encountering a throttled cfs_rq
5099 * note: in the case of encountering a throttled cfs_rq we will
5100 * post the final h_nr_running decrement below.
5102 if (cfs_rq_throttled(cfs_rq
))
5104 cfs_rq
->h_nr_running
--;
5105 walt_dec_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5107 /* Don't dequeue parent if it has other entities besides us */
5108 if (cfs_rq
->load
.weight
) {
5109 /* Avoid re-evaluating load for this entity: */
5110 se
= parent_entity(se
);
5112 * Bias pick_next to pick a task from this cfs_rq, as
5113 * p is sleeping when it is within its sched_slice.
5115 if (task_sleep
&& se
&& !throttled_hierarchy(cfs_rq
))
5119 flags
|= DEQUEUE_SLEEP
;
5122 for_each_sched_entity(se
) {
5123 cfs_rq
= cfs_rq_of(se
);
5124 cfs_rq
->h_nr_running
--;
5125 walt_dec_cfs_cumulative_runnable_avg(cfs_rq
, p
);
5127 if (cfs_rq_throttled(cfs_rq
))
5130 update_load_avg(se
, UPDATE_TG
);
5131 update_cfs_shares(se
);
5135 * Update SchedTune accounting
5137 * We do it before updating the CPU capacity to ensure the
5138 * boost value of the current task is accounted for in the
5139 * selection of the OPP.
5141 schedtune_dequeue_task(p
, cpu_of(rq
));
5144 sub_nr_running(rq
, 1);
5145 walt_dec_cumulative_runnable_avg(rq
, p
);
5153 /* Working cpumask for: load_balance, load_balance_newidle. */
5154 DEFINE_PER_CPU(cpumask_var_t
, load_balance_mask
);
5155 DEFINE_PER_CPU(cpumask_var_t
, select_idle_mask
);
5157 #ifdef CONFIG_NO_HZ_COMMON
5159 * per rq 'load' arrray crap; XXX kill this.
5163 * The exact cpuload calculated at every tick would be:
5165 * load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
5167 * If a cpu misses updates for n ticks (as it was idle) and update gets
5168 * called on the n+1-th tick when cpu may be busy, then we have:
5170 * load_n = (1 - 1/2^i)^n * load_0
5171 * load_n+1 = (1 - 1/2^i) * load_n + (1/2^i) * cur_load
5173 * decay_load_missed() below does efficient calculation of
5175 * load' = (1 - 1/2^i)^n * load
5177 * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
5178 * This allows us to precompute the above in said factors, thereby allowing the
5179 * reduction of an arbitrary n in O(log_2 n) steps. (See also
5180 * fixed_power_int())
5182 * The calculation is approximated on a 128 point scale.
5184 #define DEGRADE_SHIFT 7
5186 static const u8 degrade_zero_ticks
[CPU_LOAD_IDX_MAX
] = {0, 8, 32, 64, 128};
5187 static const u8 degrade_factor
[CPU_LOAD_IDX_MAX
][DEGRADE_SHIFT
+ 1] = {
5188 { 0, 0, 0, 0, 0, 0, 0, 0 },
5189 { 64, 32, 8, 0, 0, 0, 0, 0 },
5190 { 96, 72, 40, 12, 1, 0, 0, 0 },
5191 { 112, 98, 75, 43, 15, 1, 0, 0 },
5192 { 120, 112, 98, 76, 45, 16, 2, 0 }
5196 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
5197 * would be when CPU is idle and so we just decay the old load without
5198 * adding any new load.
5200 static unsigned long
5201 decay_load_missed(unsigned long load
, unsigned long missed_updates
, int idx
)
5205 if (!missed_updates
)
5208 if (missed_updates
>= degrade_zero_ticks
[idx
])
5212 return load
>> missed_updates
;
5214 while (missed_updates
) {
5215 if (missed_updates
% 2)
5216 load
= (load
* degrade_factor
[idx
][j
]) >> DEGRADE_SHIFT
;
5218 missed_updates
>>= 1;
5223 #endif /* CONFIG_NO_HZ_COMMON */
5226 * __cpu_load_update - update the rq->cpu_load[] statistics
5227 * @this_rq: The rq to update statistics for
5228 * @this_load: The current load
5229 * @pending_updates: The number of missed updates
5231 * Update rq->cpu_load[] statistics. This function is usually called every
5232 * scheduler tick (TICK_NSEC).
5234 * This function computes a decaying average:
5236 * load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
5238 * Because of NOHZ it might not get called on every tick which gives need for
5239 * the @pending_updates argument.
5241 * load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
5242 * = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
5243 * = A * (A * load[i]_n-2 + B) + B
5244 * = A * (A * (A * load[i]_n-3 + B) + B) + B
5245 * = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
5246 * = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
5247 * = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
5248 * = (1 - 1/2^i)^n * (load[i]_0 - load) + load
5250 * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
5251 * any change in load would have resulted in the tick being turned back on.
5253 * For regular NOHZ, this reduces to:
5255 * load[i]_n = (1 - 1/2^i)^n * load[i]_0
5257 * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
5260 static void cpu_load_update(struct rq
*this_rq
, unsigned long this_load
,
5261 unsigned long pending_updates
)
5263 unsigned long __maybe_unused tickless_load
= this_rq
->cpu_load
[0];
5266 this_rq
->nr_load_updates
++;
5268 /* Update our load: */
5269 this_rq
->cpu_load
[0] = this_load
; /* Fasttrack for idx 0 */
5270 for (i
= 1, scale
= 2; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
5271 unsigned long old_load
, new_load
;
5273 /* scale is effectively 1 << i now, and >> i divides by scale */
5275 old_load
= this_rq
->cpu_load
[i
];
5276 #ifdef CONFIG_NO_HZ_COMMON
5277 old_load
= decay_load_missed(old_load
, pending_updates
- 1, i
);
5278 if (tickless_load
) {
5279 old_load
-= decay_load_missed(tickless_load
, pending_updates
- 1, i
);
5281 * old_load can never be a negative value because a
5282 * decayed tickless_load cannot be greater than the
5283 * original tickless_load.
5285 old_load
+= tickless_load
;
5288 new_load
= this_load
;
5290 * Round up the averaging division if load is increasing. This
5291 * prevents us from getting stuck on 9 if the load is 10, for
5294 if (new_load
> old_load
)
5295 new_load
+= scale
- 1;
5297 this_rq
->cpu_load
[i
] = (old_load
* (scale
- 1) + new_load
) >> i
;
5300 sched_avg_update(this_rq
);
5303 /* Used instead of source_load when we know the type == 0 */
5304 static unsigned long weighted_cpuload(struct rq
*rq
)
5306 return cfs_rq_runnable_load_avg(&rq
->cfs
);
5309 #ifdef CONFIG_NO_HZ_COMMON
5311 * There is no sane way to deal with nohz on smp when using jiffies because the
5312 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
5313 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
5315 * Therefore we need to avoid the delta approach from the regular tick when
5316 * possible since that would seriously skew the load calculation. This is why we
5317 * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
5318 * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
5319 * loop exit, nohz_idle_balance, nohz full exit...)
5321 * This means we might still be one tick off for nohz periods.
5324 static void cpu_load_update_nohz(struct rq
*this_rq
,
5325 unsigned long curr_jiffies
,
5328 unsigned long pending_updates
;
5330 pending_updates
= curr_jiffies
- this_rq
->last_load_update_tick
;
5331 if (pending_updates
) {
5332 this_rq
->last_load_update_tick
= curr_jiffies
;
5334 * In the regular NOHZ case, we were idle, this means load 0.
5335 * In the NOHZ_FULL case, we were non-idle, we should consider
5336 * its weighted load.
5338 cpu_load_update(this_rq
, load
, pending_updates
);
5343 * Called from nohz_idle_balance() to update the load ratings before doing the
5346 static void cpu_load_update_idle(struct rq
*this_rq
)
5349 * bail if there's load or we're actually up-to-date.
5351 if (weighted_cpuload(this_rq
))
5354 cpu_load_update_nohz(this_rq
, READ_ONCE(jiffies
), 0);
5358 * Record CPU load on nohz entry so we know the tickless load to account
5359 * on nohz exit. cpu_load[0] happens then to be updated more frequently
5360 * than other cpu_load[idx] but it should be fine as cpu_load readers
5361 * shouldn't rely into synchronized cpu_load[*] updates.
5363 void cpu_load_update_nohz_start(void)
5365 struct rq
*this_rq
= this_rq();
5368 * This is all lockless but should be fine. If weighted_cpuload changes
5369 * concurrently we'll exit nohz. And cpu_load write can race with
5370 * cpu_load_update_idle() but both updater would be writing the same.
5372 this_rq
->cpu_load
[0] = weighted_cpuload(this_rq
);
5376 * Account the tickless load in the end of a nohz frame.
5378 void cpu_load_update_nohz_stop(void)
5380 unsigned long curr_jiffies
= READ_ONCE(jiffies
);
5381 struct rq
*this_rq
= this_rq();
5385 if (curr_jiffies
== this_rq
->last_load_update_tick
)
5388 load
= weighted_cpuload(this_rq
);
5389 rq_lock(this_rq
, &rf
);
5390 update_rq_clock(this_rq
);
5391 cpu_load_update_nohz(this_rq
, curr_jiffies
, load
);
5392 rq_unlock(this_rq
, &rf
);
5394 #else /* !CONFIG_NO_HZ_COMMON */
5395 static inline void cpu_load_update_nohz(struct rq
*this_rq
,
5396 unsigned long curr_jiffies
,
5397 unsigned long load
) { }
5398 #endif /* CONFIG_NO_HZ_COMMON */
5400 static void cpu_load_update_periodic(struct rq
*this_rq
, unsigned long load
)
5402 #ifdef CONFIG_NO_HZ_COMMON
5403 /* See the mess around cpu_load_update_nohz(). */
5404 this_rq
->last_load_update_tick
= READ_ONCE(jiffies
);
5406 cpu_load_update(this_rq
, load
, 1);
5410 * Called from scheduler_tick()
5412 void cpu_load_update_active(struct rq
*this_rq
)
5414 unsigned long load
= weighted_cpuload(this_rq
);
5416 if (tick_nohz_tick_stopped())
5417 cpu_load_update_nohz(this_rq
, READ_ONCE(jiffies
), load
);
5419 cpu_load_update_periodic(this_rq
, load
);
5423 * Return a low guess at the load of a migration-source cpu weighted
5424 * according to the scheduling class and "nice" value.
5426 * We want to under-estimate the load of migration sources, to
5427 * balance conservatively.
5429 static unsigned long source_load(int cpu
, int type
)
5431 struct rq
*rq
= cpu_rq(cpu
);
5432 unsigned long total
= weighted_cpuload(rq
);
5434 if (type
== 0 || !sched_feat(LB_BIAS
))
5437 return min(rq
->cpu_load
[type
-1], total
);
5441 * Return a high guess at the load of a migration-target cpu weighted
5442 * according to the scheduling class and "nice" value.
5444 static unsigned long target_load(int cpu
, int type
)
5446 struct rq
*rq
= cpu_rq(cpu
);
5447 unsigned long total
= weighted_cpuload(rq
);
5449 if (type
== 0 || !sched_feat(LB_BIAS
))
5452 return max(rq
->cpu_load
[type
-1], total
);
5455 static unsigned long cpu_avg_load_per_task(int cpu
)
5457 struct rq
*rq
= cpu_rq(cpu
);
5458 unsigned long nr_running
= READ_ONCE(rq
->cfs
.h_nr_running
);
5459 unsigned long load_avg
= weighted_cpuload(rq
);
5462 return load_avg
/ nr_running
;
5467 static void record_wakee(struct task_struct
*p
)
5470 * Only decay a single time; tasks that have less then 1 wakeup per
5471 * jiffy will not have built up many flips.
5473 if (time_after(jiffies
, current
->wakee_flip_decay_ts
+ HZ
)) {
5474 current
->wakee_flips
>>= 1;
5475 current
->wakee_flip_decay_ts
= jiffies
;
5478 if (current
->last_wakee
!= p
) {
5479 current
->last_wakee
= p
;
5480 current
->wakee_flips
++;
5485 * Returns the current capacity of cpu after applying both
5486 * cpu and freq scaling.
5488 unsigned long capacity_curr_of(int cpu
)
5490 unsigned long max_cap
= cpu_rq(cpu
)->cpu_capacity_orig
;
5491 unsigned long scale_freq
= arch_scale_freq_capacity(NULL
, cpu
);
5493 return cap_scale(max_cap
, scale_freq
);
5496 static inline bool energy_aware(void)
5498 return sched_feat(ENERGY_AWARE
);
5501 static int cpu_util_wake(int cpu
, struct task_struct
*p
);
5504 * __cpu_norm_util() returns the cpu util relative to a specific capacity,
5505 * i.e. it's busy ratio, in the range [0..SCHED_CAPACITY_SCALE] which is useful
5506 * for energy calculations. Using the scale-invariant util returned by
5507 * cpu_util() and approximating scale-invariant util by:
5509 * util ~ (curr_freq/max_freq)*1024 * capacity_orig/1024 * running_time/time
5511 * the normalized util can be found using the specific capacity.
5513 * capacity = capacity_orig * curr_freq/max_freq
5515 * norm_util = running_time/time ~ util/capacity
5517 static unsigned long __cpu_norm_util(unsigned long util
, unsigned long capacity
)
5519 if (util
>= capacity
)
5520 return SCHED_CAPACITY_SCALE
;
5522 return (util
<< SCHED_CAPACITY_SHIFT
)/capacity
;
5528 * These are labels to reference CPU candidates for an energy_diff.
5529 * Currently we support only two possible candidates: the task's previous CPU
5530 * and another candiate CPU.
5531 * More advanced/aggressive EAS selection policies can consider more
5534 #define EAS_CPU_PRV 0
5535 #define EAS_CPU_NXT 1
5536 #define EAS_CPU_BKP 2
5539 * energy_diff - supports the computation of the estimated energy impact in
5540 * moving a "task"'s "util_delta" between different CPU candidates.
5543 * NOTE: When using or examining WALT task signals, all wakeup
5544 * latency is included as busy time for task util.
5546 * This is relevant here because:
5547 * When debugging is enabled, it can take as much as 1ms to
5548 * write the output to the trace buffer for each eenv
5549 * scenario. For periodic tasks where the sleep time is of
5550 * a similar order, the WALT task util can be inflated.
5552 * Further, and even without debugging enabled,
5553 * task wakeup latency changes depending upon the EAS
5554 * wakeup algorithm selected - FIND_BEST_TARGET only does
5555 * energy calculations for up to 2 candidate CPUs. When
5556 * NO_FIND_BEST_TARGET is configured, we can potentially
5557 * do an energy calculation across all CPUS in the system.
5559 * The impact to WALT task util on a Juno board
5560 * running a periodic task which only sleeps for 200usec
5561 * between 1ms activations has been measured.
5562 * (i.e. the wakeup latency induced by energy calculation
5563 * and debug output is double the desired sleep time and
5564 * almost equivalent to the runtime which is more-or-less
5565 * the worst case possible for this test)
5567 * In this scenario, a task which has a PELT util of around
5568 * 220 is inflated under WALT to have util around 400.
5570 * This is simply a property of the way WALT includes
5571 * wakeup latency in busy time while PELT does not.
5573 * Hence - be careful when enabling DEBUG_EENV_DECISIONS
5574 * expecially if WALT is the task signal.
5576 /*#define DEBUG_EENV_DECISIONS*/
5578 #ifdef DEBUG_EENV_DECISIONS
5579 /* max of 8 levels of sched groups traversed */
5580 #define EAS_EENV_DEBUG_LEVELS 16
5582 struct _eenv_debug
{
5584 unsigned long norm_util
;
5585 unsigned long cap_energy
;
5586 unsigned long idle_energy
;
5587 unsigned long this_energy
;
5588 unsigned long this_busy_energy
;
5589 unsigned long this_idle_energy
;
5590 cpumask_t group_cpumask
;
5591 unsigned long cpu_util
[1];
5596 /* CPU ID, must be in cpus_mask */
5600 * Index (into sched_group_energy::cap_states) of the OPP the
5601 * CPU needs to run at if the task is placed on it.
5602 * This includes the both active and blocked load, due to
5603 * other tasks on this CPU, as well as the task's own
5609 /* Estimated system energy */
5610 unsigned long energy
;
5612 /* Estimated energy variation wrt EAS_CPU_PRV */
5615 #ifdef DEBUG_EENV_DECISIONS
5616 struct _eenv_debug
*debug
;
5618 #endif /* DEBUG_EENV_DECISIONS */
5622 /* Utilization to move */
5623 struct task_struct
*p
;
5624 unsigned long util_delta
;
5625 unsigned long util_delta_boosted
;
5627 /* Mask of CPUs candidates to evaluate */
5628 cpumask_t cpus_mask
;
5630 /* CPU candidates to evaluate */
5631 struct eenv_cpu
*cpu
;
5634 #ifdef DEBUG_EENV_DECISIONS
5635 /* pointer to the memory block reserved
5636 * for debug on this CPU - there will be
5637 * sizeof(struct _eenv_debug) *
5638 * (EAS_CPU_CNT * EAS_EENV_DEBUG_LEVELS)
5639 * bytes allocated here.
5641 struct _eenv_debug
*debug
;
5644 * Index (into energy_env::cpu) of the morst energy efficient CPU for
5645 * the specified energy_env::task
5651 struct sched_group
*sg_top
;
5652 struct sched_group
*sg_cap
;
5653 struct sched_group
*sg
;
5656 static int cpu_util_wake(int cpu
, struct task_struct
*p
);
5658 static unsigned long group_max_util(struct energy_env
*eenv
, int cpu_idx
)
5660 unsigned long max_util
= 0;
5664 for_each_cpu(cpu
, sched_group_span(eenv
->sg_cap
)) {
5665 util
= cpu_util_wake(cpu
, eenv
->p
);
5668 * If we are looking at the target CPU specified by the eenv,
5669 * then we should add the (estimated) utilization of the task
5670 * assuming we will wake it up on that CPU.
5672 if (unlikely(cpu
== eenv
->cpu
[cpu_idx
].cpu_id
))
5673 util
+= eenv
->util_delta_boosted
;
5675 max_util
= max(max_util
, util
);
5682 * group_norm_util() returns the approximated group util relative to it's
5683 * current capacity (busy ratio) in the range [0..SCHED_CAPACITY_SCALE] for use
5684 * in energy calculations. Since task executions may or may not overlap in time
5685 * in the group the true normalized util is between max(cpu_norm_util(i)) and
5686 * sum(cpu_norm_util(i)) when iterating over all cpus in the group, i. The
5687 * latter is used as the estimate as it leads to a more pessimistic energy
5688 * estimate (more busy).
5691 long group_norm_util(struct energy_env
*eenv
, int cpu_idx
)
5693 unsigned long capacity
= eenv
->cpu
[cpu_idx
].cap
;
5694 unsigned long util
, util_sum
= 0;
5697 for_each_cpu(cpu
, sched_group_span(eenv
->sg
)) {
5698 util
= cpu_util_wake(cpu
, eenv
->p
);
5701 * If we are looking at the target CPU specified by the eenv,
5702 * then we should add the (estimated) utilization of the task
5703 * assuming we will wake it up on that CPU.
5705 if (unlikely(cpu
== eenv
->cpu
[cpu_idx
].cpu_id
))
5706 util
+= eenv
->util_delta
;
5708 util_sum
+= __cpu_norm_util(util
, capacity
);
5711 if (util_sum
> SCHED_CAPACITY_SCALE
)
5712 return SCHED_CAPACITY_SCALE
;
5716 static int find_new_capacity(struct energy_env
*eenv
, int cpu_idx
)
5718 const struct sched_group_energy
*sge
= eenv
->sg_cap
->sge
;
5719 unsigned long util
= group_max_util(eenv
, cpu_idx
);
5722 cap_idx
= sge
->nr_cap_states
- 1;
5724 for (idx
= 0; idx
< sge
->nr_cap_states
; idx
++) {
5725 if (sge
->cap_states
[idx
].cap
>= util
) {
5730 /* Keep track of SG's capacity */
5731 eenv
->cpu
[cpu_idx
].cap
= sge
->cap_states
[cap_idx
].cap
;
5732 eenv
->cpu
[cpu_idx
].cap_idx
= cap_idx
;
5737 static int group_idle_state(struct energy_env
*eenv
, int cpu_idx
)
5739 struct sched_group
*sg
= eenv
->sg
;
5740 int src_in_grp
, dst_in_grp
;
5741 int i
, state
= INT_MAX
;
5742 int max_idle_state_idx
;
5746 /* Find the shallowest idle state in the sched group. */
5747 for_each_cpu(i
, sched_group_span(sg
))
5748 state
= min(state
, idle_get_state_idx(cpu_rq(i
)));
5750 /* Take non-cpuidle idling into account (active idle/arch_cpu_idle()) */
5753 * Try to estimate if a deeper idle state is
5754 * achievable when we move the task.
5756 for_each_cpu(i
, sched_group_span(sg
))
5757 grp_util
+= cpu_util(i
);
5759 src_in_grp
= cpumask_test_cpu(eenv
->cpu
[EAS_CPU_PRV
].cpu_id
,
5760 sched_group_span(sg
));
5761 dst_in_grp
= cpumask_test_cpu(eenv
->cpu
[cpu_idx
].cpu_id
,
5762 sched_group_span(sg
));
5763 if (src_in_grp
== dst_in_grp
) {
5765 * both CPUs under consideration are in the same group or not in
5766 * either group, migration should leave idle state the same.
5771 * add or remove util as appropriate to indicate what group util
5772 * will be (worst case - no concurrent execution) after moving the task
5774 grp_util
+= src_in_grp
? -eenv
->util_delta
: eenv
->util_delta
;
5777 ((long)sg
->sgc
->max_capacity
* (int)sg
->group_weight
)) {
5779 * After moving, the group will be fully occupied
5780 * so assume it will not be idle at all.
5786 * after moving, this group is at most partly
5787 * occupied, so it should have some idle time.
5789 max_idle_state_idx
= sg
->sge
->nr_idle_states
- 2;
5790 new_state
= grp_util
* max_idle_state_idx
;
5791 if (grp_util
<= 0) {
5792 /* group will have no util, use lowest state */
5793 new_state
= max_idle_state_idx
+ 1;
5796 * for partially idle, linearly map util to idle
5797 * states, excluding the lowest one. This does not
5798 * correspond to the state we expect to enter in
5799 * reality, but an indication of what might happen.
5801 new_state
= min_t(int, max_idle_state_idx
,
5802 new_state
/ sg
->sgc
->max_capacity
);
5803 new_state
= max_idle_state_idx
- new_state
;
5808 #ifdef DEBUG_EENV_DECISIONS
5809 static struct _eenv_debug
*eenv_debug_entry_ptr(struct _eenv_debug
*base
, int idx
);
5811 static void store_energy_calc_debug_info(struct energy_env
*eenv
, int cpu_idx
, int cap_idx
, int idle_idx
)
5813 int debug_idx
= eenv
->cpu
[cpu_idx
].debug_idx
;
5814 unsigned long sg_util
, busy_energy
, idle_energy
;
5815 const struct sched_group_energy
*sge
;
5816 struct _eenv_debug
*dbg
;
5819 if (debug_idx
< EAS_EENV_DEBUG_LEVELS
) {
5820 sge
= eenv
->sg
->sge
;
5821 sg_util
= group_norm_util(eenv
, cpu_idx
);
5822 busy_energy
= sge
->cap_states
[cap_idx
].power
;
5823 busy_energy
*= sg_util
;
5824 idle_energy
= SCHED_CAPACITY_SCALE
- sg_util
;
5825 idle_energy
*= sge
->idle_states
[idle_idx
].power
;
5826 /* should we use sg_cap or sg? */
5827 dbg
= eenv_debug_entry_ptr(eenv
->cpu
[cpu_idx
].debug
, debug_idx
);
5828 dbg
->cap
= sge
->cap_states
[cap_idx
].cap
;
5829 dbg
->norm_util
= sg_util
;
5830 dbg
->cap_energy
= sge
->cap_states
[cap_idx
].power
;
5831 dbg
->idle_energy
= sge
->idle_states
[idle_idx
].power
;
5832 dbg
->this_energy
= busy_energy
+ idle_energy
;
5833 dbg
->this_busy_energy
= busy_energy
;
5834 dbg
->this_idle_energy
= idle_energy
;
5836 cpumask_copy(&dbg
->group_cpumask
,
5837 sched_group_span(eenv
->sg
));
5839 for_each_cpu(cpu
, &dbg
->group_cpumask
)
5840 dbg
->cpu_util
[cpu
] = cpu_util(cpu
);
5842 eenv
->cpu
[cpu_idx
].debug_idx
= debug_idx
+1;
5846 #define store_energy_calc_debug_info(a,b,c,d) {}
5847 #endif /* DEBUG_EENV_DECISIONS */
5850 * calc_sg_energy: compute energy for the eenv's SG (i.e. eenv->sg).
5852 * This works in iterations to compute the SG's energy for each CPU
5853 * candidate defined by the energy_env's cpu array.
5855 static void calc_sg_energy(struct energy_env
*eenv
)
5857 struct sched_group
*sg
= eenv
->sg
;
5858 unsigned long busy_energy
, idle_energy
;
5859 unsigned int busy_power
, idle_power
;
5860 unsigned long total_energy
= 0;
5861 unsigned long sg_util
;
5862 int cap_idx
, idle_idx
;
5865 for (cpu_idx
= EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; ++cpu_idx
) {
5866 if (eenv
->cpu
[cpu_idx
].cpu_id
== -1)
5869 /* Compute ACTIVE energy */
5870 cap_idx
= find_new_capacity(eenv
, cpu_idx
);
5871 busy_power
= sg
->sge
->cap_states
[cap_idx
].power
;
5872 sg_util
= group_norm_util(eenv
, cpu_idx
);
5873 busy_energy
= sg_util
* busy_power
;
5875 /* Compute IDLE energy */
5876 idle_idx
= group_idle_state(eenv
, cpu_idx
);
5877 idle_power
= sg
->sge
->idle_states
[idle_idx
].power
;
5878 idle_energy
= SCHED_CAPACITY_SCALE
- sg_util
;
5879 idle_energy
*= idle_power
;
5881 total_energy
= busy_energy
+ idle_energy
;
5882 eenv
->cpu
[cpu_idx
].energy
+= total_energy
;
5884 store_energy_calc_debug_info(eenv
, cpu_idx
, cap_idx
, idle_idx
);
5889 * compute_energy() computes the absolute variation in energy consumption by
5890 * moving eenv.util_delta from EAS_CPU_PRV to EAS_CPU_NXT.
5892 * NOTE: compute_energy() may fail when racing with sched_domain updates, in
5893 * which case we abort by returning -EINVAL.
5895 static int compute_energy(struct energy_env
*eenv
)
5897 struct sched_domain
*sd
;
5899 struct cpumask visit_cpus
;
5900 struct sched_group
*sg
;
5902 WARN_ON(!eenv
->sg_top
->sge
);
5904 cpumask_copy(&visit_cpus
, sched_group_span(eenv
->sg_top
));
5906 while (!cpumask_empty(&visit_cpus
)) {
5907 struct sched_group
*sg_shared_cap
= NULL
;
5909 cpu
= cpumask_first(&visit_cpus
);
5912 * Is the group utilization affected by cpus outside this
5915 sd
= rcu_dereference(per_cpu(sd_scs
, cpu
));
5916 if (sd
&& sd
->parent
)
5917 sg_shared_cap
= sd
->parent
->groups
;
5919 for_each_domain(cpu
, sd
) {
5922 /* Has this sched_domain already been visited? */
5923 if (sd
->child
&& group_first_cpu(sg
) != cpu
)
5928 if (sg_shared_cap
&& sg_shared_cap
->group_weight
>= sg
->group_weight
)
5929 eenv
->sg_cap
= sg_shared_cap
;
5932 * Compute the energy for all the candidate
5933 * CPUs in the current visited SG.
5936 calc_sg_energy(eenv
);
5938 /* remove CPUs we have just visited */
5940 cpumask_xor(&visit_cpus
, &visit_cpus
, sched_group_span(sg
));
5942 if (cpumask_equal(sched_group_span(sg
), sched_group_span(eenv
->sg_top
)))
5945 } while (sg
= sg
->next
, sg
!= sd
->groups
);
5954 static inline bool cpu_in_sg(struct sched_group
*sg
, int cpu
)
5956 return cpu
!= -1 && cpumask_test_cpu(cpu
, sched_group_span(sg
));
5959 #ifdef DEBUG_EENV_DECISIONS
5960 static void dump_eenv_debug(struct energy_env
*eenv
)
5962 int cpu_idx
, grp_idx
;
5963 char cpu_utils
[(NR_CPUS
*12)+10]="cpu_util: ";
5966 trace_printk("eenv scenario: task=%p %s task_util=%lu prev_cpu=%d",
5967 eenv
->p
, eenv
->p
->comm
, eenv
->util_delta
, eenv
->cpu
[EAS_CPU_PRV
].cpu_id
);
5969 for (cpu_idx
=EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; cpu_idx
++) {
5970 if (eenv
->cpu
[cpu_idx
].cpu_id
== -1)
5972 trace_printk("---Scenario %d: Place task on cpu %d energy=%lu (%d debug logs at %p)",
5973 cpu_idx
+1, eenv
->cpu
[cpu_idx
].cpu_id
,
5974 eenv
->cpu
[cpu_idx
].energy
>> SCHED_CAPACITY_SHIFT
,
5975 eenv
->cpu
[cpu_idx
].debug_idx
,
5976 eenv
->cpu
[cpu_idx
].debug
);
5977 for (grp_idx
= 0; grp_idx
< eenv
->cpu
[cpu_idx
].debug_idx
; grp_idx
++) {
5978 struct _eenv_debug
*debug
;
5981 debug
= eenv_debug_entry_ptr(eenv
->cpu
[cpu_idx
].debug
, grp_idx
);
5982 cpu
= scnprintf(cpulist
, sizeof(cpulist
), "%*pbl", cpumask_pr_args(&debug
->group_cpumask
));
5985 /* print out the relevant cpu_util */
5986 for_each_cpu(cpu
, &(debug
->group_cpumask
)) {
5988 if (written
> sizeof(cpu_utils
)-10) {
5989 cpu_utils
[written
]=0;
5992 written
+= snprintf(tmp
, sizeof(tmp
), "cpu%d(%lu) ", cpu
, debug
->cpu_util
[cpu
]);
5993 strcat(cpu_utils
, tmp
);
5995 /* trace the data */
5996 trace_printk(" | %s : cap=%lu nutil=%lu, cap_nrg=%lu, idle_nrg=%lu energy=%lu busy_energy=%lu idle_energy=%lu %s",
5997 cpulist
, debug
->cap
, debug
->norm_util
,
5998 debug
->cap_energy
, debug
->idle_energy
,
5999 debug
->this_energy
>> SCHED_CAPACITY_SHIFT
,
6000 debug
->this_busy_energy
>> SCHED_CAPACITY_SHIFT
,
6001 debug
->this_idle_energy
>> SCHED_CAPACITY_SHIFT
,
6005 trace_printk("---");
6007 trace_printk("----- done");
6011 #define dump_eenv_debug(a) {}
6012 #endif /* DEBUG_EENV_DECISIONS */
6014 * select_energy_cpu_idx(): estimate the energy impact of changing the
6015 * utilization distribution.
6017 * The eenv parameter specifies the changes: utilization amount and a
6018 * collection of possible CPU candidates. The number of candidates
6019 * depends upon the selection algorithm used.
6021 * If find_best_target was used to select candidate CPUs, there will
6022 * be at most 3 including prev_cpu. If not, we used a brute force
6023 * selection which will provide the union of:
6024 * * CPUs belonging to the highest sd which is not overutilized
6025 * * CPUs the task is allowed to run on
6028 * This function returns the index of a CPU candidate specified by the
6029 * energy_env which corresponds to the most energy efficient CPU.
6030 * Thus, 0 (EAS_CPU_PRV) means that non of the CPU candidate is more energy
6031 * efficient than running on prev_cpu. This is also the value returned in case
6032 * of abort due to error conditions during the computations. The only
6033 * exception to this if we fail to access the energy model via sd_ea, where
6034 * we return -1 with the intent of asking the system to use a different
6035 * wakeup placement algorithm.
6037 * A value greater than zero means that the most energy efficient CPU is the
6038 * one represented by eenv->cpu[eenv->next_idx].cpu_id.
6040 static inline int select_energy_cpu_idx(struct energy_env
*eenv
)
6042 int last_cpu_idx
= eenv
->max_cpu_count
- 1;
6043 struct sched_domain
*sd
;
6044 struct sched_group
*sg
;
6049 sd_cpu
= eenv
->cpu
[EAS_CPU_PRV
].cpu_id
;
6050 sd
= rcu_dereference(per_cpu(sd_ea
, sd_cpu
));
6054 cpumask_clear(&eenv
->cpus_mask
);
6055 for (cpu_idx
= EAS_CPU_PRV
; cpu_idx
< eenv
->max_cpu_count
; ++cpu_idx
) {
6056 int cpu
= eenv
->cpu
[cpu_idx
].cpu_id
;
6060 cpumask_set_cpu(cpu
, &eenv
->cpus_mask
);
6065 /* Skip SGs which do not contains a candidate CPU */
6066 if (!cpumask_intersects(&eenv
->cpus_mask
, sched_group_span(sg
)))
6070 if (compute_energy(eenv
) == -EINVAL
)
6072 } while (sg
= sg
->next
, sg
!= sd
->groups
);
6073 /* remember - eenv energy values are unscaled */
6076 * Compute the dead-zone margin used to prevent too many task
6077 * migrations with negligible energy savings.
6078 * An energy saving is considered meaningful if it reduces the energy
6079 * consumption of EAS_CPU_PRV CPU candidate by at least ~1.56%
6081 margin
= eenv
->cpu
[EAS_CPU_PRV
].energy
>> 6;
6084 * By default the EAS_CPU_PRV CPU is considered the most energy
6085 * efficient, with a 0 energy variation.
6087 eenv
->next_idx
= EAS_CPU_PRV
;
6088 eenv
->cpu
[EAS_CPU_PRV
].nrg_delta
= 0;
6090 dump_eenv_debug(eenv
);
6093 * Compare the other CPU candidates to find a CPU which can be
6094 * more energy efficient then EAS_CPU_PRV
6096 if (sched_feat(FBT_STRICT_ORDER
))
6097 last_cpu_idx
= EAS_CPU_BKP
;
6099 for(cpu_idx
= EAS_CPU_NXT
; cpu_idx
<= last_cpu_idx
; cpu_idx
++) {
6100 if (eenv
->cpu
[cpu_idx
].cpu_id
< 0)
6102 eenv
->cpu
[cpu_idx
].nrg_delta
=
6103 eenv
->cpu
[cpu_idx
].energy
-
6104 eenv
->cpu
[EAS_CPU_PRV
].energy
;
6106 /* filter energy variations within the dead-zone margin */
6107 if (abs(eenv
->cpu
[cpu_idx
].nrg_delta
) < margin
)
6108 eenv
->cpu
[cpu_idx
].nrg_delta
= 0;
6109 /* update the schedule candidate with min(nrg_delta) */
6110 if (eenv
->cpu
[cpu_idx
].nrg_delta
<
6111 eenv
->cpu
[eenv
->next_idx
].nrg_delta
) {
6112 eenv
->next_idx
= cpu_idx
;
6113 /* break out if we want to stop on first saving candidate */
6114 if (sched_feat(FBT_STRICT_ORDER
))
6119 return eenv
->next_idx
;
6123 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6125 * A waker of many should wake a different task than the one last awakened
6126 * at a frequency roughly N times higher than one of its wakees.
6128 * In order to determine whether we should let the load spread vs consolidating
6129 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6130 * partner, and a factor of lls_size higher frequency in the other.
6132 * With both conditions met, we can be relatively sure that the relationship is
6133 * non-monogamous, with partner count exceeding socket size.
6135 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6136 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6139 static int wake_wide(struct task_struct
*p
, int sibling_count_hint
)
6141 unsigned int master
= current
->wakee_flips
;
6142 unsigned int slave
= p
->wakee_flips
;
6143 int llc_size
= this_cpu_read(sd_llc_size
);
6145 if (sibling_count_hint
>= llc_size
)
6149 swap(master
, slave
);
6150 if (slave
< llc_size
|| master
< slave
* llc_size
)
6156 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6157 * soonest. For the purpose of speed we only consider the waking and previous
6160 * wake_affine_idle() - only considers 'now', it check if the waking CPU is (or
6163 * wake_affine_weight() - considers the weight to reflect the average
6164 * scheduling latency of the CPUs. This seems to work
6165 * for the overloaded case.
6169 wake_affine_idle(struct sched_domain
*sd
, struct task_struct
*p
,
6170 int this_cpu
, int prev_cpu
, int sync
)
6172 if (idle_cpu(this_cpu
))
6175 if (sync
&& cpu_rq(this_cpu
)->nr_running
== 1)
6182 wake_affine_weight(struct sched_domain
*sd
, struct task_struct
*p
,
6183 int this_cpu
, int prev_cpu
, int sync
)
6185 s64 this_eff_load
, prev_eff_load
;
6186 unsigned long task_load
;
6188 this_eff_load
= target_load(this_cpu
, sd
->wake_idx
);
6189 prev_eff_load
= source_load(prev_cpu
, sd
->wake_idx
);
6192 unsigned long current_load
= task_h_load(current
);
6194 if (current_load
> this_eff_load
)
6197 this_eff_load
-= current_load
;
6200 task_load
= task_h_load(p
);
6202 this_eff_load
+= task_load
;
6203 if (sched_feat(WA_BIAS
))
6204 this_eff_load
*= 100;
6205 this_eff_load
*= capacity_of(prev_cpu
);
6207 prev_eff_load
-= task_load
;
6208 if (sched_feat(WA_BIAS
))
6209 prev_eff_load
*= 100 + (sd
->imbalance_pct
- 100) / 2;
6210 prev_eff_load
*= capacity_of(this_cpu
);
6212 return this_eff_load
<= prev_eff_load
;
6215 static int wake_affine(struct sched_domain
*sd
, struct task_struct
*p
,
6216 int prev_cpu
, int sync
)
6218 int this_cpu
= smp_processor_id();
6219 bool affine
= false;
6221 if (sched_feat(WA_IDLE
) && !affine
)
6222 affine
= wake_affine_idle(sd
, p
, this_cpu
, prev_cpu
, sync
);
6224 if (sched_feat(WA_WEIGHT
) && !affine
)
6225 affine
= wake_affine_weight(sd
, p
, this_cpu
, prev_cpu
, sync
);
6227 schedstat_inc(p
->se
.statistics
.nr_wakeups_affine_attempts
);
6229 schedstat_inc(sd
->ttwu_move_affine
);
6230 schedstat_inc(p
->se
.statistics
.nr_wakeups_affine
);
6236 static inline unsigned long task_util(struct task_struct
*p
);
6238 #ifdef CONFIG_SCHED_TUNE
6239 struct reciprocal_value schedtune_spc_rdiv
;
6242 schedtune_margin(unsigned long signal
, long boost
)
6244 long long margin
= 0;
6247 * Signal proportional compensation (SPC)
6249 * The Boost (B) value is used to compute a Margin (M) which is
6250 * proportional to the complement of the original Signal (S):
6251 * M = B * (SCHED_CAPACITY_SCALE - S)
6252 * The obtained M could be used by the caller to "boost" S.
6255 margin
= SCHED_CAPACITY_SCALE
- signal
;
6258 margin
= -signal
* boost
;
6260 margin
= reciprocal_divide(margin
, schedtune_spc_rdiv
);
6268 schedtune_cpu_margin(unsigned long util
, int cpu
)
6270 int boost
= schedtune_cpu_boost(cpu
);
6275 return schedtune_margin(util
, boost
);
6279 schedtune_task_margin(struct task_struct
*task
)
6281 int boost
= schedtune_task_boost(task
);
6288 util
= task_util(task
);
6289 margin
= schedtune_margin(util
, boost
);
6294 #else /* CONFIG_SCHED_TUNE */
6297 schedtune_cpu_margin(unsigned long util
, int cpu
)
6303 schedtune_task_margin(struct task_struct
*task
)
6308 #endif /* CONFIG_SCHED_TUNE */
6311 boosted_cpu_util(int cpu
)
6313 unsigned long util
= cpu_util_freq(cpu
);
6314 long margin
= schedtune_cpu_margin(util
, cpu
);
6316 trace_sched_boost_cpu(cpu
, util
, margin
);
6318 return util
+ margin
;
6321 static inline unsigned long
6322 boosted_task_util(struct task_struct
*task
)
6324 unsigned long util
= task_util(task
);
6325 long margin
= schedtune_task_margin(task
);
6327 trace_sched_boost_task(task
, util
, margin
);
6329 return util
+ margin
;
6332 static unsigned long capacity_spare_wake(int cpu
, struct task_struct
*p
)
6334 return max_t(long, capacity_of(cpu
) - cpu_util_wake(cpu
, p
), 0);
6338 * find_idlest_group finds and returns the least busy CPU group within the
6341 * Assumes p is allowed on at least one CPU in sd.
6343 static struct sched_group
*
6344 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
,
6345 int this_cpu
, int sd_flag
)
6347 struct sched_group
*idlest
= NULL
, *group
= sd
->groups
;
6348 struct sched_group
*most_spare_sg
= NULL
;
6349 unsigned long min_runnable_load
= ULONG_MAX
;
6350 unsigned long this_runnable_load
= ULONG_MAX
;
6351 unsigned long min_avg_load
= ULONG_MAX
, this_avg_load
= ULONG_MAX
;
6352 unsigned long most_spare
= 0, this_spare
= 0;
6353 int load_idx
= sd
->forkexec_idx
;
6354 int imbalance_scale
= 100 + (sd
->imbalance_pct
-100)/2;
6355 unsigned long imbalance
= scale_load_down(NICE_0_LOAD
) *
6356 (sd
->imbalance_pct
-100) / 100;
6358 if (sd_flag
& SD_BALANCE_WAKE
)
6359 load_idx
= sd
->wake_idx
;
6362 unsigned long load
, avg_load
, runnable_load
;
6363 unsigned long spare_cap
, max_spare_cap
;
6367 /* Skip over this group if it has no CPUs allowed */
6368 if (!cpumask_intersects(sched_group_span(group
),
6372 local_group
= cpumask_test_cpu(this_cpu
,
6373 sched_group_span(group
));
6376 * Tally up the load of all CPUs in the group and find
6377 * the group containing the CPU with most spare capacity.
6383 for_each_cpu(i
, sched_group_span(group
)) {
6384 /* Bias balancing toward cpus of our domain */
6386 load
= source_load(i
, load_idx
);
6388 load
= target_load(i
, load_idx
);
6390 runnable_load
+= load
;
6392 avg_load
+= cfs_rq_load_avg(&cpu_rq(i
)->cfs
);
6394 spare_cap
= capacity_spare_wake(i
, p
);
6396 if (spare_cap
> max_spare_cap
)
6397 max_spare_cap
= spare_cap
;
6400 /* Adjust by relative CPU capacity of the group */
6401 avg_load
= (avg_load
* SCHED_CAPACITY_SCALE
) /
6402 group
->sgc
->capacity
;
6403 runnable_load
= (runnable_load
* SCHED_CAPACITY_SCALE
) /
6404 group
->sgc
->capacity
;
6407 this_runnable_load
= runnable_load
;
6408 this_avg_load
= avg_load
;
6409 this_spare
= max_spare_cap
;
6411 if (min_runnable_load
> (runnable_load
+ imbalance
)) {
6413 * The runnable load is significantly smaller
6414 * so we can pick this new cpu
6416 min_runnable_load
= runnable_load
;
6417 min_avg_load
= avg_load
;
6419 } else if ((runnable_load
< (min_runnable_load
+ imbalance
)) &&
6420 (100*min_avg_load
> imbalance_scale
*avg_load
)) {
6422 * The runnable loads are close so take the
6423 * blocked load into account through avg_load.
6425 min_avg_load
= avg_load
;
6429 if (most_spare
< max_spare_cap
) {
6430 most_spare
= max_spare_cap
;
6431 most_spare_sg
= group
;
6434 } while (group
= group
->next
, group
!= sd
->groups
);
6437 * The cross-over point between using spare capacity or least load
6438 * is too conservative for high utilization tasks on partially
6439 * utilized systems if we require spare_capacity > task_util(p),
6440 * so we allow for some task stuffing by using
6441 * spare_capacity > task_util(p)/2.
6443 * Spare capacity can't be used for fork because the utilization has
6444 * not been set yet, we must first select a rq to compute the initial
6447 if (sd_flag
& SD_BALANCE_FORK
)
6450 if (this_spare
> task_util(p
) / 2 &&
6451 imbalance_scale
*this_spare
> 100*most_spare
)
6454 if (most_spare
> task_util(p
) / 2)
6455 return most_spare_sg
;
6461 if (min_runnable_load
> (this_runnable_load
+ imbalance
))
6464 if ((this_runnable_load
< (min_runnable_load
+ imbalance
)) &&
6465 (100*this_avg_load
< imbalance_scale
*min_avg_load
))
6472 * find_idlest_group_cpu - find the idlest cpu among the cpus in group.
6475 find_idlest_group_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
6477 unsigned long load
, min_load
= ULONG_MAX
;
6478 unsigned int min_exit_latency
= UINT_MAX
;
6479 u64 latest_idle_timestamp
= 0;
6480 int least_loaded_cpu
= this_cpu
;
6481 int shallowest_idle_cpu
= -1;
6484 /* Check if we have any choice: */
6485 if (group
->group_weight
== 1)
6486 return cpumask_first(sched_group_span(group
));
6488 /* Traverse only the allowed CPUs */
6489 for_each_cpu_and(i
, sched_group_span(group
), &p
->cpus_allowed
) {
6491 struct rq
*rq
= cpu_rq(i
);
6492 struct cpuidle_state
*idle
= idle_get_state(rq
);
6493 if (idle
&& idle
->exit_latency
< min_exit_latency
) {
6495 * We give priority to a CPU whose idle state
6496 * has the smallest exit latency irrespective
6497 * of any idle timestamp.
6499 min_exit_latency
= idle
->exit_latency
;
6500 latest_idle_timestamp
= rq
->idle_stamp
;
6501 shallowest_idle_cpu
= i
;
6502 } else if ((!idle
|| idle
->exit_latency
== min_exit_latency
) &&
6503 rq
->idle_stamp
> latest_idle_timestamp
) {
6505 * If equal or no active idle state, then
6506 * the most recently idled CPU might have
6509 latest_idle_timestamp
= rq
->idle_stamp
;
6510 shallowest_idle_cpu
= i
;
6512 } else if (shallowest_idle_cpu
== -1) {
6513 load
= weighted_cpuload(cpu_rq(i
));
6514 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
6516 least_loaded_cpu
= i
;
6521 return shallowest_idle_cpu
!= -1 ? shallowest_idle_cpu
: least_loaded_cpu
;
6524 static inline int find_idlest_cpu(struct sched_domain
*sd
, struct task_struct
*p
,
6525 int cpu
, int prev_cpu
, int sd_flag
)
6529 if (!cpumask_intersects(sched_domain_span(sd
), &p
->cpus_allowed
))
6533 struct sched_group
*group
;
6534 struct sched_domain
*tmp
;
6537 if (!(sd
->flags
& sd_flag
)) {
6542 group
= find_idlest_group(sd
, p
, cpu
, sd_flag
);
6548 new_cpu
= find_idlest_group_cpu(group
, p
, cpu
);
6549 if (new_cpu
== cpu
) {
6550 /* Now try balancing at a lower domain level of cpu */
6555 /* Now try balancing at a lower domain level of new_cpu */
6557 weight
= sd
->span_weight
;
6559 for_each_domain(cpu
, tmp
) {
6560 if (weight
<= tmp
->span_weight
)
6562 if (tmp
->flags
& sd_flag
)
6565 /* while loop will break here if sd == NULL */
6571 #ifdef CONFIG_SCHED_SMT
6573 static inline void set_idle_cores(int cpu
, int val
)
6575 struct sched_domain_shared
*sds
;
6577 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
6579 WRITE_ONCE(sds
->has_idle_cores
, val
);
6582 static inline bool test_idle_cores(int cpu
, bool def
)
6584 struct sched_domain_shared
*sds
;
6586 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
6588 return READ_ONCE(sds
->has_idle_cores
);
6594 * Scans the local SMT mask to see if the entire core is idle, and records this
6595 * information in sd_llc_shared->has_idle_cores.
6597 * Since SMT siblings share all cache levels, inspecting this limited remote
6598 * state should be fairly cheap.
6600 void __update_idle_core(struct rq
*rq
)
6602 int core
= cpu_of(rq
);
6606 if (test_idle_cores(core
, true))
6609 for_each_cpu(cpu
, cpu_smt_mask(core
)) {
6617 set_idle_cores(core
, 1);
6623 * Scan the entire LLC domain for idle cores; this dynamically switches off if
6624 * there are no idle cores left in the system; tracked through
6625 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6627 static int select_idle_core(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6629 struct cpumask
*cpus
= this_cpu_cpumask_var_ptr(select_idle_mask
);
6632 if (!static_branch_likely(&sched_smt_present
))
6635 if (!test_idle_cores(target
, false))
6638 cpumask_and(cpus
, sched_domain_span(sd
), &p
->cpus_allowed
);
6640 for_each_cpu_wrap(core
, cpus
, target
) {
6643 for_each_cpu(cpu
, cpu_smt_mask(core
)) {
6644 cpumask_clear_cpu(cpu
, cpus
);
6654 * Failed to find an idle core; stop looking for one.
6656 set_idle_cores(target
, 0);
6662 * Scan the local SMT mask for idle CPUs.
6664 static int select_idle_smt(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6668 if (!static_branch_likely(&sched_smt_present
))
6671 for_each_cpu(cpu
, cpu_smt_mask(target
)) {
6672 if (!cpumask_test_cpu(cpu
, &p
->cpus_allowed
))
6681 #else /* CONFIG_SCHED_SMT */
6683 static inline int select_idle_core(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6688 static inline int select_idle_smt(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6693 #endif /* CONFIG_SCHED_SMT */
6696 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6697 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6698 * average idle time for this rq (as found in rq->avg_idle).
6700 static int select_idle_cpu(struct task_struct
*p
, struct sched_domain
*sd
, int target
)
6702 struct sched_domain
*this_sd
;
6703 u64 avg_cost
, avg_idle
;
6706 int cpu
, nr
= INT_MAX
;
6708 this_sd
= rcu_dereference(*this_cpu_ptr(&sd_llc
));
6713 * Due to large variance we need a large fuzz factor; hackbench in
6714 * particularly is sensitive here.
6716 avg_idle
= this_rq()->avg_idle
/ 512;
6717 avg_cost
= this_sd
->avg_scan_cost
+ 1;
6719 if (sched_feat(SIS_AVG_CPU
) && avg_idle
< avg_cost
)
6722 if (sched_feat(SIS_PROP
)) {
6723 u64 span_avg
= sd
->span_weight
* avg_idle
;
6724 if (span_avg
> 4*avg_cost
)
6725 nr
= div_u64(span_avg
, avg_cost
);
6730 time
= local_clock();
6732 for_each_cpu_wrap(cpu
, sched_domain_span(sd
), target
) {
6735 if (!cpumask_test_cpu(cpu
, &p
->cpus_allowed
))
6741 time
= local_clock() - time
;
6742 cost
= this_sd
->avg_scan_cost
;
6743 delta
= (s64
)(time
- cost
) / 8;
6744 this_sd
->avg_scan_cost
+= delta
;
6750 * Try and locate an idle core/thread in the LLC cache domain.
6752 static inline int __select_idle_sibling(struct task_struct
*p
, int prev
, int target
)
6754 struct sched_domain
*sd
;
6757 if (idle_cpu(target
))
6761 * If the previous cpu is cache affine and idle, don't be stupid.
6763 if (prev
!= target
&& cpus_share_cache(prev
, target
) && idle_cpu(prev
))
6766 sd
= rcu_dereference(per_cpu(sd_llc
, target
));
6770 i
= select_idle_core(p
, sd
, target
);
6771 if ((unsigned)i
< nr_cpumask_bits
)
6774 i
= select_idle_cpu(p
, sd
, target
);
6775 if ((unsigned)i
< nr_cpumask_bits
)
6778 i
= select_idle_smt(p
, sd
, target
);
6779 if ((unsigned)i
< nr_cpumask_bits
)
6785 static inline int select_idle_sibling_cstate_aware(struct task_struct
*p
, int prev
, int target
)
6787 struct sched_domain
*sd
;
6788 struct sched_group
*sg
;
6789 int best_idle_cpu
= -1;
6790 int best_idle_cstate
= -1;
6791 int best_idle_capacity
= INT_MAX
;
6795 * Iterate the domains and find an elegible idle cpu.
6797 sd
= rcu_dereference(per_cpu(sd_llc
, target
));
6798 for_each_lower_domain(sd
) {
6801 if (!cpumask_intersects(
6802 sched_group_span(sg
), &p
->cpus_allowed
))
6805 for_each_cpu_and(i
, &p
->cpus_allowed
, sched_group_span(sg
)) {
6807 unsigned long new_usage
;
6808 unsigned long capacity_orig
;
6813 /* figure out if the task can fit here at all */
6814 new_usage
= boosted_task_util(p
);
6815 capacity_orig
= capacity_orig_of(i
);
6817 if (new_usage
> capacity_orig
)
6820 /* if the task fits without changing OPP and we
6821 * intended to use this CPU, just proceed
6823 if (i
== target
&& new_usage
<= capacity_curr_of(target
)) {
6827 /* otherwise select CPU with shallowest idle state
6828 * to reduce wakeup latency.
6830 idle_idx
= idle_get_state_idx(cpu_rq(i
));
6832 if (idle_idx
< best_idle_cstate
&&
6833 capacity_orig
<= best_idle_capacity
) {
6835 best_idle_cstate
= idle_idx
;
6836 best_idle_capacity
= capacity_orig
;
6841 } while (sg
!= sd
->groups
);
6844 if (best_idle_cpu
>= 0)
6845 target
= best_idle_cpu
;
6850 static int select_idle_sibling(struct task_struct
*p
, int prev
, int target
)
6852 if (!sysctl_sched_cstate_aware
)
6853 return __select_idle_sibling(p
, prev
, target
);
6855 return select_idle_sibling_cstate_aware(p
, prev
, target
);
6858 static inline unsigned long task_util(struct task_struct
*p
)
6860 #ifdef CONFIG_SCHED_WALT
6861 if (!walt_disabled
&& sysctl_sched_use_walt_task_util
) {
6862 return (p
->ravg
.demand
/ (walt_ravg_window
>> SCHED_CAPACITY_SHIFT
));
6865 return p
->se
.avg
.util_avg
;
6869 * cpu_util_wake: Compute cpu utilization with any contributions from
6870 * the waking task p removed.
6872 static int cpu_util_wake(int cpu
, struct task_struct
*p
)
6874 unsigned long util
, capacity
;
6876 #ifdef CONFIG_SCHED_WALT
6878 * WALT does not decay idle tasks in the same manner
6879 * as PELT, so it makes little sense to subtract task
6880 * utilization from cpu utilization. Instead just use
6881 * cpu_util for this case.
6883 if (!walt_disabled
&& sysctl_sched_use_walt_cpu_util
)
6884 return cpu_util(cpu
);
6886 /* Task has no contribution or is new */
6887 if (cpu
!= task_cpu(p
) || !p
->se
.avg
.last_update_time
)
6888 return cpu_util(cpu
);
6890 capacity
= capacity_orig_of(cpu
);
6891 util
= max_t(long, cpu_rq(cpu
)->cfs
.avg
.util_avg
- task_util(p
), 0);
6893 return (util
>= capacity
) ? capacity
: util
;
6896 static inline int task_fits_capacity(struct task_struct
*p
, long capacity
)
6898 return capacity
* 1024 > boosted_task_util(p
) * capacity_margin
;
6901 static int start_cpu(bool boosted
)
6903 struct root_domain
*rd
= cpu_rq(smp_processor_id())->rd
;
6905 return boosted
? rd
->max_cap_orig_cpu
: rd
->min_cap_orig_cpu
;
6908 static inline int find_best_target(struct task_struct
*p
, int *backup_cpu
,
6909 bool boosted
, bool prefer_idle
)
6911 unsigned long min_util
= boosted_task_util(p
);
6912 unsigned long target_capacity
= ULONG_MAX
;
6913 unsigned long min_wake_util
= ULONG_MAX
;
6914 unsigned long target_max_spare_cap
= 0;
6915 unsigned long target_util
= ULONG_MAX
;
6916 unsigned long best_active_util
= ULONG_MAX
;
6917 int best_idle_cstate
= INT_MAX
;
6918 struct sched_domain
*sd
;
6919 struct sched_group
*sg
;
6920 int best_active_cpu
= -1;
6921 int best_idle_cpu
= -1;
6922 int target_cpu
= -1;
6927 /* Find start CPU based on boost value */
6928 cpu
= start_cpu(boosted
);
6932 /* Find SD for the start CPU */
6933 sd
= rcu_dereference(per_cpu(sd_ea
, cpu
));
6937 /* Scan CPUs in all SDs */
6940 for_each_cpu_and(i
, &p
->cpus_allowed
, sched_group_span(sg
)) {
6941 unsigned long capacity_curr
= capacity_curr_of(i
);
6942 unsigned long capacity_orig
= capacity_orig_of(i
);
6943 unsigned long wake_util
, new_util
;
6949 if (walt_cpu_high_irqload(i
))
6953 * p's blocked utilization is still accounted for on prev_cpu
6954 * so prev_cpu will receive a negative bias due to the double
6955 * accounting. However, the blocked utilization may be zero.
6957 wake_util
= cpu_util_wake(i
, p
);
6958 new_util
= wake_util
+ task_util(p
);
6961 * Ensure minimum capacity to grant the required boost.
6962 * The target CPU can be already at a capacity level higher
6963 * than the one required to boost the task.
6965 new_util
= max(min_util
, new_util
);
6966 if (new_util
> capacity_orig
)
6970 * Pre-compute the maximum possible capacity we expect
6971 * to have available on this CPU once the task is
6974 spare_cap
= capacity_orig
- new_util
;
6977 * Case A) Latency sensitive tasks
6979 * Unconditionally favoring tasks that prefer idle CPU to
6983 * - an idle CPU, whatever its idle_state is, since
6984 * the first CPUs we explore are more likely to be
6985 * reserved for latency sensitive tasks.
6986 * - a non idle CPU where the task fits in its current
6987 * capacity and has the maximum spare capacity.
6988 * - a non idle CPU with lower contention from other
6989 * tasks and running at the lowest possible OPP.
6991 * The last two goals tries to favor a non idle CPU
6992 * where the task can run as if it is "almost alone".
6993 * A maximum spare capacity CPU is favoured since
6994 * the task already fits into that CPU's capacity
6995 * without waiting for an OPP chance.
6997 * The following code path is the only one in the CPUs
6998 * exploration loop which is always used by
6999 * prefer_idle tasks. It exits the loop with wither a
7000 * best_active_cpu or a target_cpu which should
7001 * represent an optimal choice for latency sensitive
7007 * Case A.1: IDLE CPU
7008 * Return the first IDLE CPU we find.
7011 trace_sched_find_best_target(p
,
7012 prefer_idle
, min_util
,
7014 best_active_cpu
, i
);
7020 * Case A.2: Target ACTIVE CPU
7021 * Favor CPUs with max spare capacity.
7023 if (capacity_curr
> new_util
&&
7024 spare_cap
> target_max_spare_cap
) {
7025 target_max_spare_cap
= spare_cap
;
7029 if (target_cpu
!= -1)
7034 * Case A.3: Backup ACTIVE CPU
7036 * - lower utilization due to other tasks
7037 * - lower utilization with the task in
7039 if (wake_util
> min_wake_util
)
7041 if (new_util
> best_active_util
)
7043 min_wake_util
= wake_util
;
7044 best_active_util
= new_util
;
7045 best_active_cpu
= i
;
7052 * For non latency sensitive tasks, skip CPUs that
7053 * will be overutilized by moving the task there.
7055 * The goal here is to remain in EAS mode as long as
7056 * possible at least for !prefer_idle tasks.
7058 if ((new_util
* capacity_margin
) >
7059 (capacity_orig
* SCHED_CAPACITY_SCALE
))
7063 * Favor CPUs with smaller capacity for non latency
7066 if (capacity_orig
> target_capacity
)
7070 * Case B) Non latency sensitive tasks on IDLE CPUs.
7072 * Find an optimal backup IDLE CPU for non latency
7076 * - minimizing the capacity_orig,
7077 * i.e. preferring LITTLE CPUs
7078 * - favoring shallowest idle states
7079 * i.e. avoid to wakeup deep-idle CPUs
7081 * The following code path is used by non latency
7082 * sensitive tasks if IDLE CPUs are available. If at
7083 * least one of such CPUs are available it sets the
7084 * best_idle_cpu to the most suitable idle CPU to be
7087 * If idle CPUs are available, favour these CPUs to
7088 * improve performances by spreading tasks.
7089 * Indeed, the energy_diff() computed by the caller
7090 * will take care to ensure the minimization of energy
7091 * consumptions without affecting performance.
7094 int idle_idx
= idle_get_state_idx(cpu_rq(i
));
7097 * Skip CPUs in deeper idle state, but only
7098 * if they are also less energy efficient.
7099 * IOW, prefer a deep IDLE LITTLE CPU vs a
7100 * shallow idle big CPU.
7102 if (capacity_orig
== target_capacity
&&
7103 sysctl_sched_cstate_aware
&&
7104 best_idle_cstate
<= idle_idx
)
7107 target_capacity
= capacity_orig
;
7108 best_idle_cstate
= idle_idx
;
7114 * Case C) Non latency sensitive tasks on ACTIVE CPUs.
7116 * Pack tasks in the most energy efficient capacities.
7118 * This task packing strategy prefers more energy
7119 * efficient CPUs (i.e. pack on smaller maximum
7120 * capacity CPUs) while also trying to spread tasks to
7121 * run them all at the lower OPP.
7123 * This assumes for example that it's more energy
7124 * efficient to run two tasks on two CPUs at a lower
7125 * OPP than packing both on a single CPU but running
7126 * that CPU at an higher OPP.
7128 * Thus, this case keep track of the CPU with the
7129 * smallest maximum capacity and highest spare maximum
7133 /* Favor CPUs with maximum spare capacity */
7134 if (capacity_orig
== target_capacity
&&
7135 spare_cap
< target_max_spare_cap
)
7138 target_max_spare_cap
= spare_cap
;
7139 target_capacity
= capacity_orig
;
7140 target_util
= new_util
;
7144 } while (sg
= sg
->next
, sg
!= sd
->groups
);
7147 * For non latency sensitive tasks, cases B and C in the previous loop,
7148 * we pick the best IDLE CPU only if we was not able to find a target
7151 * Policies priorities:
7153 * - prefer_idle tasks:
7155 * a) IDLE CPU available, we return immediately
7156 * b) ACTIVE CPU where task fits and has the bigger maximum spare
7157 * capacity (i.e. target_cpu)
7158 * c) ACTIVE CPU with less contention due to other tasks
7159 * (i.e. best_active_cpu)
7161 * - NON prefer_idle tasks:
7163 * a) ACTIVE CPU: target_cpu
7164 * b) IDLE CPU: best_idle_cpu
7166 if (target_cpu
== -1)
7167 target_cpu
= prefer_idle
7171 *backup_cpu
= prefer_idle
7175 trace_sched_find_best_target(p
, prefer_idle
, min_util
, cpu
,
7176 best_idle_cpu
, best_active_cpu
,
7179 /* it is possible for target and backup
7180 * to select same CPU - if so, drop backup
7182 if (*backup_cpu
== target_cpu
)
7189 * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
7190 * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
7192 * In that case WAKE_AFFINE doesn't make sense and we'll let
7193 * BALANCE_WAKE sort things out.
7195 static int wake_cap(struct task_struct
*p
, int cpu
, int prev_cpu
)
7197 long min_cap
, max_cap
;
7199 if (!static_branch_unlikely(&sched_asym_cpucapacity
))
7202 min_cap
= min(capacity_orig_of(prev_cpu
), capacity_orig_of(cpu
));
7203 max_cap
= cpu_rq(cpu
)->rd
->max_cpu_capacity
;
7205 /* Minimum capacity is close to max, no need to abort wake_affine */
7206 if (max_cap
- min_cap
< max_cap
>> 3)
7209 /* Bring task utilization in sync with prev_cpu */
7210 sync_entity_load_avg(&p
->se
);
7212 return !task_fits_capacity(p
, min_cap
);
7215 static bool cpu_overutilized(int cpu
)
7217 return (capacity_of(cpu
) * 1024) < (cpu_util(cpu
) * capacity_margin
);
7220 DEFINE_PER_CPU(struct energy_env
, eenv_cache
);
7222 /* kernels often have NR_CPUS defined to be much
7223 * larger than exist in practise on booted systems.
7224 * Allocate the cpu array for eenv calculations
7225 * at boot time to avoid massive overprovisioning.
7227 #ifdef DEBUG_EENV_DECISIONS
7228 static inline int eenv_debug_size_per_dbg_entry(void)
7230 return sizeof(struct _eenv_debug
) + (sizeof(unsigned long) * num_possible_cpus());
7233 static inline int eenv_debug_size_per_cpu_entry(void)
7235 /* each cpu struct has an array of _eenv_debug structs
7236 * which have an array of unsigned longs at the end -
7237 * the allocation should be extended so that there are
7238 * at least 'num_possible_cpus' entries in the array.
7240 return EAS_EENV_DEBUG_LEVELS
* eenv_debug_size_per_dbg_entry();
7242 /* given a per-_eenv_cpu debug env ptr, get the ptr for a given index */
7243 static inline struct _eenv_debug
*eenv_debug_entry_ptr(struct _eenv_debug
*base
, int idx
)
7245 char *ptr
= (char *)base
;
7246 ptr
+= (idx
* eenv_debug_size_per_dbg_entry());
7247 return (struct _eenv_debug
*)ptr
;
7249 /* given a pointer to the per-cpu global copy of _eenv_debug, get
7250 * a pointer to the specified _eenv_cpu debug env.
7252 static inline struct _eenv_debug
*eenv_debug_percpu_debug_env_ptr(struct _eenv_debug
*base
, int cpu_idx
)
7254 char *ptr
= (char *)base
;
7255 ptr
+= (cpu_idx
* eenv_debug_size_per_cpu_entry());
7256 return (struct _eenv_debug
*)ptr
;
7259 static inline int eenv_debug_size(void)
7261 return num_possible_cpus() * eenv_debug_size_per_cpu_entry();
7265 static inline void alloc_eenv(void)
7268 int cpu_count
= num_possible_cpus();
7270 for_each_possible_cpu(cpu
) {
7271 struct energy_env
*eenv
= &per_cpu(eenv_cache
, cpu
);
7272 eenv
->cpu
= kmalloc(sizeof(struct eenv_cpu
) * cpu_count
, GFP_KERNEL
);
7273 eenv
->eenv_cpu_count
= cpu_count
;
7274 #ifdef DEBUG_EENV_DECISIONS
7275 eenv
->debug
= (struct _eenv_debug
*)kmalloc(eenv_debug_size(), GFP_KERNEL
);
7280 static inline void reset_eenv(struct energy_env
*eenv
)
7283 struct eenv_cpu
*cpu
;
7284 #ifdef DEBUG_EENV_DECISIONS
7285 struct _eenv_debug
*debug
;
7287 debug
= eenv
->debug
;
7290 cpu_count
= eenv
->eenv_cpu_count
;
7292 memset(eenv
, 0, sizeof(struct energy_env
));
7294 memset(eenv
->cpu
, 0, sizeof(struct eenv_cpu
)*cpu_count
);
7295 eenv
->eenv_cpu_count
= cpu_count
;
7297 #ifdef DEBUG_EENV_DECISIONS
7298 memset(debug
, 0, eenv_debug_size());
7299 eenv
->debug
= debug
;
7300 for(cpu_idx
= 0; cpu_idx
< eenv
->cpu_array_len
; cpu_idx
++)
7301 eenv
->cpu
[cpu_idx
].debug
= eenv_debug_percpu_debug_env_ptr(debug
, cpu_idx
);
7305 * get_eenv - reset the eenv struct cached for this CPU
7307 * When the eenv is returned, it is configured to do
7308 * energy calculations for the maximum number of CPUs
7309 * the task can be placed on. The prev_cpu entry is
7310 * filled in here. Callers are responsible for adding
7311 * other CPU candidates up to eenv->max_cpu_count.
7313 static inline struct energy_env
*get_eenv(struct task_struct
*p
, int prev_cpu
)
7315 struct energy_env
*eenv
;
7316 cpumask_t cpumask_possible_cpus
;
7317 int cpu
= smp_processor_id();
7320 eenv
= &(per_cpu(eenv_cache
, cpu
));
7325 /* use boosted task util for capacity selection
7326 * during energy calculation, but unboosted task
7327 * util for group utilization calculations
7329 eenv
->util_delta
= task_util(p
);
7330 eenv
->util_delta_boosted
= boosted_task_util(p
);
7332 cpumask_and(&cpumask_possible_cpus
, &p
->cpus_allowed
, cpu_online_mask
);
7333 eenv
->max_cpu_count
= cpumask_weight(&cpumask_possible_cpus
);
7335 for (i
=0; i
< eenv
->max_cpu_count
; i
++)
7336 eenv
->cpu
[i
].cpu_id
= -1;
7337 eenv
->cpu
[EAS_CPU_PRV
].cpu_id
= prev_cpu
;
7338 eenv
->next_idx
= EAS_CPU_PRV
;
7344 * Needs to be called inside rcu_read_lock critical section.
7345 * sd is a pointer to the sched domain we wish to use for an
7346 * energy-aware placement option.
7348 static int find_energy_efficient_cpu(struct sched_domain
*sd
,
7349 struct task_struct
*p
,
7350 int cpu
, int prev_cpu
,
7353 int use_fbt
= sched_feat(FIND_BEST_TARGET
);
7354 int cpu_iter
, eas_cpu_idx
= EAS_CPU_NXT
;
7355 int energy_cpu
= -1;
7356 struct energy_env
*eenv
;
7358 if (sysctl_sched_sync_hint_enable
&& sync
) {
7359 if (cpumask_test_cpu(cpu
, &p
->cpus_allowed
)) {
7364 /* prepopulate energy diff environment */
7365 eenv
= get_eenv(p
, prev_cpu
);
7366 if (eenv
->max_cpu_count
< 2)
7371 * using this function outside wakeup balance will not supply
7372 * an sd ptr. Instead, fetch the highest level with energy data.
7375 sd
= rcu_dereference(per_cpu(sd_ea
, prev_cpu
));
7377 for_each_cpu_and(cpu_iter
, &p
->cpus_allowed
, sched_domain_span(sd
)) {
7378 unsigned long spare
;
7380 /* prev_cpu already in list */
7381 if (cpu_iter
== prev_cpu
)
7384 spare
= capacity_spare_wake(cpu_iter
, p
);
7386 if (spare
* 1024 < capacity_margin
* task_util(p
))
7389 /* Add CPU candidate */
7390 eenv
->cpu
[eas_cpu_idx
++].cpu_id
= cpu_iter
;
7391 eenv
->max_cpu_count
= eas_cpu_idx
;
7393 /* stop adding CPUs if we have no space left */
7394 if (eas_cpu_idx
>= eenv
->eenv_cpu_count
)
7398 int boosted
= (schedtune_task_boost(p
) > 0);
7402 * give compiler a hint that if sched_features
7403 * cannot be changed, it is safe to optimise out
7404 * all if(prefer_idle) blocks.
7406 prefer_idle
= sched_feat(EAS_PREFER_IDLE
) ?
7407 (schedtune_prefer_idle(p
) > 0) : 0;
7409 eenv
->max_cpu_count
= EAS_CPU_BKP
+ 1;
7411 /* Find a cpu with sufficient capacity */
7412 eenv
->cpu
[EAS_CPU_NXT
].cpu_id
= find_best_target(p
,
7413 &eenv
->cpu
[EAS_CPU_BKP
].cpu_id
,
7414 boosted
, prefer_idle
);
7416 /* take note if no backup was found */
7417 if (eenv
->cpu
[EAS_CPU_BKP
].cpu_id
< 0)
7418 eenv
->max_cpu_count
= EAS_CPU_BKP
;
7420 /* take note if no target was found */
7421 if (eenv
->cpu
[EAS_CPU_NXT
].cpu_id
< 0)
7422 eenv
->max_cpu_count
= EAS_CPU_NXT
;
7425 if (eenv
->max_cpu_count
== EAS_CPU_NXT
) {
7427 * we did not find any energy-awareness
7428 * candidates beyond prev_cpu, so we will
7429 * fall-back to the regular slow-path.
7434 /* find most energy-efficient CPU */
7435 energy_cpu
= select_energy_cpu_idx(eenv
) < 0 ? -1 :
7436 eenv
->cpu
[eenv
->next_idx
].cpu_id
;
7441 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
);
7442 static void nohz_balancer_kick(bool only_update
);
7445 * wake_energy: Make the decision if we want to use an energy-aware
7446 * wakeup task placement or not. This is limited to situations where
7447 * we cannot use energy-awareness right now.
7449 * Returns TRUE if we should attempt energy-aware wakeup, FALSE if not.
7451 * Should only be called from select_task_rq_fair inside the RCU
7452 * read-side critical section.
7454 static inline int wake_energy(struct task_struct
*p
, int prev_cpu
,
7455 int sd_flag
, int wake_flags
)
7457 struct sched_domain
*sd
= NULL
;
7458 int sync
= wake_flags
& WF_SYNC
;
7460 sd
= rcu_dereference_sched(cpu_rq(prev_cpu
)->sd
);
7463 * Check all definite no-energy-awareness conditions
7468 if (!energy_aware())
7471 if (sd_overutilized(sd
))
7475 * we cannot do energy-aware wakeup placement sensibly
7476 * for tasks with 0 utilization, so let them be placed
7477 * according to the normal strategy.
7478 * However if fbt is in use we may still benefit from
7479 * the heuristics we use there in selecting candidate
7482 if (unlikely(!sched_feat(FIND_BEST_TARGET
) && !task_util(p
)))
7485 if(!sched_feat(EAS_PREFER_IDLE
)){
7487 * Force prefer-idle tasks into the slow path, this may not happen
7488 * if none of the sd flags matched.
7490 if (schedtune_prefer_idle(p
) > 0 && !sync
)
7497 * select_task_rq_fair: Select target runqueue for the waking task in domains
7498 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
7499 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7501 * Balances load by selecting the idlest cpu in the idlest group, or under
7502 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
7504 * Returns the target cpu number.
7506 * preempt must be disabled.
7509 select_task_rq_fair(struct task_struct
*p
, int prev_cpu
, int sd_flag
, int wake_flags
,
7510 int sibling_count_hint
)
7512 struct sched_domain
*tmp
, *affine_sd
= NULL
;
7513 struct sched_domain
*sd
= NULL
, *energy_sd
= NULL
;
7514 int cpu
= smp_processor_id();
7515 int new_cpu
= prev_cpu
;
7516 int want_affine
= 0;
7517 int want_energy
= 0;
7518 int sync
= wake_flags
& WF_SYNC
;
7522 if (sd_flag
& SD_BALANCE_WAKE
) {
7524 want_energy
= wake_energy(p
, prev_cpu
, sd_flag
, wake_flags
);
7525 want_affine
= !want_energy
&&
7526 !wake_wide(p
, sibling_count_hint
) &&
7527 !wake_cap(p
, cpu
, prev_cpu
) &&
7528 cpumask_test_cpu(cpu
, &p
->cpus_allowed
);
7531 for_each_domain(cpu
, tmp
) {
7532 if (!(tmp
->flags
& SD_LOAD_BALANCE
))
7536 * If both cpu and prev_cpu are part of this domain,
7537 * cpu is a valid SD_WAKE_AFFINE target.
7539 if (want_affine
&& (tmp
->flags
& SD_WAKE_AFFINE
) &&
7540 cpumask_test_cpu(prev_cpu
, sched_domain_span(tmp
))) {
7546 * If we are able to try an energy-aware wakeup,
7547 * select the highest non-overutilized sched domain
7548 * which includes this cpu and prev_cpu
7550 * maybe want to not test prev_cpu and only consider
7554 !sd_overutilized(tmp
) &&
7555 cpumask_test_cpu(prev_cpu
, sched_domain_span(tmp
)))
7558 if (tmp
->flags
& sd_flag
)
7560 else if (!(want_affine
|| want_energy
))
7565 sd
= NULL
; /* Prefer wake_affine over balance flags */
7566 if (cpu
== prev_cpu
)
7569 if (wake_affine(affine_sd
, p
, prev_cpu
, sync
))
7573 if (sd
&& !(sd_flag
& SD_BALANCE_FORK
)) {
7575 * We're going to need the task's util for capacity_spare_wake
7576 * in find_idlest_group. Sync it up to prev_cpu's
7579 sync_entity_load_avg(&p
->se
);
7584 if (sd_flag
& SD_BALANCE_WAKE
) /* XXX always ? */
7585 new_cpu
= select_idle_sibling(p
, prev_cpu
, new_cpu
);
7589 new_cpu
= find_energy_efficient_cpu(energy_sd
, p
, cpu
, prev_cpu
, sync
);
7591 /* if we did an energy-aware placement and had no choices available
7592 * then fall back to the default find_idlest_cpu choice
7594 if (!energy_sd
|| (energy_sd
&& new_cpu
== -1))
7595 new_cpu
= find_idlest_cpu(sd
, p
, cpu
, prev_cpu
, sd_flag
);
7600 #ifdef CONFIG_NO_HZ_COMMON
7601 if (nohz_kick_needed(cpu_rq(new_cpu
), true))
7602 nohz_balancer_kick(true);
7609 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
7610 * cfs_rq_of(p) references at time of call are still valid and identify the
7611 * previous cpu. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7613 static void migrate_task_rq_fair(struct task_struct
*p
)
7616 * As blocked tasks retain absolute vruntime the migration needs to
7617 * deal with this by subtracting the old and adding the new
7618 * min_vruntime -- the latter is done by enqueue_entity() when placing
7619 * the task on the new runqueue.
7621 if (p
->state
== TASK_WAKING
) {
7622 struct sched_entity
*se
= &p
->se
;
7623 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
7626 #ifndef CONFIG_64BIT
7627 u64 min_vruntime_copy
;
7630 min_vruntime_copy
= cfs_rq
->min_vruntime_copy
;
7632 min_vruntime
= cfs_rq
->min_vruntime
;
7633 } while (min_vruntime
!= min_vruntime_copy
);
7635 min_vruntime
= cfs_rq
->min_vruntime
;
7638 se
->vruntime
-= min_vruntime
;
7642 * We are supposed to update the task to "current" time, then its up to date
7643 * and ready to go to new CPU/cfs_rq. But we have difficulty in getting
7644 * what current time is, so simply throw away the out-of-date time. This
7645 * will result in the wakee task is less decayed, but giving the wakee more
7646 * load sounds not bad.
7648 remove_entity_load_avg(&p
->se
);
7650 /* Tell new CPU we are migrated */
7651 p
->se
.avg
.last_update_time
= 0;
7653 /* We have migrated, no longer consider this task hot */
7654 p
->se
.exec_start
= 0;
7657 static void task_dead_fair(struct task_struct
*p
)
7659 remove_entity_load_avg(&p
->se
);
7661 #endif /* CONFIG_SMP */
7663 static unsigned long
7664 wakeup_gran(struct sched_entity
*curr
, struct sched_entity
*se
)
7666 unsigned long gran
= sysctl_sched_wakeup_granularity
;
7669 * Since its curr running now, convert the gran from real-time
7670 * to virtual-time in his units.
7672 * By using 'se' instead of 'curr' we penalize light tasks, so
7673 * they get preempted easier. That is, if 'se' < 'curr' then
7674 * the resulting gran will be larger, therefore penalizing the
7675 * lighter, if otoh 'se' > 'curr' then the resulting gran will
7676 * be smaller, again penalizing the lighter task.
7678 * This is especially important for buddies when the leftmost
7679 * task is higher priority than the buddy.
7681 return calc_delta_fair(gran
, se
);
7685 * Should 'se' preempt 'curr'.
7699 wakeup_preempt_entity(struct sched_entity
*curr
, struct sched_entity
*se
)
7701 s64 gran
, vdiff
= curr
->vruntime
- se
->vruntime
;
7706 gran
= wakeup_gran(curr
, se
);
7713 static void set_last_buddy(struct sched_entity
*se
)
7715 if (entity_is_task(se
) && unlikely(task_of(se
)->policy
== SCHED_IDLE
))
7718 for_each_sched_entity(se
) {
7719 if (SCHED_WARN_ON(!se
->on_rq
))
7721 cfs_rq_of(se
)->last
= se
;
7725 static void set_next_buddy(struct sched_entity
*se
)
7727 if (entity_is_task(se
) && unlikely(task_of(se
)->policy
== SCHED_IDLE
))
7730 for_each_sched_entity(se
) {
7731 if (SCHED_WARN_ON(!se
->on_rq
))
7733 cfs_rq_of(se
)->next
= se
;
7737 static void set_skip_buddy(struct sched_entity
*se
)
7739 for_each_sched_entity(se
)
7740 cfs_rq_of(se
)->skip
= se
;
7744 * Preempt the current task with a newly woken task if needed:
7746 static void check_preempt_wakeup(struct rq
*rq
, struct task_struct
*p
, int wake_flags
)
7748 struct task_struct
*curr
= rq
->curr
;
7749 struct sched_entity
*se
= &curr
->se
, *pse
= &p
->se
;
7750 struct cfs_rq
*cfs_rq
= task_cfs_rq(curr
);
7751 int scale
= cfs_rq
->nr_running
>= sched_nr_latency
;
7752 int next_buddy_marked
= 0;
7754 if (unlikely(se
== pse
))
7758 * This is possible from callers such as attach_tasks(), in which we
7759 * unconditionally check_prempt_curr() after an enqueue (which may have
7760 * lead to a throttle). This both saves work and prevents false
7761 * next-buddy nomination below.
7763 if (unlikely(throttled_hierarchy(cfs_rq_of(pse
))))
7766 if (sched_feat(NEXT_BUDDY
) && scale
&& !(wake_flags
& WF_FORK
)) {
7767 set_next_buddy(pse
);
7768 next_buddy_marked
= 1;
7772 * We can come here with TIF_NEED_RESCHED already set from new task
7775 * Note: this also catches the edge-case of curr being in a throttled
7776 * group (e.g. via set_curr_task), since update_curr() (in the
7777 * enqueue of curr) will have resulted in resched being set. This
7778 * prevents us from potentially nominating it as a false LAST_BUDDY
7781 if (test_tsk_need_resched(curr
))
7784 /* Idle tasks are by definition preempted by non-idle tasks. */
7785 if (unlikely(curr
->policy
== SCHED_IDLE
) &&
7786 likely(p
->policy
!= SCHED_IDLE
))
7790 * Batch and idle tasks do not preempt non-idle tasks (their preemption
7791 * is driven by the tick):
7793 if (unlikely(p
->policy
!= SCHED_NORMAL
) || !sched_feat(WAKEUP_PREEMPTION
))
7796 find_matching_se(&se
, &pse
);
7797 update_curr(cfs_rq_of(se
));
7799 if (wakeup_preempt_entity(se
, pse
) == 1) {
7801 * Bias pick_next to pick the sched entity that is
7802 * triggering this preemption.
7804 if (!next_buddy_marked
)
7805 set_next_buddy(pse
);
7814 * Only set the backward buddy when the current task is still
7815 * on the rq. This can happen when a wakeup gets interleaved
7816 * with schedule on the ->pre_schedule() or idle_balance()
7817 * point, either of which can * drop the rq lock.
7819 * Also, during early boot the idle thread is in the fair class,
7820 * for obvious reasons its a bad idea to schedule back to it.
7822 if (unlikely(!se
->on_rq
|| curr
== rq
->idle
))
7825 if (sched_feat(LAST_BUDDY
) && scale
&& entity_is_task(se
))
7829 static struct task_struct
*
7830 pick_next_task_fair(struct rq
*rq
, struct task_struct
*prev
, struct rq_flags
*rf
)
7832 struct cfs_rq
*cfs_rq
= &rq
->cfs
;
7833 struct sched_entity
*se
;
7834 struct task_struct
*p
;
7838 if (!cfs_rq
->nr_running
)
7841 #ifdef CONFIG_FAIR_GROUP_SCHED
7842 if (prev
->sched_class
!= &fair_sched_class
)
7846 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7847 * likely that a next task is from the same cgroup as the current.
7849 * Therefore attempt to avoid putting and setting the entire cgroup
7850 * hierarchy, only change the part that actually changes.
7854 struct sched_entity
*curr
= cfs_rq
->curr
;
7857 * Since we got here without doing put_prev_entity() we also
7858 * have to consider cfs_rq->curr. If it is still a runnable
7859 * entity, update_curr() will update its vruntime, otherwise
7860 * forget we've ever seen it.
7864 update_curr(cfs_rq
);
7869 * This call to check_cfs_rq_runtime() will do the
7870 * throttle and dequeue its entity in the parent(s).
7871 * Therefore the nr_running test will indeed
7874 if (unlikely(check_cfs_rq_runtime(cfs_rq
))) {
7877 if (!cfs_rq
->nr_running
)
7884 se
= pick_next_entity(cfs_rq
, curr
);
7885 cfs_rq
= group_cfs_rq(se
);
7891 * Since we haven't yet done put_prev_entity and if the selected task
7892 * is a different task than we started out with, try and touch the
7893 * least amount of cfs_rqs.
7896 struct sched_entity
*pse
= &prev
->se
;
7898 while (!(cfs_rq
= is_same_group(se
, pse
))) {
7899 int se_depth
= se
->depth
;
7900 int pse_depth
= pse
->depth
;
7902 if (se_depth
<= pse_depth
) {
7903 put_prev_entity(cfs_rq_of(pse
), pse
);
7904 pse
= parent_entity(pse
);
7906 if (se_depth
>= pse_depth
) {
7907 set_next_entity(cfs_rq_of(se
), se
);
7908 se
= parent_entity(se
);
7912 put_prev_entity(cfs_rq
, pse
);
7913 set_next_entity(cfs_rq
, se
);
7916 if (hrtick_enabled(rq
))
7917 hrtick_start_fair(rq
, p
);
7919 update_misfit_status(p
, rq
);
7925 put_prev_task(rq
, prev
);
7928 se
= pick_next_entity(cfs_rq
, NULL
);
7929 set_next_entity(cfs_rq
, se
);
7930 cfs_rq
= group_cfs_rq(se
);
7935 if (hrtick_enabled(rq
))
7936 hrtick_start_fair(rq
, p
);
7938 update_misfit_status(p
, rq
);
7943 update_misfit_status(NULL
, rq
);
7944 new_tasks
= idle_balance(rq
, rf
);
7947 * Because idle_balance() releases (and re-acquires) rq->lock, it is
7948 * possible for any higher priority task to appear. In that case we
7949 * must re-start the pick_next_entity() loop.
7961 * Account for a descheduled task:
7963 static void put_prev_task_fair(struct rq
*rq
, struct task_struct
*prev
)
7965 struct sched_entity
*se
= &prev
->se
;
7966 struct cfs_rq
*cfs_rq
;
7968 for_each_sched_entity(se
) {
7969 cfs_rq
= cfs_rq_of(se
);
7970 put_prev_entity(cfs_rq
, se
);
7975 * sched_yield() is very simple
7977 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7979 static void yield_task_fair(struct rq
*rq
)
7981 struct task_struct
*curr
= rq
->curr
;
7982 struct cfs_rq
*cfs_rq
= task_cfs_rq(curr
);
7983 struct sched_entity
*se
= &curr
->se
;
7986 * Are we the only task in the tree?
7988 if (unlikely(rq
->nr_running
== 1))
7991 clear_buddies(cfs_rq
, se
);
7993 if (curr
->policy
!= SCHED_BATCH
) {
7994 update_rq_clock(rq
);
7996 * Update run-time statistics of the 'current'.
7998 update_curr(cfs_rq
);
8000 * Tell update_rq_clock() that we've just updated,
8001 * so we don't do microscopic update in schedule()
8002 * and double the fastpath cost.
8004 rq_clock_skip_update(rq
, true);
8010 static bool yield_to_task_fair(struct rq
*rq
, struct task_struct
*p
, bool preempt
)
8012 struct sched_entity
*se
= &p
->se
;
8014 /* throttled hierarchies are not runnable */
8015 if (!se
->on_rq
|| throttled_hierarchy(cfs_rq_of(se
)))
8018 /* Tell the scheduler that we'd really like pse to run next. */
8021 yield_task_fair(rq
);
8027 /**************************************************
8028 * Fair scheduling class load-balancing methods.
8032 * The purpose of load-balancing is to achieve the same basic fairness the
8033 * per-cpu scheduler provides, namely provide a proportional amount of compute
8034 * time to each task. This is expressed in the following equation:
8036 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8038 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
8039 * W_i,0 is defined as:
8041 * W_i,0 = \Sum_j w_i,j (2)
8043 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
8044 * is derived from the nice value as per sched_prio_to_weight[].
8046 * The weight average is an exponential decay average of the instantaneous
8049 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8051 * C_i is the compute capacity of cpu i, typically it is the
8052 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8053 * can also include other factors [XXX].
8055 * To achieve this balance we define a measure of imbalance which follows
8056 * directly from (1):
8058 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8060 * We them move tasks around to minimize the imbalance. In the continuous
8061 * function space it is obvious this converges, in the discrete case we get
8062 * a few fun cases generally called infeasible weight scenarios.
8065 * - infeasible weights;
8066 * - local vs global optima in the discrete case. ]
8071 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8072 * for all i,j solution, we create a tree of cpus that follows the hardware
8073 * topology where each level pairs two lower groups (or better). This results
8074 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
8075 * tree to only the first of the previous level and we decrease the frequency
8076 * of load-balance at each level inv. proportional to the number of cpus in
8082 * \Sum { --- * --- * 2^i } = O(n) (5)
8084 * `- size of each group
8085 * | | `- number of cpus doing load-balance
8087 * `- sum over all levels
8089 * Coupled with a limit on how many tasks we can migrate every balance pass,
8090 * this makes (5) the runtime complexity of the balancer.
8092 * An important property here is that each CPU is still (indirectly) connected
8093 * to every other cpu in at most O(log n) steps:
8095 * The adjacency matrix of the resulting graph is given by:
8098 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8101 * And you'll find that:
8103 * A^(log_2 n)_i,j != 0 for all i,j (7)
8105 * Showing there's indeed a path between every cpu in at most O(log n) steps.
8106 * The task movement gives a factor of O(m), giving a convergence complexity
8109 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8114 * In order to avoid CPUs going idle while there's still work to do, new idle
8115 * balancing is more aggressive and has the newly idle cpu iterate up the domain
8116 * tree itself instead of relying on other CPUs to bring it work.
8118 * This adds some complexity to both (5) and (8) but it reduces the total idle
8126 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8129 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8134 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8136 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
8138 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8141 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8142 * rewrite all of this once again.]
8145 static unsigned long __read_mostly max_load_balance_interval
= HZ
/10;
8147 enum fbq_type
{ regular
, remote
, all
};
8156 #define LBF_ALL_PINNED 0x01
8157 #define LBF_NEED_BREAK 0x02
8158 #define LBF_DST_PINNED 0x04
8159 #define LBF_SOME_PINNED 0x08
8162 struct sched_domain
*sd
;
8170 struct cpumask
*dst_grpmask
;
8172 enum cpu_idle_type idle
;
8174 unsigned int src_grp_nr_running
;
8175 /* The set of CPUs under consideration for load-balancing */
8176 struct cpumask
*cpus
;
8181 unsigned int loop_break
;
8182 unsigned int loop_max
;
8184 enum fbq_type fbq_type
;
8185 enum group_type src_grp_type
;
8186 struct list_head tasks
;
8190 * Is this task likely cache-hot:
8192 static int task_hot(struct task_struct
*p
, struct lb_env
*env
)
8196 lockdep_assert_held(&env
->src_rq
->lock
);
8198 if (p
->sched_class
!= &fair_sched_class
)
8201 if (unlikely(p
->policy
== SCHED_IDLE
))
8205 * Buddy candidates are cache hot:
8207 if (sched_feat(CACHE_HOT_BUDDY
) && env
->dst_rq
->nr_running
&&
8208 (&p
->se
== cfs_rq_of(&p
->se
)->next
||
8209 &p
->se
== cfs_rq_of(&p
->se
)->last
))
8212 if (sysctl_sched_migration_cost
== -1)
8214 if (sysctl_sched_migration_cost
== 0)
8217 delta
= rq_clock_task(env
->src_rq
) - p
->se
.exec_start
;
8219 return delta
< (s64
)sysctl_sched_migration_cost
;
8222 #ifdef CONFIG_NUMA_BALANCING
8224 * Returns 1, if task migration degrades locality
8225 * Returns 0, if task migration improves locality i.e migration preferred.
8226 * Returns -1, if task migration is not affected by locality.
8228 static int migrate_degrades_locality(struct task_struct
*p
, struct lb_env
*env
)
8230 struct numa_group
*numa_group
= rcu_dereference(p
->numa_group
);
8231 unsigned long src_faults
, dst_faults
;
8232 int src_nid
, dst_nid
;
8234 if (!static_branch_likely(&sched_numa_balancing
))
8237 if (!p
->numa_faults
|| !(env
->sd
->flags
& SD_NUMA
))
8240 src_nid
= cpu_to_node(env
->src_cpu
);
8241 dst_nid
= cpu_to_node(env
->dst_cpu
);
8243 if (src_nid
== dst_nid
)
8246 /* Migrating away from the preferred node is always bad. */
8247 if (src_nid
== p
->numa_preferred_nid
) {
8248 if (env
->src_rq
->nr_running
> env
->src_rq
->nr_preferred_running
)
8254 /* Encourage migration to the preferred node. */
8255 if (dst_nid
== p
->numa_preferred_nid
)
8258 /* Leaving a core idle is often worse than degrading locality. */
8259 if (env
->idle
!= CPU_NOT_IDLE
)
8263 src_faults
= group_faults(p
, src_nid
);
8264 dst_faults
= group_faults(p
, dst_nid
);
8266 src_faults
= task_faults(p
, src_nid
);
8267 dst_faults
= task_faults(p
, dst_nid
);
8270 return dst_faults
< src_faults
;
8274 static inline int migrate_degrades_locality(struct task_struct
*p
,
8282 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8285 int can_migrate_task(struct task_struct
*p
, struct lb_env
*env
)
8289 lockdep_assert_held(&env
->src_rq
->lock
);
8292 * We do not migrate tasks that are:
8293 * 1) throttled_lb_pair, or
8294 * 2) cannot be migrated to this CPU due to cpus_allowed, or
8295 * 3) running (obviously), or
8296 * 4) are cache-hot on their current CPU.
8298 if (throttled_lb_pair(task_group(p
), env
->src_cpu
, env
->dst_cpu
))
8301 if (!cpumask_test_cpu(env
->dst_cpu
, &p
->cpus_allowed
)) {
8304 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_affine
);
8306 env
->flags
|= LBF_SOME_PINNED
;
8309 * Remember if this task can be migrated to any other cpu in
8310 * our sched_group. We may want to revisit it if we couldn't
8311 * meet load balance goals by pulling other tasks on src_cpu.
8313 * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
8314 * already computed one in current iteration.
8316 if (env
->idle
== CPU_NEWLY_IDLE
|| (env
->flags
& LBF_DST_PINNED
))
8319 /* Prevent to re-select dst_cpu via env's cpus */
8320 for_each_cpu_and(cpu
, env
->dst_grpmask
, env
->cpus
) {
8321 if (cpumask_test_cpu(cpu
, &p
->cpus_allowed
)) {
8322 env
->flags
|= LBF_DST_PINNED
;
8323 env
->new_dst_cpu
= cpu
;
8331 /* Record that we found atleast one task that could run on dst_cpu */
8332 env
->flags
&= ~LBF_ALL_PINNED
;
8334 if (task_running(env
->src_rq
, p
)) {
8335 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_running
);
8340 * Aggressive migration if:
8341 * 1) destination numa is preferred
8342 * 2) task is cache cold, or
8343 * 3) too many balance attempts have failed.
8345 tsk_cache_hot
= migrate_degrades_locality(p
, env
);
8346 if (tsk_cache_hot
== -1)
8347 tsk_cache_hot
= task_hot(p
, env
);
8349 if (tsk_cache_hot
<= 0 ||
8350 env
->sd
->nr_balance_failed
> env
->sd
->cache_nice_tries
) {
8351 if (tsk_cache_hot
== 1) {
8352 schedstat_inc(env
->sd
->lb_hot_gained
[env
->idle
]);
8353 schedstat_inc(p
->se
.statistics
.nr_forced_migrations
);
8358 schedstat_inc(p
->se
.statistics
.nr_failed_migrations_hot
);
8363 * detach_task() -- detach the task for the migration specified in env
8365 static void detach_task(struct task_struct
*p
, struct lb_env
*env
)
8367 lockdep_assert_held(&env
->src_rq
->lock
);
8369 p
->on_rq
= TASK_ON_RQ_MIGRATING
;
8370 deactivate_task(env
->src_rq
, p
, DEQUEUE_NOCLOCK
);
8371 set_task_cpu(p
, env
->dst_cpu
);
8375 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8376 * part of active balancing operations within "domain".
8378 * Returns a task if successful and NULL otherwise.
8380 static struct task_struct
*detach_one_task(struct lb_env
*env
)
8382 struct task_struct
*p
, *n
;
8384 lockdep_assert_held(&env
->src_rq
->lock
);
8386 list_for_each_entry_safe(p
, n
, &env
->src_rq
->cfs_tasks
, se
.group_node
) {
8387 if (!can_migrate_task(p
, env
))
8390 detach_task(p
, env
);
8393 * Right now, this is only the second place where
8394 * lb_gained[env->idle] is updated (other is detach_tasks)
8395 * so we can safely collect stats here rather than
8396 * inside detach_tasks().
8398 schedstat_inc(env
->sd
->lb_gained
[env
->idle
]);
8404 static const unsigned int sched_nr_migrate_break
= 32;
8407 * detach_tasks() -- tries to detach up to imbalance weighted load from
8408 * busiest_rq, as part of a balancing operation within domain "sd".
8410 * Returns number of detached tasks if successful and 0 otherwise.
8412 static int detach_tasks(struct lb_env
*env
)
8414 struct list_head
*tasks
= &env
->src_rq
->cfs_tasks
;
8415 struct task_struct
*p
;
8419 lockdep_assert_held(&env
->src_rq
->lock
);
8421 if (env
->imbalance
<= 0)
8424 while (!list_empty(tasks
)) {
8426 * We don't want to steal all, otherwise we may be treated likewise,
8427 * which could at worst lead to a livelock crash.
8429 if (env
->idle
!= CPU_NOT_IDLE
&& env
->src_rq
->nr_running
<= 1)
8432 p
= list_first_entry(tasks
, struct task_struct
, se
.group_node
);
8435 /* We've more or less seen every task there is, call it quits */
8436 if (env
->loop
> env
->loop_max
)
8439 /* take a breather every nr_migrate tasks */
8440 if (env
->loop
> env
->loop_break
) {
8441 env
->loop_break
+= sched_nr_migrate_break
;
8442 env
->flags
|= LBF_NEED_BREAK
;
8446 if (!can_migrate_task(p
, env
))
8449 load
= task_h_load(p
);
8451 if (sched_feat(LB_MIN
) && load
< 16 && !env
->sd
->nr_balance_failed
)
8454 if ((load
/ 2) > env
->imbalance
)
8457 detach_task(p
, env
);
8458 list_add(&p
->se
.group_node
, &env
->tasks
);
8461 env
->imbalance
-= load
;
8463 #ifdef CONFIG_PREEMPT
8465 * NEWIDLE balancing is a source of latency, so preemptible
8466 * kernels will stop after the first task is detached to minimize
8467 * the critical section.
8469 if (env
->idle
== CPU_NEWLY_IDLE
)
8474 * We only want to steal up to the prescribed amount of
8477 if (env
->imbalance
<= 0)
8482 list_move_tail(&p
->se
.group_node
, tasks
);
8486 * Right now, this is one of only two places we collect this stat
8487 * so we can safely collect detach_one_task() stats here rather
8488 * than inside detach_one_task().
8490 schedstat_add(env
->sd
->lb_gained
[env
->idle
], detached
);
8496 * attach_task() -- attach the task detached by detach_task() to its new rq.
8498 static void attach_task(struct rq
*rq
, struct task_struct
*p
)
8500 lockdep_assert_held(&rq
->lock
);
8502 BUG_ON(task_rq(p
) != rq
);
8503 activate_task(rq
, p
, ENQUEUE_NOCLOCK
);
8504 p
->on_rq
= TASK_ON_RQ_QUEUED
;
8505 check_preempt_curr(rq
, p
, 0);
8509 * attach_one_task() -- attaches the task returned from detach_one_task() to
8512 static void attach_one_task(struct rq
*rq
, struct task_struct
*p
)
8517 update_rq_clock(rq
);
8523 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8526 static void attach_tasks(struct lb_env
*env
)
8528 struct list_head
*tasks
= &env
->tasks
;
8529 struct task_struct
*p
;
8532 rq_lock(env
->dst_rq
, &rf
);
8533 update_rq_clock(env
->dst_rq
);
8535 while (!list_empty(tasks
)) {
8536 p
= list_first_entry(tasks
, struct task_struct
, se
.group_node
);
8537 list_del_init(&p
->se
.group_node
);
8539 attach_task(env
->dst_rq
, p
);
8542 rq_unlock(env
->dst_rq
, &rf
);
8545 #ifdef CONFIG_FAIR_GROUP_SCHED
8547 static inline bool cfs_rq_is_decayed(struct cfs_rq
*cfs_rq
)
8549 if (cfs_rq
->load
.weight
)
8552 if (cfs_rq
->avg
.load_sum
)
8555 if (cfs_rq
->avg
.util_sum
)
8558 if (cfs_rq
->runnable_load_sum
)
8564 static void update_blocked_averages(int cpu
)
8566 struct rq
*rq
= cpu_rq(cpu
);
8567 struct cfs_rq
*cfs_rq
, *pos
;
8570 rq_lock_irqsave(rq
, &rf
);
8571 update_rq_clock(rq
);
8574 * Iterates the task_group tree in a bottom up fashion, see
8575 * list_add_leaf_cfs_rq() for details.
8577 for_each_leaf_cfs_rq_safe(rq
, cfs_rq
, pos
) {
8578 struct sched_entity
*se
;
8580 /* throttled entities do not contribute to load */
8581 if (throttled_hierarchy(cfs_rq
))
8584 if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq
), cfs_rq
))
8585 update_tg_load_avg(cfs_rq
, 0);
8587 /* Propagate pending load changes to the parent, if any: */
8588 se
= cfs_rq
->tg
->se
[cpu
];
8589 if (se
&& !skip_blocked_update(se
))
8590 update_load_avg(se
, 0);
8593 * There can be a lot of idle CPU cgroups. Don't let fully
8594 * decayed cfs_rqs linger on the list.
8596 if (cfs_rq_is_decayed(cfs_rq
))
8597 list_del_leaf_cfs_rq(cfs_rq
);
8599 update_rt_rq_load_avg(rq_clock_task(rq
), cpu
, &rq
->rt
, 0);
8600 #ifdef CONFIG_NO_HZ_COMMON
8601 rq
->last_blocked_load_update_tick
= jiffies
;
8603 rq_unlock_irqrestore(rq
, &rf
);
8607 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
8608 * This needs to be done in a top-down fashion because the load of a child
8609 * group is a fraction of its parents load.
8611 static void update_cfs_rq_h_load(struct cfs_rq
*cfs_rq
)
8613 struct rq
*rq
= rq_of(cfs_rq
);
8614 struct sched_entity
*se
= cfs_rq
->tg
->se
[cpu_of(rq
)];
8615 unsigned long now
= jiffies
;
8618 if (cfs_rq
->last_h_load_update
== now
)
8621 cfs_rq
->h_load_next
= NULL
;
8622 for_each_sched_entity(se
) {
8623 cfs_rq
= cfs_rq_of(se
);
8624 cfs_rq
->h_load_next
= se
;
8625 if (cfs_rq
->last_h_load_update
== now
)
8630 cfs_rq
->h_load
= cfs_rq_load_avg(cfs_rq
);
8631 cfs_rq
->last_h_load_update
= now
;
8634 while ((se
= cfs_rq
->h_load_next
) != NULL
) {
8635 load
= cfs_rq
->h_load
;
8636 load
= div64_ul(load
* se
->avg
.load_avg
,
8637 cfs_rq_load_avg(cfs_rq
) + 1);
8638 cfs_rq
= group_cfs_rq(se
);
8639 cfs_rq
->h_load
= load
;
8640 cfs_rq
->last_h_load_update
= now
;
8644 static unsigned long task_h_load(struct task_struct
*p
)
8646 struct cfs_rq
*cfs_rq
= task_cfs_rq(p
);
8648 update_cfs_rq_h_load(cfs_rq
);
8649 return div64_ul(p
->se
.avg
.load_avg
* cfs_rq
->h_load
,
8650 cfs_rq_load_avg(cfs_rq
) + 1);
8653 static inline void update_blocked_averages(int cpu
)
8655 struct rq
*rq
= cpu_rq(cpu
);
8656 struct cfs_rq
*cfs_rq
= &rq
->cfs
;
8659 rq_lock_irqsave(rq
, &rf
);
8660 update_rq_clock(rq
);
8661 update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq
), cfs_rq
);
8662 update_rt_rq_load_avg(rq_clock_task(rq
), cpu
, &rq
->rt
, 0);
8663 #ifdef CONFIG_NO_HZ_COMMON
8664 rq
->last_blocked_load_update_tick
= jiffies
;
8666 rq_unlock_irqrestore(rq
, &rf
);
8669 static unsigned long task_h_load(struct task_struct
*p
)
8671 return p
->se
.avg
.load_avg
;
8675 /********** Helpers for find_busiest_group ************************/
8678 * sg_lb_stats - stats of a sched_group required for load_balancing
8680 struct sg_lb_stats
{
8681 unsigned long avg_load
; /*Avg load across the CPUs of the group */
8682 unsigned long group_load
; /* Total load over the CPUs of the group */
8683 unsigned long sum_weighted_load
; /* Weighted load of group's tasks */
8684 unsigned long load_per_task
;
8685 unsigned long group_capacity
;
8686 unsigned long group_util
; /* Total utilization of the group */
8687 unsigned int sum_nr_running
; /* Nr tasks running in the group */
8688 unsigned int idle_cpus
;
8689 unsigned int group_weight
;
8690 enum group_type group_type
;
8691 int group_no_capacity
;
8692 /* A cpu has a task too big for its capacity */
8693 unsigned long group_misfit_task_load
;
8694 #ifdef CONFIG_NUMA_BALANCING
8695 unsigned int nr_numa_running
;
8696 unsigned int nr_preferred_running
;
8701 * sd_lb_stats - Structure to store the statistics of a sched_domain
8702 * during load balancing.
8704 struct sd_lb_stats
{
8705 struct sched_group
*busiest
; /* Busiest group in this sd */
8706 struct sched_group
*local
; /* Local group in this sd */
8707 unsigned long total_running
;
8708 unsigned long total_load
; /* Total load of all groups in sd */
8709 unsigned long total_capacity
; /* Total capacity of all groups in sd */
8710 unsigned long total_util
; /* Total util of all groups in sd */
8711 unsigned long avg_load
; /* Average load across all groups in sd */
8713 struct sg_lb_stats busiest_stat
;/* Statistics of the busiest group */
8714 struct sg_lb_stats local_stat
; /* Statistics of the local group */
8717 static inline void init_sd_lb_stats(struct sd_lb_stats
*sds
)
8720 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
8721 * local_stat because update_sg_lb_stats() does a full clear/assignment.
8722 * We must however clear busiest_stat::avg_load because
8723 * update_sd_pick_busiest() reads this before assignment.
8725 *sds
= (struct sd_lb_stats
){
8728 .total_running
= 0UL,
8730 .total_capacity
= 0UL,
8734 .sum_nr_running
= 0,
8735 .group_type
= group_other
,
8741 * get_sd_load_idx - Obtain the load index for a given sched domain.
8742 * @sd: The sched_domain whose load_idx is to be obtained.
8743 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
8745 * Return: The load index.
8747 static inline int get_sd_load_idx(struct sched_domain
*sd
,
8748 enum cpu_idle_type idle
)
8754 load_idx
= sd
->busy_idx
;
8757 case CPU_NEWLY_IDLE
:
8758 load_idx
= sd
->newidle_idx
;
8761 load_idx
= sd
->idle_idx
;
8768 static unsigned long scale_rt_capacity(int cpu
)
8770 struct rq
*rq
= cpu_rq(cpu
);
8771 u64 total
, used
, age_stamp
, avg
;
8775 * Since we're reading these variables without serialization make sure
8776 * we read them once before doing sanity checks on them.
8778 age_stamp
= READ_ONCE(rq
->age_stamp
);
8779 avg
= READ_ONCE(rq
->rt_avg
);
8780 delta
= __rq_clock_broken(rq
) - age_stamp
;
8782 if (unlikely(delta
< 0))
8785 total
= sched_avg_period() + delta
;
8787 used
= div_u64(avg
, total
);
8789 if (likely(used
< SCHED_CAPACITY_SCALE
))
8790 return SCHED_CAPACITY_SCALE
- used
;
8795 static void update_cpu_capacity(struct sched_domain
*sd
, int cpu
)
8797 unsigned long capacity
= arch_scale_cpu_capacity(sd
, cpu
);
8798 struct sched_group
*sdg
= sd
->groups
;
8800 cpu_rq(cpu
)->cpu_capacity_orig
= capacity
;
8802 capacity
*= scale_rt_capacity(cpu
);
8803 capacity
>>= SCHED_CAPACITY_SHIFT
;
8808 cpu_rq(cpu
)->cpu_capacity
= capacity
;
8809 sdg
->sgc
->capacity
= capacity
;
8810 sdg
->sgc
->min_capacity
= capacity
;
8811 sdg
->sgc
->max_capacity
= capacity
;
8814 void update_group_capacity(struct sched_domain
*sd
, int cpu
)
8816 struct sched_domain
*child
= sd
->child
;
8817 struct sched_group
*group
, *sdg
= sd
->groups
;
8818 unsigned long capacity
, min_capacity
, max_capacity
;
8819 unsigned long interval
;
8821 interval
= msecs_to_jiffies(sd
->balance_interval
);
8822 interval
= clamp(interval
, 1UL, max_load_balance_interval
);
8823 sdg
->sgc
->next_update
= jiffies
+ interval
;
8826 update_cpu_capacity(sd
, cpu
);
8831 min_capacity
= ULONG_MAX
;
8834 if (child
->flags
& SD_OVERLAP
) {
8836 * SD_OVERLAP domains cannot assume that child groups
8837 * span the current group.
8840 for_each_cpu(cpu
, sched_group_span(sdg
)) {
8841 struct sched_group_capacity
*sgc
;
8842 struct rq
*rq
= cpu_rq(cpu
);
8845 * build_sched_domains() -> init_sched_groups_capacity()
8846 * gets here before we've attached the domains to the
8849 * Use capacity_of(), which is set irrespective of domains
8850 * in update_cpu_capacity().
8852 * This avoids capacity from being 0 and
8853 * causing divide-by-zero issues on boot.
8855 if (unlikely(!rq
->sd
)) {
8856 capacity
+= capacity_of(cpu
);
8858 sgc
= rq
->sd
->groups
->sgc
;
8859 capacity
+= sgc
->capacity
;
8862 min_capacity
= min(capacity
, min_capacity
);
8863 max_capacity
= max(capacity
, max_capacity
);
8867 * !SD_OVERLAP domains can assume that child groups
8868 * span the current group.
8871 group
= child
->groups
;
8873 struct sched_group_capacity
*sgc
= group
->sgc
;
8875 capacity
+= sgc
->capacity
;
8876 min_capacity
= min(sgc
->min_capacity
, min_capacity
);
8877 max_capacity
= max(sgc
->max_capacity
, max_capacity
);
8878 group
= group
->next
;
8879 } while (group
!= child
->groups
);
8882 sdg
->sgc
->capacity
= capacity
;
8883 sdg
->sgc
->min_capacity
= min_capacity
;
8884 sdg
->sgc
->max_capacity
= max_capacity
;
8888 * Check whether the capacity of the rq has been noticeably reduced by side
8889 * activity. The imbalance_pct is used for the threshold.
8890 * Return true is the capacity is reduced
8893 check_cpu_capacity(struct rq
*rq
, struct sched_domain
*sd
)
8895 return ((rq
->cpu_capacity
* sd
->imbalance_pct
) <
8896 (rq
->cpu_capacity_orig
* 100));
8900 * Group imbalance indicates (and tries to solve) the problem where balancing
8901 * groups is inadequate due to ->cpus_allowed constraints.
8903 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
8904 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
8907 * { 0 1 2 3 } { 4 5 6 7 }
8910 * If we were to balance group-wise we'd place two tasks in the first group and
8911 * two tasks in the second group. Clearly this is undesired as it will overload
8912 * cpu 3 and leave one of the cpus in the second group unused.
8914 * The current solution to this issue is detecting the skew in the first group
8915 * by noticing the lower domain failed to reach balance and had difficulty
8916 * moving tasks due to affinity constraints.
8918 * When this is so detected; this group becomes a candidate for busiest; see
8919 * update_sd_pick_busiest(). And calculate_imbalance() and
8920 * find_busiest_group() avoid some of the usual balance conditions to allow it
8921 * to create an effective group imbalance.
8923 * This is a somewhat tricky proposition since the next run might not find the
8924 * group imbalance and decide the groups need to be balanced again. A most
8925 * subtle and fragile situation.
8928 static inline int sg_imbalanced(struct sched_group
*group
)
8930 return group
->sgc
->imbalance
;
8934 * group_has_capacity returns true if the group has spare capacity that could
8935 * be used by some tasks.
8936 * We consider that a group has spare capacity if the * number of task is
8937 * smaller than the number of CPUs or if the utilization is lower than the
8938 * available capacity for CFS tasks.
8939 * For the latter, we use a threshold to stabilize the state, to take into
8940 * account the variance of the tasks' load and to return true if the available
8941 * capacity in meaningful for the load balancer.
8942 * As an example, an available capacity of 1% can appear but it doesn't make
8943 * any benefit for the load balance.
8946 group_has_capacity(struct lb_env
*env
, struct sg_lb_stats
*sgs
)
8948 if (sgs
->sum_nr_running
< sgs
->group_weight
)
8951 if ((sgs
->group_capacity
* 100) >
8952 (sgs
->group_util
* env
->sd
->imbalance_pct
))
8959 * group_is_overloaded returns true if the group has more tasks than it can
8961 * group_is_overloaded is not equals to !group_has_capacity because a group
8962 * with the exact right number of tasks, has no more spare capacity but is not
8963 * overloaded so both group_has_capacity and group_is_overloaded return
8967 group_is_overloaded(struct lb_env
*env
, struct sg_lb_stats
*sgs
)
8969 if (sgs
->sum_nr_running
<= sgs
->group_weight
)
8972 if ((sgs
->group_capacity
* 100) <
8973 (sgs
->group_util
* env
->sd
->imbalance_pct
))
8980 * group_smaller_min_cpu_capacity: Returns true if sched_group sg has smaller
8981 * per-CPU capacity than sched_group ref.
8984 group_smaller_min_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
8986 return sg
->sgc
->min_capacity
* capacity_margin
<
8987 ref
->sgc
->min_capacity
* 1024;
8991 * group_smaller_max_cpu_capacity: Returns true if sched_group sg has smaller
8992 * per-CPU capacity_orig than sched_group ref.
8995 group_smaller_max_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
8997 return sg
->sgc
->max_capacity
* capacity_margin
<
8998 ref
->sgc
->max_capacity
* 1024;
9002 * group_similar_cpu_capacity: Returns true if the minimum capacity of the
9003 * compared groups differ by less than 12.5%.
9006 group_similar_cpu_capacity(struct sched_group
*sg
, struct sched_group
*ref
)
9008 long diff
= sg
->sgc
->min_capacity
- ref
->sgc
->min_capacity
;
9009 long max
= max(sg
->sgc
->min_capacity
, ref
->sgc
->min_capacity
);
9011 return abs(diff
) < max
>> 3;
9015 group_type
group_classify(struct sched_group
*group
,
9016 struct sg_lb_stats
*sgs
)
9018 if (sgs
->group_no_capacity
)
9019 return group_overloaded
;
9021 if (sg_imbalanced(group
))
9022 return group_imbalanced
;
9024 if (sgs
->group_misfit_task_load
)
9025 return group_misfit_task
;
9031 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9032 * @env: The load balancing environment.
9033 * @group: sched_group whose statistics are to be updated.
9034 * @load_idx: Load index of sched_domain of this_cpu for load calc.
9035 * @local_group: Does group contain this_cpu.
9036 * @sgs: variable to hold the statistics for this group.
9037 * @overload: Indicate pullable load (e.g. >1 runnable task).
9038 * @overutilized: Indicate overutilization for any CPU.
9040 static inline void update_sg_lb_stats(struct lb_env
*env
,
9041 struct sched_group
*group
, int load_idx
,
9042 int local_group
, struct sg_lb_stats
*sgs
,
9043 bool *overload
, bool *overutilized
, bool *misfit_task
)
9048 memset(sgs
, 0, sizeof(*sgs
));
9050 for_each_cpu_and(i
, sched_group_span(group
), env
->cpus
) {
9051 struct rq
*rq
= cpu_rq(i
);
9053 /* Bias balancing toward cpus of our domain */
9055 load
= target_load(i
, load_idx
);
9057 load
= source_load(i
, load_idx
);
9059 sgs
->group_load
+= load
;
9060 sgs
->group_util
+= cpu_util(i
);
9061 sgs
->sum_nr_running
+= rq
->cfs
.h_nr_running
;
9063 nr_running
= rq
->nr_running
;
9067 #ifdef CONFIG_NUMA_BALANCING
9068 sgs
->nr_numa_running
+= rq
->nr_numa_running
;
9069 sgs
->nr_preferred_running
+= rq
->nr_preferred_running
;
9071 sgs
->sum_weighted_load
+= weighted_cpuload(rq
);
9073 * No need to call idle_cpu() if nr_running is not 0
9075 if (!nr_running
&& idle_cpu(i
))
9078 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
9079 sgs
->group_misfit_task_load
< rq
->misfit_task_load
) {
9080 sgs
->group_misfit_task_load
= rq
->misfit_task_load
;
9085 if (cpu_overutilized(i
)) {
9086 *overutilized
= true;
9088 if (rq
->misfit_task_load
)
9089 *misfit_task
= true;
9093 /* Adjust by relative CPU capacity of the group */
9094 sgs
->group_capacity
= group
->sgc
->capacity
;
9095 sgs
->avg_load
= (sgs
->group_load
*SCHED_CAPACITY_SCALE
) / sgs
->group_capacity
;
9097 if (sgs
->sum_nr_running
)
9098 sgs
->load_per_task
= sgs
->sum_weighted_load
/ sgs
->sum_nr_running
;
9100 sgs
->group_weight
= group
->group_weight
;
9102 sgs
->group_no_capacity
= group_is_overloaded(env
, sgs
);
9103 sgs
->group_type
= group_classify(group
, sgs
);
9107 * update_sd_pick_busiest - return 1 on busiest group
9108 * @env: The load balancing environment.
9109 * @sds: sched_domain statistics
9110 * @sg: sched_group candidate to be checked for being the busiest
9111 * @sgs: sched_group statistics
9113 * Determine if @sg is a busier group than the previously selected
9116 * Return: %true if @sg is a busier group than the previously selected
9117 * busiest group. %false otherwise.
9119 static bool update_sd_pick_busiest(struct lb_env
*env
,
9120 struct sd_lb_stats
*sds
,
9121 struct sched_group
*sg
,
9122 struct sg_lb_stats
*sgs
)
9124 struct sg_lb_stats
*busiest
= &sds
->busiest_stat
;
9127 * Don't try to pull misfit tasks we can't help.
9128 * We can use max_capacity here as reduction in capacity on some
9129 * cpus in the group should either be possible to resolve
9130 * internally or be covered by avg_load imbalance (eventually).
9132 if (sgs
->group_type
== group_misfit_task
&&
9133 (!group_smaller_max_cpu_capacity(sg
, sds
->local
) ||
9134 !group_has_capacity(env
, &sds
->local_stat
)))
9137 if (sgs
->group_type
> busiest
->group_type
)
9140 if (sgs
->group_type
< busiest
->group_type
)
9143 if (sgs
->avg_load
<= busiest
->avg_load
)
9146 if (!(env
->sd
->flags
& SD_ASYM_CPUCAPACITY
))
9150 * Candidate sg has no more than one task per CPU and
9151 * has higher per-CPU capacity. Migrating tasks to less
9152 * capable CPUs may harm throughput. Maximize throughput,
9153 * power/energy consequences are not considered.
9155 if (sgs
->sum_nr_running
<= sgs
->group_weight
&&
9156 group_smaller_min_cpu_capacity(sds
->local
, sg
))
9160 * Candidate sg doesn't face any severe imbalance issues so
9161 * don't disturb unless the groups are of similar capacity
9162 * where balancing is more harmless.
9164 if (sgs
->group_type
== group_other
&&
9165 !group_similar_cpu_capacity(sds
->local
, sg
))
9169 * If we have more than one misfit sg go with the biggest misfit.
9171 if (sgs
->group_type
== group_misfit_task
&&
9172 sgs
->group_misfit_task_load
< busiest
->group_misfit_task_load
)
9176 /* This is the busiest node in its class. */
9177 if (!(env
->sd
->flags
& SD_ASYM_PACKING
))
9180 /* No ASYM_PACKING if target cpu is already busy */
9181 if (env
->idle
== CPU_NOT_IDLE
)
9184 * ASYM_PACKING needs to move all the work to the highest
9185 * prority CPUs in the group, therefore mark all groups
9186 * of lower priority than ourself as busy.
9188 if (sgs
->sum_nr_running
&&
9189 sched_asym_prefer(env
->dst_cpu
, sg
->asym_prefer_cpu
)) {
9193 /* Prefer to move from lowest priority cpu's work */
9194 if (sched_asym_prefer(sds
->busiest
->asym_prefer_cpu
,
9195 sg
->asym_prefer_cpu
))
9202 #ifdef CONFIG_NUMA_BALANCING
9203 static inline enum fbq_type
fbq_classify_group(struct sg_lb_stats
*sgs
)
9205 if (sgs
->sum_nr_running
> sgs
->nr_numa_running
)
9207 if (sgs
->sum_nr_running
> sgs
->nr_preferred_running
)
9212 static inline enum fbq_type
fbq_classify_rq(struct rq
*rq
)
9214 if (rq
->nr_running
> rq
->nr_numa_running
)
9216 if (rq
->nr_running
> rq
->nr_preferred_running
)
9221 static inline enum fbq_type
fbq_classify_group(struct sg_lb_stats
*sgs
)
9226 static inline enum fbq_type
fbq_classify_rq(struct rq
*rq
)
9230 #endif /* CONFIG_NUMA_BALANCING */
9232 #ifdef CONFIG_NO_HZ_COMMON
9234 cpumask_var_t idle_cpus_mask
;
9236 unsigned long next_balance
; /* in jiffy units */
9237 unsigned long next_update
; /* in jiffy units */
9238 } nohz ____cacheline_aligned
;
9241 #define lb_sd_parent(sd) \
9242 (sd->parent && sd->parent->groups != sd->parent->groups->next)
9245 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
9246 * @env: The load balancing environment.
9247 * @sds: variable to hold the statistics for this sched_domain.
9249 static inline void update_sd_lb_stats(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9251 struct sched_domain
*child
= env
->sd
->child
;
9252 struct sched_group
*sg
= env
->sd
->groups
;
9253 struct sg_lb_stats
*local
= &sds
->local_stat
;
9254 struct sg_lb_stats tmp_sgs
;
9256 bool overload
= false, overutilized
= false, misfit_task
= false;
9257 bool prefer_sibling
= child
&& child
->flags
& SD_PREFER_SIBLING
;
9259 #ifdef CONFIG_NO_HZ_COMMON
9260 if (env
->idle
== CPU_NEWLY_IDLE
) {
9263 /* Update the stats of NOHZ idle CPUs in the sd */
9264 for_each_cpu_and(cpu
, sched_domain_span(env
->sd
),
9265 nohz
.idle_cpus_mask
) {
9266 struct rq
*rq
= cpu_rq(cpu
);
9268 /* ... Unless we've already done since the last tick */
9269 if (time_after(jiffies
,
9270 rq
->last_blocked_load_update_tick
))
9271 update_blocked_averages(cpu
);
9275 * If we've just updated all of the NOHZ idle CPUs, then we can push
9276 * back the next nohz.next_update, which will prevent an unnecessary
9277 * wakeup for the nohz stats kick
9279 if (cpumask_subset(nohz
.idle_cpus_mask
, sched_domain_span(env
->sd
)))
9280 nohz
.next_update
= jiffies
+ LOAD_AVG_PERIOD
;
9283 load_idx
= get_sd_load_idx(env
->sd
, env
->idle
);
9286 struct sg_lb_stats
*sgs
= &tmp_sgs
;
9289 local_group
= cpumask_test_cpu(env
->dst_cpu
, sched_group_span(sg
));
9294 if (env
->idle
!= CPU_NEWLY_IDLE
||
9295 time_after_eq(jiffies
, sg
->sgc
->next_update
))
9296 update_group_capacity(env
->sd
, env
->dst_cpu
);
9299 update_sg_lb_stats(env
, sg
, load_idx
, local_group
, sgs
,
9300 &overload
, &overutilized
,
9307 * In case the child domain prefers tasks go to siblings
9308 * first, lower the sg capacity so that we'll try
9309 * and move all the excess tasks away. We lower the capacity
9310 * of a group only if the local group has the capacity to fit
9311 * these excess tasks. The extra check prevents the case where
9312 * you always pull from the heaviest group when it is already
9313 * under-utilized (possible with a large weight task outweighs
9314 * the tasks on the system).
9316 if (prefer_sibling
&& sds
->local
&&
9317 group_has_capacity(env
, local
) &&
9318 (sgs
->sum_nr_running
> local
->sum_nr_running
+ 1)) {
9319 sgs
->group_no_capacity
= 1;
9320 sgs
->group_type
= group_classify(sg
, sgs
);
9323 if (update_sd_pick_busiest(env
, sds
, sg
, sgs
)) {
9325 sds
->busiest_stat
= *sgs
;
9329 /* Now, start updating sd_lb_stats */
9330 sds
->total_running
+= sgs
->sum_nr_running
;
9331 sds
->total_load
+= sgs
->group_load
;
9332 sds
->total_capacity
+= sgs
->group_capacity
;
9333 sds
->total_util
+= sgs
->group_util
;
9336 } while (sg
!= env
->sd
->groups
);
9338 if (env
->sd
->flags
& SD_NUMA
)
9339 env
->fbq_type
= fbq_classify_group(&sds
->busiest_stat
);
9341 env
->src_grp_nr_running
= sds
->busiest_stat
.sum_nr_running
;
9343 if (!lb_sd_parent(env
->sd
)) {
9344 /* update overload indicator if we are at root domain */
9345 if (READ_ONCE(env
->dst_rq
->rd
->overload
) != overload
)
9346 WRITE_ONCE(env
->dst_rq
->rd
->overload
, overload
);
9350 set_sd_overutilized(env
->sd
);
9352 clear_sd_overutilized(env
->sd
);
9355 * If there is a misfit task in one cpu in this sched_domain
9356 * it is likely that the imbalance cannot be sorted out among
9357 * the cpu's in this sched_domain. In this case set the
9358 * overutilized flag at the parent sched_domain.
9361 struct sched_domain
*sd
= env
->sd
->parent
;
9364 * In case of a misfit task, load balance at the parent
9365 * sched domain level will make sense only if the the cpus
9366 * have a different capacity. If cpus at a domain level have
9367 * the same capacity, the misfit task cannot be well
9368 * accomodated in any of the cpus and there in no point in
9369 * trying a load balance at this level
9372 if (sd
->flags
& SD_ASYM_CPUCAPACITY
) {
9373 set_sd_overutilized(sd
);
9381 * If the domain util is greater that domain capacity, load balancing
9382 * needs to be done at the next sched domain level as well.
9384 if (lb_sd_parent(env
->sd
) &&
9385 sds
->total_capacity
* 1024 < sds
->total_util
* capacity_margin
)
9386 set_sd_overutilized(env
->sd
->parent
);
9390 * check_asym_packing - Check to see if the group is packed into the
9393 * This is primarily intended to used at the sibling level. Some
9394 * cores like POWER7 prefer to use lower numbered SMT threads. In the
9395 * case of POWER7, it can move to lower SMT modes only when higher
9396 * threads are idle. When in lower SMT modes, the threads will
9397 * perform better since they share less core resources. Hence when we
9398 * have idle threads, we want them to be the higher ones.
9400 * This packing function is run on idle threads. It checks to see if
9401 * the busiest CPU in this domain (core in the P7 case) has a higher
9402 * CPU number than the packing function is being run on. Here we are
9403 * assuming lower CPU number will be equivalent to lower a SMT thread
9406 * Return: 1 when packing is required and a task should be moved to
9407 * this CPU. The amount of the imbalance is returned in env->imbalance.
9409 * @env: The load balancing environment.
9410 * @sds: Statistics of the sched_domain which is to be packed
9412 static int check_asym_packing(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9416 if (!(env
->sd
->flags
& SD_ASYM_PACKING
))
9419 if (env
->idle
== CPU_NOT_IDLE
)
9425 busiest_cpu
= sds
->busiest
->asym_prefer_cpu
;
9426 if (sched_asym_prefer(busiest_cpu
, env
->dst_cpu
))
9429 env
->imbalance
= DIV_ROUND_CLOSEST(
9430 sds
->busiest_stat
.avg_load
* sds
->busiest_stat
.group_capacity
,
9431 SCHED_CAPACITY_SCALE
);
9437 * fix_small_imbalance - Calculate the minor imbalance that exists
9438 * amongst the groups of a sched_domain, during
9440 * @env: The load balancing environment.
9441 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
9444 void fix_small_imbalance(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9446 unsigned long tmp
, capa_now
= 0, capa_move
= 0;
9447 unsigned int imbn
= 2;
9448 unsigned long scaled_busy_load_per_task
;
9449 struct sg_lb_stats
*local
, *busiest
;
9451 local
= &sds
->local_stat
;
9452 busiest
= &sds
->busiest_stat
;
9454 if (!local
->sum_nr_running
)
9455 local
->load_per_task
= cpu_avg_load_per_task(env
->dst_cpu
);
9456 else if (busiest
->load_per_task
> local
->load_per_task
)
9459 scaled_busy_load_per_task
=
9460 (busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) /
9461 busiest
->group_capacity
;
9463 if (busiest
->avg_load
+ scaled_busy_load_per_task
>=
9464 local
->avg_load
+ (scaled_busy_load_per_task
* imbn
)) {
9465 env
->imbalance
= busiest
->load_per_task
;
9470 * OK, we don't have enough imbalance to justify moving tasks,
9471 * however we may be able to increase total CPU capacity used by
9475 capa_now
+= busiest
->group_capacity
*
9476 min(busiest
->load_per_task
, busiest
->avg_load
);
9477 capa_now
+= local
->group_capacity
*
9478 min(local
->load_per_task
, local
->avg_load
);
9479 capa_now
/= SCHED_CAPACITY_SCALE
;
9481 /* Amount of load we'd subtract */
9482 if (busiest
->avg_load
> scaled_busy_load_per_task
) {
9483 capa_move
+= busiest
->group_capacity
*
9484 min(busiest
->load_per_task
,
9485 busiest
->avg_load
- scaled_busy_load_per_task
);
9488 /* Amount of load we'd add */
9489 if (busiest
->avg_load
* busiest
->group_capacity
<
9490 busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) {
9491 tmp
= (busiest
->avg_load
* busiest
->group_capacity
) /
9492 local
->group_capacity
;
9494 tmp
= (busiest
->load_per_task
* SCHED_CAPACITY_SCALE
) /
9495 local
->group_capacity
;
9497 capa_move
+= local
->group_capacity
*
9498 min(local
->load_per_task
, local
->avg_load
+ tmp
);
9499 capa_move
/= SCHED_CAPACITY_SCALE
;
9501 /* Move if we gain throughput */
9502 if (capa_move
> capa_now
) {
9503 env
->imbalance
= busiest
->load_per_task
;
9507 /* We can't see throughput improvement with the load-based
9508 * method, but it is possible depending upon group size and
9509 * capacity range that there might still be an underutilized
9510 * cpu available in an asymmetric capacity system. Do one last
9511 * check just in case.
9513 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
9514 busiest
->group_type
== group_overloaded
&&
9515 busiest
->sum_nr_running
> busiest
->group_weight
&&
9516 local
->sum_nr_running
< local
->group_weight
&&
9517 local
->group_capacity
< busiest
->group_capacity
)
9518 env
->imbalance
= busiest
->load_per_task
;
9522 * calculate_imbalance - Calculate the amount of imbalance present within the
9523 * groups of a given sched_domain during load balance.
9524 * @env: load balance environment
9525 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
9527 static inline void calculate_imbalance(struct lb_env
*env
, struct sd_lb_stats
*sds
)
9529 unsigned long max_pull
, load_above_capacity
= ~0UL;
9530 struct sg_lb_stats
*local
, *busiest
;
9532 local
= &sds
->local_stat
;
9533 busiest
= &sds
->busiest_stat
;
9535 if (busiest
->group_type
== group_imbalanced
) {
9537 * In the group_imb case we cannot rely on group-wide averages
9538 * to ensure cpu-load equilibrium, look at wider averages. XXX
9540 busiest
->load_per_task
=
9541 min(busiest
->load_per_task
, sds
->avg_load
);
9545 * Avg load of busiest sg can be less and avg load of local sg can
9546 * be greater than avg load across all sgs of sd because avg load
9547 * factors in sg capacity and sgs with smaller group_type are
9548 * skipped when updating the busiest sg:
9550 if (busiest
->group_type
!= group_misfit_task
&&
9551 (busiest
->avg_load
<= sds
->avg_load
||
9552 local
->avg_load
>= sds
->avg_load
)) {
9554 return fix_small_imbalance(env
, sds
);
9558 * If there aren't any idle cpus, avoid creating some.
9560 if (busiest
->group_type
== group_overloaded
&&
9561 local
->group_type
== group_overloaded
) {
9562 load_above_capacity
= busiest
->sum_nr_running
* SCHED_CAPACITY_SCALE
;
9563 if (load_above_capacity
> busiest
->group_capacity
) {
9564 load_above_capacity
-= busiest
->group_capacity
;
9565 load_above_capacity
*= scale_load_down(NICE_0_LOAD
);
9566 load_above_capacity
/= busiest
->group_capacity
;
9568 load_above_capacity
= ~0UL;
9572 * We're trying to get all the cpus to the average_load, so we don't
9573 * want to push ourselves above the average load, nor do we wish to
9574 * reduce the max loaded cpu below the average load. At the same time,
9575 * we also don't want to reduce the group load below the group
9576 * capacity. Thus we look for the minimum possible imbalance.
9578 max_pull
= min(busiest
->avg_load
- sds
->avg_load
, load_above_capacity
);
9580 /* How much load to actually move to equalise the imbalance */
9581 env
->imbalance
= min(
9582 max_pull
* busiest
->group_capacity
,
9583 (sds
->avg_load
- local
->avg_load
) * local
->group_capacity
9584 ) / SCHED_CAPACITY_SCALE
;
9586 /* Boost imbalance to allow misfit task to be balanced.
9587 * Always do this if we are doing a NEWLY_IDLE balance
9588 * on the assumption that any tasks we have must not be
9589 * long-running (and hence we cannot rely upon load).
9590 * However if we are not idle, we should assume the tasks
9591 * we have are longer running and not override load-based
9592 * calculations above unless we are sure that the local
9593 * group is underutilized.
9595 if (busiest
->group_type
== group_misfit_task
&&
9596 (env
->idle
== CPU_NEWLY_IDLE
||
9597 local
->sum_nr_running
< local
->group_weight
)) {
9598 env
->imbalance
= max_t(long, env
->imbalance
,
9599 busiest
->group_misfit_task_load
);
9603 * if *imbalance is less than the average load per runnable task
9604 * there is no guarantee that any tasks will be moved so we'll have
9605 * a think about bumping its value to force at least one task to be
9608 if (env
->imbalance
< busiest
->load_per_task
)
9609 return fix_small_imbalance(env
, sds
);
9612 /******* find_busiest_group() helpers end here *********************/
9615 * find_busiest_group - Returns the busiest group within the sched_domain
9616 * if there is an imbalance.
9618 * Also calculates the amount of weighted load which should be moved
9619 * to restore balance.
9621 * @env: The load balancing environment.
9623 * Return: - The busiest group if imbalance exists.
9625 static struct sched_group
*find_busiest_group(struct lb_env
*env
)
9627 struct sg_lb_stats
*local
, *busiest
;
9628 struct sd_lb_stats sds
;
9630 init_sd_lb_stats(&sds
);
9633 * Compute the various statistics relavent for load balancing at
9636 update_sd_lb_stats(env
, &sds
);
9638 if (energy_aware() && !sd_overutilized(env
->sd
))
9641 local
= &sds
.local_stat
;
9642 busiest
= &sds
.busiest_stat
;
9644 /* ASYM feature bypasses nice load balance check */
9645 if (check_asym_packing(env
, &sds
))
9648 /* There is no busy sibling group to pull tasks from */
9649 if (!sds
.busiest
|| busiest
->sum_nr_running
== 0)
9652 /* XXX broken for overlapping NUMA groups */
9653 sds
.avg_load
= (SCHED_CAPACITY_SCALE
* sds
.total_load
)
9654 / sds
.total_capacity
;
9657 * If the busiest group is imbalanced the below checks don't
9658 * work because they assume all things are equal, which typically
9659 * isn't true due to cpus_allowed constraints and the like.
9661 if (busiest
->group_type
== group_imbalanced
)
9665 * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
9666 * capacities from resulting in underutilization due to avg_load.
9668 if (env
->idle
!= CPU_NOT_IDLE
&& group_has_capacity(env
, local
) &&
9669 busiest
->group_no_capacity
)
9672 /* Misfit tasks should be dealt with regardless of the avg load */
9673 if (busiest
->group_type
== group_misfit_task
)
9677 * If the local group is busier than the selected busiest group
9678 * don't try and pull any tasks.
9680 if (local
->avg_load
>= busiest
->avg_load
)
9684 * Don't pull any tasks if this group is already above the domain
9687 if (local
->avg_load
>= sds
.avg_load
)
9690 if (env
->idle
== CPU_IDLE
) {
9692 * This cpu is idle. If the busiest group is not overloaded
9693 * and there is no imbalance between this and busiest group
9694 * wrt idle cpus, it is balanced. The imbalance becomes
9695 * significant if the diff is greater than 1 otherwise we
9696 * might end up to just move the imbalance on another group
9698 if ((busiest
->group_type
!= group_overloaded
) &&
9699 (local
->idle_cpus
<= (busiest
->idle_cpus
+ 1)))
9703 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
9704 * imbalance_pct to be conservative.
9706 if (100 * busiest
->avg_load
<=
9707 env
->sd
->imbalance_pct
* local
->avg_load
)
9712 /* Looks like there is an imbalance. Compute it */
9713 env
->src_grp_type
= busiest
->group_type
;
9714 calculate_imbalance(env
, &sds
);
9723 * find_busiest_queue - find the busiest runqueue among the cpus in group.
9725 static struct rq
*find_busiest_queue(struct lb_env
*env
,
9726 struct sched_group
*group
)
9728 struct rq
*busiest
= NULL
, *rq
;
9729 unsigned long busiest_load
= 0, busiest_capacity
= 1;
9732 for_each_cpu_and(i
, sched_group_span(group
), env
->cpus
) {
9733 unsigned long capacity
, wl
;
9737 rt
= fbq_classify_rq(rq
);
9740 * We classify groups/runqueues into three groups:
9741 * - regular: there are !numa tasks
9742 * - remote: there are numa tasks that run on the 'wrong' node
9743 * - all: there is no distinction
9745 * In order to avoid migrating ideally placed numa tasks,
9746 * ignore those when there's better options.
9748 * If we ignore the actual busiest queue to migrate another
9749 * task, the next balance pass can still reduce the busiest
9750 * queue by moving tasks around inside the node.
9752 * If we cannot move enough load due to this classification
9753 * the next pass will adjust the group classification and
9754 * allow migration of more tasks.
9756 * Both cases only affect the total convergence complexity.
9758 if (rt
> env
->fbq_type
)
9762 * For ASYM_CPUCAPACITY domains with misfit tasks we simply
9763 * seek the "biggest" misfit task.
9765 if (env
->src_grp_type
== group_misfit_task
) {
9766 if (rq
->misfit_task_load
> busiest_load
) {
9767 busiest_load
= rq
->misfit_task_load
;
9773 capacity
= capacity_of(i
);
9776 * For ASYM_CPUCAPACITY domains, don't pick a cpu that could
9777 * eventually lead to active_balancing high->low capacity.
9778 * Higher per-cpu capacity is considered better than balancing
9781 if (env
->sd
->flags
& SD_ASYM_CPUCAPACITY
&&
9782 capacity_of(env
->dst_cpu
) < capacity
&&
9783 rq
->nr_running
== 1)
9786 wl
= weighted_cpuload(rq
);
9789 * When comparing with imbalance, use weighted_cpuload()
9790 * which is not scaled with the cpu capacity.
9793 if (rq
->nr_running
== 1 && wl
> env
->imbalance
&&
9794 !check_cpu_capacity(rq
, env
->sd
))
9798 * For the load comparisons with the other cpu's, consider
9799 * the weighted_cpuload() scaled with the cpu capacity, so
9800 * that the load can be moved away from the cpu that is
9801 * potentially running at a lower capacity.
9803 * Thus we're looking for max(wl_i / capacity_i), crosswise
9804 * multiplication to rid ourselves of the division works out
9805 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
9806 * our previous maximum.
9808 if (wl
* busiest_capacity
> busiest_load
* capacity
) {
9810 busiest_capacity
= capacity
;
9819 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
9820 * so long as it is large enough.
9822 #define MAX_PINNED_INTERVAL 512
9824 static int need_active_balance(struct lb_env
*env
)
9826 struct sched_domain
*sd
= env
->sd
;
9828 if (env
->idle
== CPU_NEWLY_IDLE
) {
9831 * ASYM_PACKING needs to force migrate tasks from busy but
9832 * lower priority CPUs in order to pack all tasks in the
9833 * highest priority CPUs.
9835 if ((sd
->flags
& SD_ASYM_PACKING
) &&
9836 sched_asym_prefer(env
->dst_cpu
, env
->src_cpu
))
9841 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
9842 * It's worth migrating the task if the src_cpu's capacity is reduced
9843 * because of other sched_class or IRQs if more capacity stays
9844 * available on dst_cpu.
9846 if ((env
->idle
!= CPU_NOT_IDLE
) &&
9847 (env
->src_rq
->cfs
.h_nr_running
== 1)) {
9848 if ((check_cpu_capacity(env
->src_rq
, sd
)) &&
9849 (capacity_of(env
->src_cpu
)*sd
->imbalance_pct
< capacity_of(env
->dst_cpu
)*100))
9853 if ((capacity_of(env
->src_cpu
) < capacity_of(env
->dst_cpu
)) &&
9854 ((capacity_orig_of(env
->src_cpu
) < capacity_orig_of(env
->dst_cpu
))) &&
9855 env
->src_rq
->cfs
.h_nr_running
== 1 &&
9856 cpu_overutilized(env
->src_cpu
) &&
9857 !cpu_overutilized(env
->dst_cpu
)) {
9861 if (env
->src_grp_type
== group_misfit_task
)
9864 if (env
->src_grp_type
== group_overloaded
&&
9865 env
->src_rq
->misfit_task_load
)
9868 return unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2);
9871 static int active_load_balance_cpu_stop(void *data
);
9873 static int should_we_balance(struct lb_env
*env
)
9875 struct sched_group
*sg
= env
->sd
->groups
;
9876 int cpu
, balance_cpu
= -1;
9879 * Ensure the balancing environment is consistent; can happen
9880 * when the softirq triggers 'during' hotplug.
9882 if (!cpumask_test_cpu(env
->dst_cpu
, env
->cpus
))
9886 * In the newly idle case, we will allow all the cpu's
9887 * to do the newly idle load balance.
9889 if (env
->idle
== CPU_NEWLY_IDLE
)
9892 /* Try to find first idle cpu */
9893 for_each_cpu_and(cpu
, group_balance_mask(sg
), env
->cpus
) {
9901 if (balance_cpu
== -1)
9902 balance_cpu
= group_balance_cpu(sg
);
9905 * First idle cpu or the first cpu(busiest) in this sched group
9906 * is eligible for doing load balancing at this and above domains.
9908 return balance_cpu
== env
->dst_cpu
;
9912 * Check this_cpu to ensure it is balanced within domain. Attempt to move
9913 * tasks if there is an imbalance.
9915 static int load_balance(int this_cpu
, struct rq
*this_rq
,
9916 struct sched_domain
*sd
, enum cpu_idle_type idle
,
9917 int *continue_balancing
)
9919 int ld_moved
, cur_ld_moved
, active_balance
= 0;
9920 struct sched_domain
*sd_parent
= lb_sd_parent(sd
) ? sd
->parent
: NULL
;
9921 struct sched_group
*group
;
9924 struct cpumask
*cpus
= this_cpu_cpumask_var_ptr(load_balance_mask
);
9926 struct lb_env env
= {
9928 .dst_cpu
= this_cpu
,
9930 .dst_grpmask
= sched_group_span(sd
->groups
),
9932 .loop_break
= sched_nr_migrate_break
,
9935 .tasks
= LIST_HEAD_INIT(env
.tasks
),
9938 cpumask_and(cpus
, sched_domain_span(sd
), cpu_active_mask
);
9940 schedstat_inc(sd
->lb_count
[idle
]);
9943 if (!should_we_balance(&env
)) {
9944 *continue_balancing
= 0;
9948 group
= find_busiest_group(&env
);
9950 schedstat_inc(sd
->lb_nobusyg
[idle
]);
9954 busiest
= find_busiest_queue(&env
, group
);
9956 schedstat_inc(sd
->lb_nobusyq
[idle
]);
9960 BUG_ON(busiest
== env
.dst_rq
);
9962 schedstat_add(sd
->lb_imbalance
[idle
], env
.imbalance
);
9964 env
.src_cpu
= busiest
->cpu
;
9965 env
.src_rq
= busiest
;
9968 if (busiest
->nr_running
> 1) {
9970 * Attempt to move tasks. If find_busiest_group has found
9971 * an imbalance but busiest->nr_running <= 1, the group is
9972 * still unbalanced. ld_moved simply stays zero, so it is
9973 * correctly treated as an imbalance.
9975 env
.flags
|= LBF_ALL_PINNED
;
9976 env
.loop_max
= min(sysctl_sched_nr_migrate
, busiest
->nr_running
);
9979 rq_lock_irqsave(busiest
, &rf
);
9980 update_rq_clock(busiest
);
9983 * cur_ld_moved - load moved in current iteration
9984 * ld_moved - cumulative load moved across iterations
9986 cur_ld_moved
= detach_tasks(&env
);
9989 * We've detached some tasks from busiest_rq. Every
9990 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
9991 * unlock busiest->lock, and we are able to be sure
9992 * that nobody can manipulate the tasks in parallel.
9993 * See task_rq_lock() family for the details.
9996 rq_unlock(busiest
, &rf
);
10000 ld_moved
+= cur_ld_moved
;
10003 local_irq_restore(rf
.flags
);
10005 if (env
.flags
& LBF_NEED_BREAK
) {
10006 env
.flags
&= ~LBF_NEED_BREAK
;
10011 * Revisit (affine) tasks on src_cpu that couldn't be moved to
10012 * us and move them to an alternate dst_cpu in our sched_group
10013 * where they can run. The upper limit on how many times we
10014 * iterate on same src_cpu is dependent on number of cpus in our
10017 * This changes load balance semantics a bit on who can move
10018 * load to a given_cpu. In addition to the given_cpu itself
10019 * (or a ilb_cpu acting on its behalf where given_cpu is
10020 * nohz-idle), we now have balance_cpu in a position to move
10021 * load to given_cpu. In rare situations, this may cause
10022 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
10023 * _independently_ and at _same_ time to move some load to
10024 * given_cpu) causing exceess load to be moved to given_cpu.
10025 * This however should not happen so much in practice and
10026 * moreover subsequent load balance cycles should correct the
10027 * excess load moved.
10029 if ((env
.flags
& LBF_DST_PINNED
) && env
.imbalance
> 0) {
10031 /* Prevent to re-select dst_cpu via env's cpus */
10032 cpumask_clear_cpu(env
.dst_cpu
, env
.cpus
);
10034 env
.dst_rq
= cpu_rq(env
.new_dst_cpu
);
10035 env
.dst_cpu
= env
.new_dst_cpu
;
10036 env
.flags
&= ~LBF_DST_PINNED
;
10038 env
.loop_break
= sched_nr_migrate_break
;
10041 * Go back to "more_balance" rather than "redo" since we
10042 * need to continue with same src_cpu.
10048 * We failed to reach balance because of affinity.
10051 int *group_imbalance
= &sd_parent
->groups
->sgc
->imbalance
;
10053 if ((env
.flags
& LBF_SOME_PINNED
) && env
.imbalance
> 0)
10054 *group_imbalance
= 1;
10057 /* All tasks on this runqueue were pinned by CPU affinity */
10058 if (unlikely(env
.flags
& LBF_ALL_PINNED
)) {
10059 cpumask_clear_cpu(cpu_of(busiest
), cpus
);
10061 * Attempting to continue load balancing at the current
10062 * sched_domain level only makes sense if there are
10063 * active CPUs remaining as possible busiest CPUs to
10064 * pull load from which are not contained within the
10065 * destination group that is receiving any migrated
10068 if (!cpumask_subset(cpus
, env
.dst_grpmask
)) {
10070 env
.loop_break
= sched_nr_migrate_break
;
10073 goto out_all_pinned
;
10078 schedstat_inc(sd
->lb_failed
[idle
]);
10080 * Increment the failure counter only on periodic balance.
10081 * We do not want newidle balance, which can be very
10082 * frequent, pollute the failure counter causing
10083 * excessive cache_hot migrations and active balances.
10085 if (idle
!= CPU_NEWLY_IDLE
)
10086 if (env
.src_grp_nr_running
> 1)
10087 sd
->nr_balance_failed
++;
10089 if (need_active_balance(&env
)) {
10090 unsigned long flags
;
10092 raw_spin_lock_irqsave(&busiest
->lock
, flags
);
10094 /* don't kick the active_load_balance_cpu_stop,
10095 * if the curr task on busiest cpu can't be
10096 * moved to this_cpu
10098 if (!cpumask_test_cpu(this_cpu
, &busiest
->curr
->cpus_allowed
)) {
10099 raw_spin_unlock_irqrestore(&busiest
->lock
,
10101 env
.flags
|= LBF_ALL_PINNED
;
10102 goto out_one_pinned
;
10106 * ->active_balance synchronizes accesses to
10107 * ->active_balance_work. Once set, it's cleared
10108 * only after active load balance is finished.
10110 if (!busiest
->active_balance
) {
10111 busiest
->active_balance
= 1;
10112 busiest
->push_cpu
= this_cpu
;
10113 active_balance
= 1;
10115 raw_spin_unlock_irqrestore(&busiest
->lock
, flags
);
10117 if (active_balance
) {
10118 stop_one_cpu_nowait(cpu_of(busiest
),
10119 active_load_balance_cpu_stop
, busiest
,
10120 &busiest
->active_balance_work
);
10123 /* We've kicked active balancing, force task migration. */
10124 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
10127 sd
->nr_balance_failed
= 0;
10129 if (likely(!active_balance
)) {
10130 /* We were unbalanced, so reset the balancing interval */
10131 sd
->balance_interval
= sd
->min_interval
;
10134 * If we've begun active balancing, start to back off. This
10135 * case may not be covered by the all_pinned logic if there
10136 * is only 1 task on the busy runqueue (because we don't call
10139 if (sd
->balance_interval
< sd
->max_interval
)
10140 sd
->balance_interval
*= 2;
10147 * We reach balance although we may have faced some affinity
10148 * constraints. Clear the imbalance flag if it was set.
10151 int *group_imbalance
= &sd_parent
->groups
->sgc
->imbalance
;
10153 if (*group_imbalance
)
10154 *group_imbalance
= 0;
10159 * We reach balance because all tasks are pinned at this level so
10160 * we can't migrate them. Let the imbalance flag set so parent level
10161 * can try to migrate them.
10163 schedstat_inc(sd
->lb_balanced
[idle
]);
10165 sd
->nr_balance_failed
= 0;
10168 /* tune up the balancing interval */
10169 if (((env
.flags
& LBF_ALL_PINNED
) &&
10170 sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
10171 (sd
->balance_interval
< sd
->max_interval
))
10172 sd
->balance_interval
*= 2;
10179 static inline unsigned long
10180 get_sd_balance_interval(struct sched_domain
*sd
, int cpu_busy
)
10182 unsigned long interval
= sd
->balance_interval
;
10186 interval
*= sd
->busy_factor
;
10188 /* scale ms to jiffies */
10189 interval
= msecs_to_jiffies(interval
);
10190 interval
= clamp(interval
, 1UL, max_load_balance_interval
);
10193 * check if sched domain is marked as overutilized
10194 * we ought to only do this on systems which have SD_ASYMCAPACITY
10195 * but we want to do it for all sched domains in those systems
10196 * So for now, just check if overutilized as a proxy.
10199 * If we are overutilized and we have a misfit task, then
10200 * we want to balance as soon as practically possible, so
10201 * we return an interval of zero.
10203 if (energy_aware() && sd_overutilized(sd
)) {
10204 /* we know the root is overutilized, let's check for a misfit task */
10205 for_each_cpu(cpu
, sched_domain_span(sd
)) {
10206 if (cpu_rq(cpu
)->misfit_task_load
)
10214 update_next_balance(struct sched_domain
*sd
, unsigned long *next_balance
)
10216 unsigned long interval
, next
;
10218 /* used by idle balance, so cpu_busy = 0 */
10219 interval
= get_sd_balance_interval(sd
, 0);
10220 next
= sd
->last_balance
+ interval
;
10222 if (time_after(*next_balance
, next
))
10223 *next_balance
= next
;
10227 * idle_balance is called by schedule() if this_cpu is about to become
10228 * idle. Attempts to pull tasks from other CPUs.
10230 static int idle_balance(struct rq
*this_rq
, struct rq_flags
*rf
)
10232 unsigned long next_balance
= jiffies
+ HZ
;
10233 int this_cpu
= this_rq
->cpu
;
10234 struct sched_domain
*sd
;
10235 int pulled_task
= 0;
10239 * We must set idle_stamp _before_ calling idle_balance(), such that we
10240 * measure the duration of idle_balance() as idle time.
10242 this_rq
->idle_stamp
= rq_clock(this_rq
);
10245 * Do not pull tasks towards !active CPUs...
10247 if (!cpu_active(this_cpu
))
10251 * This is OK, because current is on_cpu, which avoids it being picked
10252 * for load-balance and preemption/IRQs are still disabled avoiding
10253 * further scheduler activity on it and we're being very careful to
10254 * re-start the picking loop.
10256 rq_unpin_lock(this_rq
, rf
);
10258 if (this_rq
->avg_idle
< sysctl_sched_migration_cost
||
10259 !READ_ONCE(this_rq
->rd
->overload
)) {
10261 sd
= rcu_dereference_check_sched_domain(this_rq
->sd
);
10263 update_next_balance(sd
, &next_balance
);
10269 raw_spin_unlock(&this_rq
->lock
);
10271 update_blocked_averages(this_cpu
);
10273 for_each_domain(this_cpu
, sd
) {
10274 int continue_balancing
= 1;
10275 u64 t0
, domain_cost
;
10277 if (!(sd
->flags
& SD_LOAD_BALANCE
))
10280 if (this_rq
->avg_idle
< curr_cost
+ sd
->max_newidle_lb_cost
) {
10281 update_next_balance(sd
, &next_balance
);
10285 if (sd
->flags
& SD_BALANCE_NEWIDLE
) {
10286 t0
= sched_clock_cpu(this_cpu
);
10288 pulled_task
= load_balance(this_cpu
, this_rq
,
10289 sd
, CPU_NEWLY_IDLE
,
10290 &continue_balancing
);
10292 domain_cost
= sched_clock_cpu(this_cpu
) - t0
;
10293 if (domain_cost
> sd
->max_newidle_lb_cost
)
10294 sd
->max_newidle_lb_cost
= domain_cost
;
10296 curr_cost
+= domain_cost
;
10299 update_next_balance(sd
, &next_balance
);
10302 * Stop searching for tasks to pull if there are
10303 * now runnable tasks on this rq.
10305 if (pulled_task
|| this_rq
->nr_running
> 0)
10310 raw_spin_lock(&this_rq
->lock
);
10312 if (curr_cost
> this_rq
->max_idle_balance_cost
)
10313 this_rq
->max_idle_balance_cost
= curr_cost
;
10316 * While browsing the domains, we released the rq lock, a task could
10317 * have been enqueued in the meantime. Since we're not going idle,
10318 * pretend we pulled a task.
10320 if (this_rq
->cfs
.h_nr_running
&& !pulled_task
)
10324 /* Move the next balance forward */
10325 if (time_after(this_rq
->next_balance
, next_balance
))
10326 this_rq
->next_balance
= next_balance
;
10328 /* Is there a task of a high priority class? */
10329 if (this_rq
->nr_running
!= this_rq
->cfs
.h_nr_running
)
10333 this_rq
->idle_stamp
= 0;
10335 rq_repin_lock(this_rq
, rf
);
10337 return pulled_task
;
10341 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
10342 * running tasks off the busiest CPU onto idle CPUs. It requires at
10343 * least 1 task to be running on each physical CPU where possible, and
10344 * avoids physical / logical imbalances.
10346 static int active_load_balance_cpu_stop(void *data
)
10348 struct rq
*busiest_rq
= data
;
10349 int busiest_cpu
= cpu_of(busiest_rq
);
10350 int target_cpu
= busiest_rq
->push_cpu
;
10351 struct rq
*target_rq
= cpu_rq(target_cpu
);
10352 struct sched_domain
*sd
;
10353 struct task_struct
*p
= NULL
;
10354 struct rq_flags rf
;
10356 rq_lock_irq(busiest_rq
, &rf
);
10358 * Between queueing the stop-work and running it is a hole in which
10359 * CPUs can become inactive. We should not move tasks from or to
10362 if (!cpu_active(busiest_cpu
) || !cpu_active(target_cpu
))
10365 /* make sure the requested cpu hasn't gone down in the meantime */
10366 if (unlikely(busiest_cpu
!= smp_processor_id() ||
10367 !busiest_rq
->active_balance
))
10370 /* Is there any task to move? */
10371 if (busiest_rq
->nr_running
<= 1)
10375 * This condition is "impossible", if it occurs
10376 * we need to fix it. Originally reported by
10377 * Bjorn Helgaas on a 128-cpu setup.
10379 BUG_ON(busiest_rq
== target_rq
);
10381 /* Search for an sd spanning us and the target CPU. */
10383 for_each_domain(target_cpu
, sd
) {
10384 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
10385 cpumask_test_cpu(busiest_cpu
, sched_domain_span(sd
)))
10390 struct lb_env env
= {
10392 .dst_cpu
= target_cpu
,
10393 .dst_rq
= target_rq
,
10394 .src_cpu
= busiest_rq
->cpu
,
10395 .src_rq
= busiest_rq
,
10398 * can_migrate_task() doesn't need to compute new_dst_cpu
10399 * for active balancing. Since we have CPU_IDLE, but no
10400 * @dst_grpmask we need to make that test go away with lying
10401 * about DST_PINNED.
10403 .flags
= LBF_DST_PINNED
,
10406 schedstat_inc(sd
->alb_count
);
10407 update_rq_clock(busiest_rq
);
10409 p
= detach_one_task(&env
);
10411 schedstat_inc(sd
->alb_pushed
);
10412 /* Active balancing done, reset the failure counter. */
10413 sd
->nr_balance_failed
= 0;
10415 schedstat_inc(sd
->alb_failed
);
10420 busiest_rq
->active_balance
= 0;
10421 rq_unlock(busiest_rq
, &rf
);
10424 attach_one_task(target_rq
, p
);
10426 local_irq_enable();
10431 static inline int on_null_domain(struct rq
*rq
)
10433 return unlikely(!rcu_dereference_sched(rq
->sd
));
10436 #ifdef CONFIG_NO_HZ_COMMON
10438 * idle load balancing details
10439 * - When one of the busy CPUs notice that there may be an idle rebalancing
10440 * needed, they will kick the idle load balancer, which then does idle
10441 * load balancing for all the idle CPUs.
10444 static inline int find_new_ilb(void)
10446 int ilb
= cpumask_first(nohz
.idle_cpus_mask
);
10448 if (ilb
< nr_cpu_ids
&& idle_cpu(ilb
))
10455 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
10456 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
10457 * CPU (if there is one).
10459 static void nohz_balancer_kick(bool only_update
)
10463 nohz
.next_balance
++;
10465 ilb_cpu
= find_new_ilb();
10467 if (ilb_cpu
>= nr_cpu_ids
)
10470 if (test_and_set_bit(NOHZ_BALANCE_KICK
, nohz_flags(ilb_cpu
)))
10474 set_bit(NOHZ_STATS_KICK
, nohz_flags(ilb_cpu
));
10477 * Use smp_send_reschedule() instead of resched_cpu().
10478 * This way we generate a sched IPI on the target cpu which
10479 * is idle. And the softirq performing nohz idle load balance
10480 * will be run before returning from the IPI.
10482 smp_send_reschedule(ilb_cpu
);
10486 void nohz_balance_exit_idle(unsigned int cpu
)
10488 if (unlikely(test_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
)))) {
10490 * Completely isolated CPUs don't ever set, so we must test.
10492 if (likely(cpumask_test_cpu(cpu
, nohz
.idle_cpus_mask
))) {
10493 cpumask_clear_cpu(cpu
, nohz
.idle_cpus_mask
);
10494 atomic_dec(&nohz
.nr_cpus
);
10496 clear_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
));
10500 static inline void set_cpu_sd_state_busy(void)
10502 struct sched_domain
*sd
;
10503 int cpu
= smp_processor_id();
10506 sd
= rcu_dereference(per_cpu(sd_llc
, cpu
));
10508 if (!sd
|| !sd
->nohz_idle
)
10512 atomic_inc(&sd
->shared
->nr_busy_cpus
);
10517 void set_cpu_sd_state_idle(void)
10519 struct sched_domain
*sd
;
10520 int cpu
= smp_processor_id();
10523 sd
= rcu_dereference(per_cpu(sd_llc
, cpu
));
10525 if (!sd
|| sd
->nohz_idle
)
10529 atomic_dec(&sd
->shared
->nr_busy_cpus
);
10535 * This routine will record that the cpu is going idle with tick stopped.
10536 * This info will be used in performing idle load balancing in the future.
10538 void nohz_balance_enter_idle(int cpu
)
10541 * If this cpu is going down, then nothing needs to be done.
10543 if (!cpu_active(cpu
))
10546 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
10547 if (!is_housekeeping_cpu(cpu
))
10550 if (test_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
)))
10554 * If we're a completely isolated CPU, we don't play.
10556 if (on_null_domain(cpu_rq(cpu
)))
10559 cpumask_set_cpu(cpu
, nohz
.idle_cpus_mask
);
10560 atomic_inc(&nohz
.nr_cpus
);
10561 set_bit(NOHZ_TICK_STOPPED
, nohz_flags(cpu
));
10564 static inline void nohz_balancer_kick(bool only_update
) {}
10567 static DEFINE_SPINLOCK(balancing
);
10570 * Scale the max load_balance interval with the number of CPUs in the system.
10571 * This trades load-balance latency on larger machines for less cross talk.
10573 void update_max_interval(void)
10575 max_load_balance_interval
= HZ
*num_online_cpus()/10;
10579 * It checks each scheduling domain to see if it is due to be balanced,
10580 * and initiates a balancing operation if so.
10582 * Balancing parameters are set up in init_sched_domains.
10584 static void rebalance_domains(struct rq
*rq
, enum cpu_idle_type idle
)
10586 int continue_balancing
= 1;
10588 unsigned long interval
;
10589 struct sched_domain
*sd
;
10590 /* Earliest time when we have to do rebalance again */
10591 unsigned long next_balance
= jiffies
+ 60*HZ
;
10592 int update_next_balance
= 0;
10593 int need_serialize
, need_decay
= 0;
10597 for_each_domain(cpu
, sd
) {
10599 * Decay the newidle max times here because this is a regular
10600 * visit to all the domains. Decay ~1% per second.
10602 if (time_after(jiffies
, sd
->next_decay_max_lb_cost
)) {
10603 sd
->max_newidle_lb_cost
=
10604 (sd
->max_newidle_lb_cost
* 253) / 256;
10605 sd
->next_decay_max_lb_cost
= jiffies
+ HZ
;
10608 max_cost
+= sd
->max_newidle_lb_cost
;
10610 if (energy_aware() && !sd_overutilized(sd
))
10613 if (!(sd
->flags
& SD_LOAD_BALANCE
))
10617 * Stop the load balance at this level. There is another
10618 * CPU in our sched group which is doing load balancing more
10621 if (!continue_balancing
) {
10627 interval
= get_sd_balance_interval(sd
, idle
!= CPU_IDLE
);
10629 need_serialize
= sd
->flags
& SD_SERIALIZE
;
10630 if (need_serialize
) {
10631 if (!spin_trylock(&balancing
))
10635 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
10636 if (load_balance(cpu
, rq
, sd
, idle
, &continue_balancing
)) {
10638 * The LBF_DST_PINNED logic could have changed
10639 * env->dst_cpu, so we can't know our idle
10640 * state even if we migrated tasks. Update it.
10642 idle
= idle_cpu(cpu
) ? CPU_IDLE
: CPU_NOT_IDLE
;
10644 sd
->last_balance
= jiffies
;
10645 interval
= get_sd_balance_interval(sd
, idle
!= CPU_IDLE
);
10647 if (need_serialize
)
10648 spin_unlock(&balancing
);
10650 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
10651 next_balance
= sd
->last_balance
+ interval
;
10652 update_next_balance
= 1;
10657 * Ensure the rq-wide value also decays but keep it at a
10658 * reasonable floor to avoid funnies with rq->avg_idle.
10660 rq
->max_idle_balance_cost
=
10661 max((u64
)sysctl_sched_migration_cost
, max_cost
);
10666 * next_balance will be updated only when there is a need.
10667 * When the cpu is attached to null domain for ex, it will not be
10670 if (likely(update_next_balance
)) {
10671 rq
->next_balance
= next_balance
;
10673 #ifdef CONFIG_NO_HZ_COMMON
10675 * If this CPU has been elected to perform the nohz idle
10676 * balance. Other idle CPUs have already rebalanced with
10677 * nohz_idle_balance() and nohz.next_balance has been
10678 * updated accordingly. This CPU is now running the idle load
10679 * balance for itself and we need to update the
10680 * nohz.next_balance accordingly.
10682 if ((idle
== CPU_IDLE
) && time_after(nohz
.next_balance
, rq
->next_balance
))
10683 nohz
.next_balance
= rq
->next_balance
;
10688 #ifdef CONFIG_NO_HZ_COMMON
10690 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
10691 * rebalancing for all the cpus for whom scheduler ticks are stopped.
10693 static void nohz_idle_balance(struct rq
*this_rq
, enum cpu_idle_type idle
)
10695 int this_cpu
= this_rq
->cpu
;
10697 struct sched_domain
*sd
;
10699 /* Earliest time when we have to do rebalance again */
10700 unsigned long next_balance
= jiffies
+ 60*HZ
;
10701 int update_next_balance
= 0;
10703 if (idle
!= CPU_IDLE
||
10704 !test_bit(NOHZ_BALANCE_KICK
, nohz_flags(this_cpu
)))
10708 * This cpu is going to update the blocked load of idle CPUs either
10709 * before doing a rebalancing or just to keep metrics up to date. we
10710 * can safely update the next update timestamp
10713 sd
= rcu_dereference(this_rq
->sd
);
10715 * Check whether there is a sched_domain available for this cpu.
10716 * The last other cpu can have been unplugged since the ILB has been
10717 * triggered and the sched_domain can now be null. The idle balance
10718 * sequence will quickly be aborted as there is no more idle CPUs
10721 nohz
.next_update
= jiffies
+ msecs_to_jiffies(LOAD_AVG_PERIOD
);
10724 for_each_cpu(balance_cpu
, nohz
.idle_cpus_mask
) {
10725 if (balance_cpu
== this_cpu
|| !idle_cpu(balance_cpu
))
10729 * If this cpu gets work to do, stop the load balancing
10730 * work being done for other cpus. Next load
10731 * balancing owner will pick it up.
10733 if (need_resched())
10736 rq
= cpu_rq(balance_cpu
);
10739 * If time for next balance is due,
10742 if (time_after_eq(jiffies
, rq
->next_balance
)) {
10743 struct rq_flags rf
;
10745 rq_lock_irq(rq
, &rf
);
10746 update_rq_clock(rq
);
10747 cpu_load_update_idle(rq
);
10748 rq_unlock_irq(rq
, &rf
);
10750 update_blocked_averages(balance_cpu
);
10752 * This idle load balance softirq may have been
10753 * triggered only to update the blocked load and shares
10754 * of idle CPUs (which we have just done for
10755 * balance_cpu). In that case skip the actual balance.
10757 if (!test_bit(NOHZ_STATS_KICK
, nohz_flags(this_cpu
)))
10758 rebalance_domains(rq
, idle
);
10761 if (time_after(next_balance
, rq
->next_balance
)) {
10762 next_balance
= rq
->next_balance
;
10763 update_next_balance
= 1;
10768 * next_balance will be updated only when there is a need.
10769 * When the CPU is attached to null domain for ex, it will not be
10772 if (likely(update_next_balance
))
10773 nohz
.next_balance
= next_balance
;
10775 clear_bit(NOHZ_BALANCE_KICK
, nohz_flags(this_cpu
));
10779 * Current heuristic for kicking the idle load balancer in the presence
10780 * of an idle cpu in the system.
10781 * - This rq has more than one task.
10782 * - This rq has at least one CFS task and the capacity of the CPU is
10783 * significantly reduced because of RT tasks or IRQs.
10784 * - At parent of LLC scheduler domain level, this cpu's scheduler group has
10785 * multiple busy cpu.
10786 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
10787 * domain span are idle.
10789 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
)
10791 unsigned long now
= jiffies
;
10792 struct sched_domain_shared
*sds
;
10793 struct sched_domain
*sd
;
10794 int nr_busy
, i
, cpu
= rq
->cpu
;
10797 if (unlikely(rq
->idle_balance
) && !only_update
)
10801 * We may be recently in ticked or tickless idle mode. At the first
10802 * busy tick after returning from idle, we will update the busy stats.
10804 set_cpu_sd_state_busy();
10805 nohz_balance_exit_idle(cpu
);
10808 * None are in tickless mode and hence no need for NOHZ idle load
10811 if (likely(!atomic_read(&nohz
.nr_cpus
)))
10815 if (time_before(now
, nohz
.next_update
))
10821 if (time_before(now
, nohz
.next_balance
))
10824 if (rq
->nr_running
>= 2 &&
10825 (!energy_aware() || cpu_overutilized(cpu
)))
10828 /* Do idle load balance if there have misfit task */
10829 if (energy_aware())
10830 return rq
->misfit_task_load
;
10833 sds
= rcu_dereference(per_cpu(sd_llc_shared
, cpu
));
10834 if (sds
&& !energy_aware()) {
10836 * XXX: write a coherent comment on why we do this.
10837 * See also: http://lkml.kernel.org/r/20111202010832.602203411@sbsiddha-desk.sc.intel.com
10839 nr_busy
= atomic_read(&sds
->nr_busy_cpus
);
10847 sd
= rcu_dereference(rq
->sd
);
10849 if ((rq
->cfs
.h_nr_running
>= 1) &&
10850 check_cpu_capacity(rq
, sd
)) {
10856 sd
= rcu_dereference(per_cpu(sd_asym
, cpu
));
10858 for_each_cpu(i
, sched_domain_span(sd
)) {
10860 !cpumask_test_cpu(i
, nohz
.idle_cpus_mask
))
10863 if (sched_asym_prefer(i
, cpu
)) {
10874 static void nohz_idle_balance(struct rq
*this_rq
, enum cpu_idle_type idle
) { }
10875 static inline bool nohz_kick_needed(struct rq
*rq
, bool only_update
) { return false; }
10879 * run_rebalance_domains is triggered when needed from the scheduler tick.
10880 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
10882 static __latent_entropy
void run_rebalance_domains(struct softirq_action
*h
)
10884 struct rq
*this_rq
= this_rq();
10885 enum cpu_idle_type idle
= this_rq
->idle_balance
?
10886 CPU_IDLE
: CPU_NOT_IDLE
;
10889 * If this cpu has a pending nohz_balance_kick, then do the
10890 * balancing on behalf of the other idle cpus whose ticks are
10891 * stopped. Do nohz_idle_balance *before* rebalance_domains to
10892 * give the idle cpus a chance to load balance. Else we may
10893 * load balance only within the local sched_domain hierarchy
10894 * and abort nohz_idle_balance altogether if we pull some load.
10896 nohz_idle_balance(this_rq
, idle
);
10897 update_blocked_averages(this_rq
->cpu
);
10898 #ifdef CONFIG_NO_HZ_COMMON
10899 if (!test_bit(NOHZ_STATS_KICK
, nohz_flags(this_rq
->cpu
)))
10900 rebalance_domains(this_rq
, idle
);
10901 clear_bit(NOHZ_STATS_KICK
, nohz_flags(this_rq
->cpu
));
10903 rebalance_domains(this_rq
, idle
);
10908 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
10910 void trigger_load_balance(struct rq
*rq
)
10912 /* Don't need to rebalance while attached to NULL domain */
10913 if (unlikely(on_null_domain(rq
)))
10916 if (time_after_eq(jiffies
, rq
->next_balance
))
10917 raise_softirq(SCHED_SOFTIRQ
);
10918 #ifdef CONFIG_NO_HZ_COMMON
10919 if (nohz_kick_needed(rq
, false))
10920 nohz_balancer_kick(false);
10924 static void rq_online_fair(struct rq
*rq
)
10928 update_runtime_enabled(rq
);
10931 static void rq_offline_fair(struct rq
*rq
)
10935 /* Ensure any throttled groups are reachable by pick_next_task */
10936 unthrottle_offline_cfs_rqs(rq
);
10939 #endif /* CONFIG_SMP */
10942 * scheduler tick hitting a task of our scheduling class:
10944 static void task_tick_fair(struct rq
*rq
, struct task_struct
*curr
, int queued
)
10946 struct cfs_rq
*cfs_rq
;
10947 struct sched_entity
*se
= &curr
->se
;
10949 for_each_sched_entity(se
) {
10950 cfs_rq
= cfs_rq_of(se
);
10951 entity_tick(cfs_rq
, se
, queued
);
10954 if (static_branch_unlikely(&sched_numa_balancing
))
10955 task_tick_numa(rq
, curr
);
10957 update_misfit_status(curr
, rq
);
10959 update_overutilized_status(rq
);
10963 * called on fork with the child task as argument from the parent's context
10964 * - child not yet on the tasklist
10965 * - preemption disabled
10967 static void task_fork_fair(struct task_struct
*p
)
10969 struct cfs_rq
*cfs_rq
;
10970 struct sched_entity
*se
= &p
->se
, *curr
;
10971 struct rq
*rq
= this_rq();
10972 struct rq_flags rf
;
10975 update_rq_clock(rq
);
10977 cfs_rq
= task_cfs_rq(current
);
10978 curr
= cfs_rq
->curr
;
10980 update_curr(cfs_rq
);
10981 se
->vruntime
= curr
->vruntime
;
10983 place_entity(cfs_rq
, se
, 1);
10985 if (sysctl_sched_child_runs_first
&& curr
&& entity_before(curr
, se
)) {
10987 * Upon rescheduling, sched_class::put_prev_task() will place
10988 * 'current' within the tree based on its new key value.
10990 swap(curr
->vruntime
, se
->vruntime
);
10994 se
->vruntime
-= cfs_rq
->min_vruntime
;
10995 rq_unlock(rq
, &rf
);
10999 * Priority of the task has changed. Check to see if we preempt
11000 * the current task.
11003 prio_changed_fair(struct rq
*rq
, struct task_struct
*p
, int oldprio
)
11005 if (!task_on_rq_queued(p
))
11009 * Reschedule if we are currently running on this runqueue and
11010 * our priority decreased, or if we are not currently running on
11011 * this runqueue and our priority is higher than the current's
11013 if (rq
->curr
== p
) {
11014 if (p
->prio
> oldprio
)
11017 check_preempt_curr(rq
, p
, 0);
11020 static inline bool vruntime_normalized(struct task_struct
*p
)
11022 struct sched_entity
*se
= &p
->se
;
11025 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
11026 * the dequeue_entity(.flags=0) will already have normalized the
11033 * When !on_rq, vruntime of the task has usually NOT been normalized.
11034 * But there are some cases where it has already been normalized:
11036 * - A forked child which is waiting for being woken up by
11037 * wake_up_new_task().
11038 * - A task which has been woken up by try_to_wake_up() and
11039 * waiting for actually being woken up by sched_ttwu_pending().
11041 if (!se
->sum_exec_runtime
|| p
->state
== TASK_WAKING
)
11047 #ifdef CONFIG_FAIR_GROUP_SCHED
11049 * Propagate the changes of the sched_entity across the tg tree to make it
11050 * visible to the root
11052 static void propagate_entity_cfs_rq(struct sched_entity
*se
)
11054 struct cfs_rq
*cfs_rq
;
11056 /* Start to propagate at parent */
11059 for_each_sched_entity(se
) {
11060 cfs_rq
= cfs_rq_of(se
);
11062 if (cfs_rq_throttled(cfs_rq
))
11065 update_load_avg(se
, UPDATE_TG
);
11069 static void propagate_entity_cfs_rq(struct sched_entity
*se
) { }
11072 static void detach_entity_cfs_rq(struct sched_entity
*se
)
11074 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11076 /* Catch up with the cfs_rq and remove our load when we leave */
11077 update_load_avg(se
, 0);
11078 detach_entity_load_avg(cfs_rq
, se
);
11079 update_tg_load_avg(cfs_rq
, false);
11080 propagate_entity_cfs_rq(se
);
11083 static void attach_entity_cfs_rq(struct sched_entity
*se
)
11085 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11087 #ifdef CONFIG_FAIR_GROUP_SCHED
11089 * Since the real-depth could have been changed (only FAIR
11090 * class maintain depth value), reset depth properly.
11092 se
->depth
= se
->parent
? se
->parent
->depth
+ 1 : 0;
11095 /* Synchronize entity with its cfs_rq */
11096 update_load_avg(se
, sched_feat(ATTACH_AGE_LOAD
) ? 0 : SKIP_AGE_LOAD
);
11097 attach_entity_load_avg(cfs_rq
, se
);
11098 update_tg_load_avg(cfs_rq
, false);
11099 propagate_entity_cfs_rq(se
);
11102 static void detach_task_cfs_rq(struct task_struct
*p
)
11104 struct sched_entity
*se
= &p
->se
;
11105 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11107 if (!vruntime_normalized(p
)) {
11109 * Fix up our vruntime so that the current sleep doesn't
11110 * cause 'unlimited' sleep bonus.
11112 place_entity(cfs_rq
, se
, 0);
11113 se
->vruntime
-= cfs_rq
->min_vruntime
;
11116 detach_entity_cfs_rq(se
);
11119 static void attach_task_cfs_rq(struct task_struct
*p
)
11121 struct sched_entity
*se
= &p
->se
;
11122 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11124 attach_entity_cfs_rq(se
);
11126 if (!vruntime_normalized(p
))
11127 se
->vruntime
+= cfs_rq
->min_vruntime
;
11130 static void switched_from_fair(struct rq
*rq
, struct task_struct
*p
)
11132 detach_task_cfs_rq(p
);
11135 static void switched_to_fair(struct rq
*rq
, struct task_struct
*p
)
11137 attach_task_cfs_rq(p
);
11139 if (task_on_rq_queued(p
)) {
11141 * We were most likely switched from sched_rt, so
11142 * kick off the schedule if running, otherwise just see
11143 * if we can still preempt the current task.
11148 check_preempt_curr(rq
, p
, 0);
11152 /* Account for a task changing its policy or group.
11154 * This routine is mostly called to set cfs_rq->curr field when a task
11155 * migrates between groups/classes.
11157 static void set_curr_task_fair(struct rq
*rq
)
11159 struct sched_entity
*se
= &rq
->curr
->se
;
11161 for_each_sched_entity(se
) {
11162 struct cfs_rq
*cfs_rq
= cfs_rq_of(se
);
11164 set_next_entity(cfs_rq
, se
);
11165 /* ensure bandwidth has been allocated on our new cfs_rq */
11166 account_cfs_rq_runtime(cfs_rq
, 0);
11170 void init_cfs_rq(struct cfs_rq
*cfs_rq
)
11172 cfs_rq
->tasks_timeline
= RB_ROOT_CACHED
;
11173 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
11174 #ifndef CONFIG_64BIT
11175 cfs_rq
->min_vruntime_copy
= cfs_rq
->min_vruntime
;
11178 #ifdef CONFIG_FAIR_GROUP_SCHED
11179 cfs_rq
->propagate_avg
= 0;
11181 atomic_long_set(&cfs_rq
->removed_load_avg
, 0);
11182 atomic_long_set(&cfs_rq
->removed_util_avg
, 0);
11186 #ifdef CONFIG_FAIR_GROUP_SCHED
11187 static void task_set_group_fair(struct task_struct
*p
)
11189 struct sched_entity
*se
= &p
->se
;
11191 set_task_rq(p
, task_cpu(p
));
11192 se
->depth
= se
->parent
? se
->parent
->depth
+ 1 : 0;
11195 static void task_move_group_fair(struct task_struct
*p
)
11197 detach_task_cfs_rq(p
);
11198 set_task_rq(p
, task_cpu(p
));
11201 /* Tell se's cfs_rq has been changed -- migrated */
11202 p
->se
.avg
.last_update_time
= 0;
11204 attach_task_cfs_rq(p
);
11207 static void task_change_group_fair(struct task_struct
*p
, int type
)
11210 case TASK_SET_GROUP
:
11211 task_set_group_fair(p
);
11214 case TASK_MOVE_GROUP
:
11215 task_move_group_fair(p
);
11220 void free_fair_sched_group(struct task_group
*tg
)
11224 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg
));
11226 for_each_possible_cpu(i
) {
11228 kfree(tg
->cfs_rq
[i
]);
11237 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
11239 struct sched_entity
*se
;
11240 struct cfs_rq
*cfs_rq
;
11243 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * nr_cpu_ids
, GFP_KERNEL
);
11246 tg
->se
= kzalloc(sizeof(se
) * nr_cpu_ids
, GFP_KERNEL
);
11250 tg
->shares
= NICE_0_LOAD
;
11252 init_cfs_bandwidth(tg_cfs_bandwidth(tg
));
11254 for_each_possible_cpu(i
) {
11255 cfs_rq
= kzalloc_node(sizeof(struct cfs_rq
),
11256 GFP_KERNEL
, cpu_to_node(i
));
11260 se
= kzalloc_node(sizeof(struct sched_entity
),
11261 GFP_KERNEL
, cpu_to_node(i
));
11265 init_cfs_rq(cfs_rq
);
11266 init_tg_cfs_entry(tg
, cfs_rq
, se
, i
, parent
->se
[i
]);
11267 init_entity_runnable_average(se
);
11278 void online_fair_sched_group(struct task_group
*tg
)
11280 struct sched_entity
*se
;
11284 for_each_possible_cpu(i
) {
11288 raw_spin_lock_irq(&rq
->lock
);
11289 update_rq_clock(rq
);
11290 attach_entity_cfs_rq(se
);
11291 sync_throttle(tg
, i
);
11292 raw_spin_unlock_irq(&rq
->lock
);
11296 void unregister_fair_sched_group(struct task_group
*tg
)
11298 unsigned long flags
;
11302 for_each_possible_cpu(cpu
) {
11304 remove_entity_load_avg(tg
->se
[cpu
]);
11307 * Only empty task groups can be destroyed; so we can speculatively
11308 * check on_list without danger of it being re-added.
11310 if (!tg
->cfs_rq
[cpu
]->on_list
)
11315 raw_spin_lock_irqsave(&rq
->lock
, flags
);
11316 list_del_leaf_cfs_rq(tg
->cfs_rq
[cpu
]);
11317 raw_spin_unlock_irqrestore(&rq
->lock
, flags
);
11321 void init_tg_cfs_entry(struct task_group
*tg
, struct cfs_rq
*cfs_rq
,
11322 struct sched_entity
*se
, int cpu
,
11323 struct sched_entity
*parent
)
11325 struct rq
*rq
= cpu_rq(cpu
);
11329 init_cfs_rq_runtime(cfs_rq
);
11331 tg
->cfs_rq
[cpu
] = cfs_rq
;
11334 /* se could be NULL for root_task_group */
11339 se
->cfs_rq
= &rq
->cfs
;
11342 se
->cfs_rq
= parent
->my_q
;
11343 se
->depth
= parent
->depth
+ 1;
11347 /* guarantee group entities always have weight */
11348 update_load_set(&se
->load
, NICE_0_LOAD
);
11349 se
->parent
= parent
;
11352 static DEFINE_MUTEX(shares_mutex
);
11354 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
11359 * We can't change the weight of the root cgroup.
11364 shares
= clamp(shares
, scale_load(MIN_SHARES
), scale_load(MAX_SHARES
));
11366 mutex_lock(&shares_mutex
);
11367 if (tg
->shares
== shares
)
11370 tg
->shares
= shares
;
11371 for_each_possible_cpu(i
) {
11372 struct rq
*rq
= cpu_rq(i
);
11373 struct sched_entity
*se
= tg
->se
[i
];
11374 struct rq_flags rf
;
11376 /* Propagate contribution to hierarchy */
11377 rq_lock_irqsave(rq
, &rf
);
11378 update_rq_clock(rq
);
11379 for_each_sched_entity(se
) {
11380 update_load_avg(se
, UPDATE_TG
);
11381 update_cfs_shares(se
);
11383 rq_unlock_irqrestore(rq
, &rf
);
11387 mutex_unlock(&shares_mutex
);
11390 #else /* CONFIG_FAIR_GROUP_SCHED */
11392 void free_fair_sched_group(struct task_group
*tg
) { }
11394 int alloc_fair_sched_group(struct task_group
*tg
, struct task_group
*parent
)
11399 void online_fair_sched_group(struct task_group
*tg
) { }
11401 void unregister_fair_sched_group(struct task_group
*tg
) { }
11403 #endif /* CONFIG_FAIR_GROUP_SCHED */
11406 static unsigned int get_rr_interval_fair(struct rq
*rq
, struct task_struct
*task
)
11408 struct sched_entity
*se
= &task
->se
;
11409 unsigned int rr_interval
= 0;
11412 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11415 if (rq
->cfs
.load
.weight
)
11416 rr_interval
= NS_TO_JIFFIES(sched_slice(cfs_rq_of(se
), se
));
11418 return rr_interval
;
11422 * All the scheduling class methods:
11424 const struct sched_class fair_sched_class
= {
11425 .next
= &idle_sched_class
,
11426 .enqueue_task
= enqueue_task_fair
,
11427 .dequeue_task
= dequeue_task_fair
,
11428 .yield_task
= yield_task_fair
,
11429 .yield_to_task
= yield_to_task_fair
,
11431 .check_preempt_curr
= check_preempt_wakeup
,
11433 .pick_next_task
= pick_next_task_fair
,
11434 .put_prev_task
= put_prev_task_fair
,
11437 .select_task_rq
= select_task_rq_fair
,
11438 .migrate_task_rq
= migrate_task_rq_fair
,
11440 .rq_online
= rq_online_fair
,
11441 .rq_offline
= rq_offline_fair
,
11443 .task_dead
= task_dead_fair
,
11444 .set_cpus_allowed
= set_cpus_allowed_common
,
11447 .set_curr_task
= set_curr_task_fair
,
11448 .task_tick
= task_tick_fair
,
11449 .task_fork
= task_fork_fair
,
11451 .prio_changed
= prio_changed_fair
,
11452 .switched_from
= switched_from_fair
,
11453 .switched_to
= switched_to_fair
,
11455 .get_rr_interval
= get_rr_interval_fair
,
11457 .update_curr
= update_curr_fair
,
11459 #ifdef CONFIG_FAIR_GROUP_SCHED
11460 .task_change_group
= task_change_group_fair
,
11464 #ifdef CONFIG_SCHED_DEBUG
11465 void print_cfs_stats(struct seq_file
*m
, int cpu
)
11467 struct cfs_rq
*cfs_rq
, *pos
;
11470 for_each_leaf_cfs_rq_safe(cpu_rq(cpu
), cfs_rq
, pos
)
11471 print_cfs_rq(m
, cpu
, cfs_rq
);
11475 #ifdef CONFIG_NUMA_BALANCING
11476 void show_numa_stats(struct task_struct
*p
, struct seq_file
*m
)
11479 unsigned long tsf
= 0, tpf
= 0, gsf
= 0, gpf
= 0;
11481 for_each_online_node(node
) {
11482 if (p
->numa_faults
) {
11483 tsf
= p
->numa_faults
[task_faults_idx(NUMA_MEM
, node
, 0)];
11484 tpf
= p
->numa_faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
11486 if (p
->numa_group
) {
11487 gsf
= p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, node
, 0)],
11488 gpf
= p
->numa_group
->faults
[task_faults_idx(NUMA_MEM
, node
, 1)];
11490 print_numa_stats(m
, node
, tsf
, tpf
, gsf
, gpf
);
11493 #endif /* CONFIG_NUMA_BALANCING */
11494 #endif /* CONFIG_SCHED_DEBUG */
11496 __init
void init_sched_fair_class(void)
11499 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
);
11501 #ifdef CONFIG_NO_HZ_COMMON
11502 nohz
.next_balance
= jiffies
;
11503 nohz
.next_update
= jiffies
;
11504 zalloc_cpumask_var(&nohz
.idle_cpus_mask
, GFP_NOWAIT
);