Skip to contentSkip to conversation

sched/fair: A series of load balance patches to improve real-time performance of CFS tasks

PATCH New Xin Zhao 1 participant 11 messages Aug 15 Scheduler

lore
Share & tools
lore

Xin Zhao

author
#0 lore raw

cover sched/fair: A series of load balance patches to improve real-time performance of CFS tasks

Embedded platforms commonly use CONFIG_HZ_250, and testing has revealed that there are numerous instances of unreasonable CPU idle events on such platforms. Unreasonable CPU idle refers to situations where the CPU enters an idle state for a duration of time (t), while there are tasks that can run on the idle CPU and are not limited by cgroup constraints, yet these tasks remain unscheduled for a duration greater than (t), t > 2.5 ms.

Testing has shown that over 95% of these events last less than 4 ms, but there are still some instances of longer durations between 4-5ms, even occasionally between 5-10 ms. For a real-time system, scheduling delays greater than 4 ms can lead to performance spikes.

Enabling this option can effectively reduce the occurrence of unreasonable CPU idle events on low HZ systems like CONFIG_HZ_250, and completely eliminate events exceeding 4 ms. Note that the feature only affects fair tasks.

Note that enabling this feature will increase sys%, as it uses CPU time that would have been idle to expedite the scheduling of tasks. There will also be some CPU overhead involved in searching for suitable tasks.

This feature has been split into several smaller patches, which will be elaborated on one by one later. Below are some test data:

Test one compares the number of unreasonable CPU idle events and their distribution when this feature is enabled versus when it is not, under the same fillback scenario. The test duration was 60 seconds.

      LB_PROMOTE(on/off) 2.5-3ms 3-4ms  4ms+
index 0               on       0     0     0
index 1              off       4    13     1
index 2               on       0     0     0
index 3              off       6     3     0
index 4               on       0     0     0
index 5              off       1     1     0

Test two compares the performance of the system with and without the feature enabled, based on the same fillback scenario. Each test lasts for 25 minutes, and a total of 15 comparative tests were conducted. The results include a comparison of the maximum and median values of end-to-end latency and sys%.

LB_PROMOTE(on/off) on off
end-to-end latency(max) 172 180
end-to-end latency(median of avg) 166 167.68

sys%(max)                           9.68       9.35
sys%(median of avg)                 8.81       8.55

All of the patches are derived from analysis through ftrace and process logs of load balance code flow corresponding to every unreasonable CPU idle event captured during testing.

In patch 4, we define a new feature called LB_PROMOTE, which means to promote load balance. Currently, this feature only optimizes the CFS load balance part. The first three patches are prerequisite patches; patch 1 addresses a common issue unrelated to the LB_PROMOTE feature, while patches 2 and 3 are two prerequisite patches that can be applied independently of LB_PROMOTE feature but are primarily intended to support patches 6 and 7. Patches 5, 7, 8, and 10 are all based on the LB_PROMOTE feature introduced in patch 4. Patch 5 implements an improved version of select_task_rq_fair() for embedded platforms, enhancing performance and real-time capabilities. Patch 7 implements preemptive active balance, while patch 6 allows active_load_balance_cpu_stop() to be reused in preemptive active balance scenarios. Patch 8 removes checks related to avg_idle. Patch 9 is a minor optimization that does not depend on the LB_PROMOTE feature, but since it modifies sched_balance_rq() as patch 10 does, it serves as a precursor to patch 10.

Xin Zhao (10):
sched/fair: Do not set_rd_overloaded() if rd->online != env->cpus scbed/fair: Remove duplicate check for busiest_cpu in
active_load_balance_cpu_stop()
sched/fair: Clear active_balance at the end of
active_load_balance_cpu_stop()
sched/fair: Add LB_PROMOTE feature to enhance real-time performance of
fair tasks
sched/fair: Introduce select_task_rq_fair_thin() to select rq when
LB_PROMOTE
sched/fair: Modify active_load_balance_cpu_stop() to accommodate more
scenarios
sched/fair: Trigger active balance if a CFS task is preempted when
LB_PROMOTE
sched/fair: Do not check avg_idle to prematurely exit newly idle when
LB_PROMOTE
sched/fair: Not goto more_balance if newly idle and has pending task
when LBF_NEED_BREAK
sched/fair: Strive to find a task to migrate if newly idle when
LB_PROMOTE

 kernel/sched/core.c     |   3 +
 kernel/sched/fair.c     | 220 +++++++++++++++++++++++++++++++++++-----
 kernel/sched/features.h |  24 +++++
 kernel/sched/sched.h    |   2 +
 4 files changed, 224 insertions(+), 25 deletions(-)
Signature · 1 line
2.34.1
author
#1 lore raw

PATCH 1/10 sched/fair: Do not set_rd_overloaded() if rd->online != env->cpus

In update_sg_lb_stats(), it only traverses sched_group that belongs to env->cpus, but env->cpus may not necessarily equal rd->online. This can lead to the incorrect clearing of the overloaded flag of rd. For example, if cpuA belongs to the online CPU mask of the rd but does not belong to env->cpus, and cpuA consistently maintains nr_running >= 2, while other CPUs in rd->online keep rq->nr_running <= 1, the overloaded flag of rd will not be set until next update of update_sd_lb_stats() for that rd. During this period, sched_balance_newidle() will prematurely return due to the incorrect assumption that the rd is in a non-overloaded state.

In update_sd_lb_stats(), add a check to verify whether rd->online is equal to env->cpus before calling set_rd_overloaded() to avoid such incorrect settings.

---
 kernel/sched/fair.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/sched/fair.c +6 -2
index dcf860c59a14..13e873b1ef58 100644
@@ -12679,8 +12679,12 @@ static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sd
 		env->fbq_type = fbq_classify_group(&sds->busiest_stat);
 
 	if (!env->sd->parent) {
-		/* update overload indicator if we are at root domain */
-		set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
+		/*
+		 * Update overload indicator if we are at root domain.
+		 * Note that env->cpus may change during sched_balance_rq().
+		 */
+		if (cpumask_equal(env->dst_rq->rd->online, env->cpus))
+			set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
 
 		/* Update over-utilization (tipping point, U >= 0) indicator */
 		set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
Signature · 1 line
2.34.1
author
#2 lore raw

PATCH 2/10 scbed/fair: Remove duplicate check for busiest_cpu in active_load_balance_cpu_stop()

In reply to Xin Zhao

The check for cpu_active(busiest_cpu) already ensures that busiest_cpu has not gone down. An additional check for busiest_cpu != smp_processor_id() is redundant. After this modification, busiest_cpu will no longer be bound to smp_processor_id(), allowing the active_load_balance_cpu_stop function to accommodate more scenarios, such as preempt active balancing feature that will be addressed in later patches.

---
 kernel/sched/fair.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
kernel/sched/fair.c +1 -3
index 13e873b1ef58..11c104010b2e 100644
@@ -13769,9 +13769,7 @@ static int active_load_balance_cpu_stop(void *data)
 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
 		goto out_unlock;
 
-	/* Make sure the requested CPU hasn't gone down in the meantime: */
-	if (unlikely(busiest_cpu != smp_processor_id() ||
-		     !busiest_rq->active_balance))
+	if (unlikely(!busiest_rq->active_balance))
 		goto out_unlock;
 
 	/* Is there any task to move? */
Signature · 1 line
2.34.1
author
#3 lore raw

PATCH 3/10 sched/fair: Clear active_balance at the end of active_load_balance_cpu_stop()

In reply to Xin Zhao

The rq->active_balance flag is used to prevent multiple CPUs from simultaneously dispatching active balance stop tasks. Since there can only ever be one consumer of the stop task, it is not strictly necessary to protect the setting of rq->active_balance to 0 with the rq lock in active_load_balance_cpu_stop(). Therefore, we can move the action of clearing rq->active_balance to the end of active_load_balance_cpu_stop(). The benefit of this approach is that the task load of dst_rq will change due to the execution of attach_one_task(), which helps avoid prematurely clearing rq->active_balance before attach_one_task(), thus preventing unnecessary dispatch of duplicate active balance stop tasks.

Active balance stop task is triggered only when rq->active_balance flag changes from 0 to 1, and there can be at most one consumer of active balance stop task at any given time. Therefore, we should never see zero rq->active_balance in active_load_balance_cpu_stop(), use WARN_ON_ONCE instead.

---
 kernel/sched/fair.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
kernel/sched/fair.c +2 -3
index 11c104010b2e..20d03ceed9d7 100644
@@ -13769,8 +13769,7 @@ static int active_load_balance_cpu_stop(void *data)
 	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
 		goto out_unlock;
 
-	if (unlikely(!busiest_rq->active_balance))
-		goto out_unlock;
+	WARN_ON_ONCE(!busiest_rq->active_balance);
 
 	/* Is there any task to move? */
 	if (busiest_rq->nr_running <= 1)
@@ -13815,13 +13814,13 @@ static int active_load_balance_cpu_stop(void *data)
 	}
 	rcu_read_unlock();
 out_unlock:
-	busiest_rq->active_balance = 0;
 	rq_unlock(busiest_rq, &rf);
 
 	if (p)
 		attach_one_task(target_rq, p);
 
 	local_irq_enable();
+	busiest_rq->active_balance = 0;
 
 	return 0;
 }
Signature · 1 line
2.34.1
author
#4 lore raw

PATCH 4/10 sched/fair: Add LB_PROMOTE feature to enhance real-time performance of fair tasks

In reply to Xin Zhao

Embedded platforms commonly use CONFIG_HZ_250, and testing has revealed that there are numerous instances of unreasonable CPU idle events on such platforms. Unreasonable CPU idle refers to situations where the CPU enters an idle state for a duration of time (t), while there are tasks that can run on the idle CPU and are not limited by cgroup constraints, yet these tasks remain unscheduled for a duration greater than (t), t > 2.5 ms.

Testing has shown that over 95% of these events last less than 4 ms, but there are still some instances of longer durations between 4-5ms, even occasionally between 5-10 ms. For a real-time system, scheduling delays greater than 4 ms can lead to performance spikes.

Enabling this option can effectively reduce the occurrence of unreasonable CPU idle events on low HZ systems like CONFIG_HZ_250, and completely eliminate events exceeding 4 ms. Note that the feature only affects fair tasks.

Note that enabling this feature will increase sys%, as it uses CPU time that would have been idle to expedite the scheduling of tasks. There will also be some CPU overhead involved in searching for suitable tasks.

This feature has been split into several smaller patches, which will be elaborated on one by one later. Below are some test data:

Test one compares the number of unreasonable CPU idle events and their distribution when this feature is enabled versus when it is not, under the same fillback scenario. The test duration was 60 seconds.

      LB_PROMOTE(on/off) 2.5-3ms 3-4ms  4ms+
index 0               on       0     0     0
index 1              off       4    13     1
index 2               on       0     0     0
index 3              off       6     3     0
index 4               on       0     0     0
index 5              off       1     1     0

Test two compares the performance of the system with and without the feature enabled, based on the same fillback scenario. Each test lasts for 25 minutes, and a total of 15 comparative tests were conducted. The results include a comparison of the maximum and median values of end-to-end latency and sys%.

LB_PROMOTE(on/off) on off
end-to-end latency(max) 172 180
end-to-end latency(median of avg) 166 167.68

sys%(max)                           9.68       9.35
sys%(median of avg)                 8.81       8.55
---
 kernel/sched/features.h | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
kernel/sched/features.h +24 -0
index 8f0dee8fc475..4916a4b89ab3 100644
@@ -142,3 +142,27 @@ SCHED_FEAT(LATENCY_WARN, false)
  */
 SCHED_FEAT(NI_RANDOM, true)
 SCHED_FEAT(NI_RATE, true)
+
+/*
+ * Embedded platforms commonly use CONFIG_HZ_250, and testing has revealed that
+ * there are numerous instances of unreasonable CPU idle events on such
+ * platforms. Unreasonable CPU idle refers to situations where the CPU enters
+ * an idle state for a duration of time (t), while there are tasks that can run
+ * on the idle CPU and are not limited by cgroup constraints, yet these tasks
+ * remain unscheduled for a duration greater than (t), t > 2.5 ms.
+ *
+ * Testing has shown that over 95% of these events last less than 4 ms, but
+ * there are still some instances of longer durations between 4-5ms, even
+ * occasionally between 5-10 ms. For a real-time system, scheduling delays
+ * greater than 4 ms can lead to performance spikes.
+ *
+ * Enabling this option can effectively reduce the occurrence of unreasonable
+ * CPU idle events on low HZ systems like CONFIG_HZ_250, and completely
+ * eliminate events exceeding 4 ms. Note that the feature only affects fair
+ * tasks.
+ *
+ * Note that enabling this feature will increase sys%, as it uses CPU time that
+ * would have been idle to expedite the scheduling of tasks. There will also be
+ * some CPU overhead involved in searching for suitable tasks.
+ */
+SCHED_FEAT(LB_PROMOTE, false)
Signature · 1 line
2.34.1
author
#5 lore raw

PATCH 5/10 sched/fair: Introduce select_task_rq_fair_thin() to select rq when LB_PROMOTE

In reply to Xin Zhao

The logic of select_task_rq_fair() is relatively complex, and on typical embedded systems, the number of CPUs in sd_llc domain is often limited to a maximum of 4, and sometimes only 2. This makes the complex logic of select_task_rq_fair() seem less necessary. Additionally, the update logic for the nr_idle_scan value that select_task_rq_fair() relies on is also quite time-consuming.

Moreover, embedded systems require better real-time performance, and with fewer CPUs available, it becomes necessary to bind certain tasks across the sd_llc range. The default enabled feature, SD_WAKE_AFFINE, causes select_task_rq_fair() to take the fast path, often overlooking some idle CPUs across sd_llc domain, leading to increased scheduling latency.

To address this, we introduce the select_task_rq_fair_thin() function, which serves as a streamlined version of select_task_rq_fair(). It can quickly perform CPU selection while also considering the real-time requirements of embedded systems. select_task_rq_fair_thin() retains the priority selection logic for prev_cpu and recent_used_cpu, and it will prioritize CPUs within the sd_llc. If there are no idle CPUs in the sd_llc, it will then look for other available CPUs to run.

When the LB_PROMOTE feature is enabled, select_task_rq_fair_thin() will replace the original select_task_rq_fair(), and the update logic for nr_idle_scan that select_task_rq_fair() relies on will no longer need to be executed.

Testing has shown that in our system with 18 CPUs running at 2.1GHz, where the first three sd_llc domains each contains 4 CPUs and the last sd_llc contains 2 CPUs, under same fillback scenario, select_task_rq_fair_thin() executes 25% faster than the original select_task_rq_fair(). It saves 22ms over a 10-second period, with this optimization accounting for 0.174% of total system time. Additionally, we measured the execution time of update_idle_cpu_scan, which took 0.5ms over the same 10-second period. If we use select_task_rq_fair_thin() instead, this time can be eliminated, accounting for 0.04% of total system time. Therefore, the overall optimization contributes to a reduction of 0.214% of total system time.

---
 kernel/sched/fair.c | 52 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 51 insertions(+), 1 deletion(-)
kernel/sched/fair.c +51 -1
index 20d03ceed9d7..f10e709921fd 100644
@@ -9661,6 +9661,51 @@ static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
 	return target;
 }
 
+/*
+ * A streamlined version of select_task_rq_fair().
+ * It runs faster than select_task_rq_fair, especially when there are not
+ * many CPUs. It will prioritize selecting an idle CPU in the following order:
+ * 1. prev_cpu
+ * 2. recent_used_cpu
+ * 3. cpu belongs to intersection of sd_llc and cpus_ptr
+ * 4. cpu belongs to cpus_ptr but not belongs to sd_llc
+ * If there is no idle CPU in cpus_ptr, it will select prev_cpu.
+ */
+static int select_task_rq_fair_thin(struct task_struct *p, int prev_cpu, int wake_flags)
+{
+	int recent_used_cpu, target, cpu, start = nr_cpu_ids;
+	struct sched_domain *sd;
+
+	if (likely(available_idle_cpu(prev_cpu)))
+		return prev_cpu;
+
+	recent_used_cpu = p->recent_used_cpu;
+	p->recent_used_cpu = prev_cpu;
+	if (recent_used_cpu != prev_cpu && available_idle_cpu(recent_used_cpu))
+		return recent_used_cpu;
+
+	target = prev_cpu;
+	rcu_read_lock();
+
+	sd = rcu_dereference(per_cpu(sd_llc, target));
+	if (sd)
+		start = cpumask_first_and(sched_domain_span(sd), p->cpus_ptr);
+	if (start >= nr_cpu_ids)
+		start = cpumask_first(p->cpus_ptr);
+
+	for_each_cpu_wrap(cpu, p->cpus_ptr, start) {
+		if (available_idle_cpu(cpu)) {
+			target = cpu;
+			goto unlock;
+		}
+	}
+
+unlock:
+	rcu_read_unlock();
+
+	return target;
+}
+
 /*
  * select_task_rq_fair: Select target runqueue for the waking task in domains
  * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
@@ -9682,6 +9727,9 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
 	/* SD_flags and WF_flags share the first nibble */
 	int sd_flag = wake_flags & 0xF;
 
+	if (sched_feat(LB_PROMOTE))
+		return select_task_rq_fair_thin(p, prev_cpu, wake_flags);
+
 	/*
 	 * required for stable ->cpus_allowed
 	 */
@@ -12564,8 +12612,10 @@ static void update_idle_cpu_scan(struct lb_env *env,
 	 * So the write of this hint only occurs during periodic load
 	 * balancing, rather than CPU_NEWLY_IDLE, because the latter
 	 * can fire way more frequently than the former.
+	 * When LB_PROMOTE is enabled, select_task_rq_fair() is no longer
+	 * used, and there is no need to update nr_idle_scan.
 	 */
-	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
+	if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE || sched_feat(LB_PROMOTE))
 		return;
 
 	sd_share = sd->shared;
Signature · 1 line
2.34.1
author
#6 lore raw

PATCH 6/10 sched/fair: Modify active_load_balance_cpu_stop() to accommodate more scenarios

In reply to Xin Zhao

Modify active_load_balance_cpu_stop() to make it more generalized, no longer limited to the context of finding the busiest rq in the sched_balance_rq() scenario to migrate to the dst rq. Change the variables that start with 'busiest' to start with 'src'.

Additionally, adjust the reference to the active_balance variable from busiest_rq->active_balance to this_rq()->active_balance. With these changes, the CPU where the stop task is located can serve as either a dst CPU or a src CPU, laying the groundwork for the upcoming preempt active balance feature.

---
 kernel/sched/fair.c | 30 +++++++++++++++---------------
 1 file changed, 15 insertions(+), 15 deletions(-)
kernel/sched/fair.c +15 -15
index f10e709921fd..9ffd01717599 100644
@@ -13796,33 +13796,33 @@ update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
 
 /*
  * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
- * running tasks off the busiest CPU onto idle CPUs. It requires at
+ * one running task off the src CPU onto dst CPU. It requires at
  * least 1 task to be running on each physical CPU where possible, and
  * avoids physical / logical imbalances.
  */
 static int active_load_balance_cpu_stop(void *data)
 {
-	struct rq *busiest_rq = data;
-	int busiest_cpu = cpu_of(busiest_rq);
-	int target_cpu = busiest_rq->push_cpu;
+	struct rq *src_rq = data;
+	int src_cpu = cpu_of(src_rq);
+	int target_cpu = this_rq()->push_cpu;
 	struct rq *target_rq = cpu_rq(target_cpu);
 	struct sched_domain *sd;
 	struct task_struct *p = NULL;
 	struct rq_flags rf;
 
-	rq_lock_irq(busiest_rq, &rf);
+	rq_lock_irq(src_rq, &rf);
 	/*
 	 * Between queueing the stop-work and running it is a hole in which
 	 * CPUs can become inactive. We should not move tasks from or to
 	 * inactive CPUs.
 	 */
-	if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
+	if (!cpu_active(src_cpu) || !cpu_active(target_cpu))
 		goto out_unlock;
 
-	WARN_ON_ONCE(!busiest_rq->active_balance);
+	WARN_ON_ONCE(!this_rq()->active_balance);
 
 	/* Is there any task to move? */
-	if (busiest_rq->nr_running <= 1)
+	if (src_rq->nr_running <= 1)
 		goto out_unlock;
 
 	/*
@@ -13830,12 +13830,12 @@ static int active_load_balance_cpu_stop(void *data)
 	 * we need to fix it. Originally reported by
 	 * Bjorn Helgaas on a 128-CPU setup.
 	 */
-	WARN_ON_ONCE(busiest_rq == target_rq);
+	WARN_ON_ONCE(src_rq == target_rq);
 
 	/* Search for an sd spanning us and the target CPU. */
 	rcu_read_lock();
 	for_each_domain(target_cpu, sd) {
-		if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
+		if (cpumask_test_cpu(src_cpu, sched_domain_span(sd)))
 			break;
 	}
 
@@ -13844,14 +13844,14 @@ static int active_load_balance_cpu_stop(void *data)
 			.sd		= sd,
 			.dst_cpu	= target_cpu,
 			.dst_rq		= target_rq,
-			.src_cpu	= busiest_rq->cpu,
-			.src_rq		= busiest_rq,
+			.src_cpu	= src_rq->cpu,
+			.src_rq		= src_rq,
 			.idle		= CPU_IDLE,
 			.flags		= LBF_ACTIVE_LB,
 		};
 
 		schedstat_inc(sd->alb_count);
-		update_rq_clock(busiest_rq);
+		update_rq_clock(src_rq);
 
 		p = detach_one_task(&env);
 		if (p) {
@@ -13864,13 +13864,13 @@ static int active_load_balance_cpu_stop(void *data)
 	}
 	rcu_read_unlock();
 out_unlock:
-	rq_unlock(busiest_rq, &rf);
+	rq_unlock(src_rq, &rf);
 
 	if (p)
 		attach_one_task(target_rq, p);
 
 	local_irq_enable();
-	busiest_rq->active_balance = 0;
+	this_rq()->active_balance = 0;
 
 	return 0;
 }
Signature · 1 line
2.34.1
author
#7 lore raw

PATCH 7/10 sched/fair: Trigger active balance if a CFS task is preempted when LB_PROMOTE

In reply to Xin Zhao

When LB_PROMOTE is on, in addition to the scenarios modified in the previous patches regarding .select_task_rq implement, preemption of CFS tasks also needs to be addressed. Once a CFS task is preempted by a real-time task, if that task is executing logic in a critical section that does not support priority inheritance, such as read-write locks or read-write semaphores, it may lead to performance issues.

By adding this checkpoint for when a CFS task is preempted, we can migrate the task to an idle CPU, thus alleviating such performance problems. Additionally, the patch set for the LB_PROMOTE feature does not alter the logic of task_hot(), so this patch will not significantly increase the frequency of load balance migration.

The newly introduced function preempt_active_balance() will be triggered in __schedule() when it detects that the previous task has been preempted while the LB_PROMOTE feature is enabled. preempt_active_balance() will first check whether the currently preempted task has other CPUs available to run on. If there are idle CPUs available, the preempted task will be migrated to one of those idle CPUs.

The implementation of preempt_active_balance() considers the desire not to introduce additional "holes" of rq locks, so the migration triggering action is deferred to the balance_callback which is trigger_preempt_alb(). trigger_preempt_alb() will issue a stop work to allow the idle target CPU to perform the migration.

After the modifications made by the previous patches, we can reuse active_load_balance_cpu_stop() to assist in this migration action. In preempt_active_balance(), we use list_move_tail to move the currently preempted task to position where detach_one_task() will first traverse, allowing active_load_balance_cpu_stop() to prioritize finding the task.

---
 kernel/sched/core.c  |  3 ++
 kernel/sched/fair.c  | 80 ++++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h |  2 ++
 3 files changed, 85 insertions(+)
kernel/sched/core.c +3 -0
index 2e7cde033a31..757ea5ef303d 100644
@@ -7227,6 +7227,9 @@ static void __sched notrace __schedule(int sched_mode)
 
 		trace_sched_switch(preempt, prev, next, prev_state);
 
+		if (sched_feat(LB_PROMOTE) && preempt)
+			preempt_active_balance(prev);
+
 		/* Also unlocks the rq: */
 		rq = context_switch(rq, prev, next, &rf);
 	} else {
kernel/sched/fair.c +80 -0

86 lines not on this page · raw message

kernel/sched/sched.h +2 -0
index 26ae13c86b69..11848708e5ce 100644
@@ -4193,6 +4193,8 @@ extern struct balance_callback *splice_balance_callbacks(struct rq *rq);
 extern void __balance_callbacks(struct rq *rq, struct rq_flags *rf);
 extern void balance_callbacks(struct rq *rq, struct balance_callback *head);
 
+extern void preempt_active_balance(struct task_struct *prev);
+
 /*
  * The 'sched_change' pattern is the safe, easy and slow way of changing a
  * task's scheduling properties. It dequeues a task, such that the scheduler
Signature · 1 line
2.34.1
author
#8 lore raw

PATCH 8/10 sched/fair: Do not check avg_idle to prematurely exit newly idle when LB_PROMOTE

In reply to Xin Zhao

When LB_PROMOTE is on, there are high real-time requirements, we should avoid prematurely exiting in sched_balance_newidle() due to a short avg_idle. This is because after any newly idle state, if no tasks are found to run, there may be a long-term lack of new incoming tasks to wake up on that CPU. Meanwhile, there may be tasks waiting to run on other cores, leading to unreasonable CPU idleness. The definition of unreasonable CPU idleness can be found in the commit-log of the previous patch that introduced the LB_PROMOTE feature.

---
 kernel/sched/fair.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
kernel/sched/fair.c +3 -2
index d2b538abdf3e..8a1d2763a923 100644
@@ -14694,7 +14694,7 @@ static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
 		goto out;
 
 	if (!get_rd_overloaded(this_rq->rd) ||
-	    this_rq->avg_idle < sd->max_newidle_lb_cost) {
+	    (!sched_feat(LB_PROMOTE) && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
 
 		update_next_balance(sd, &next_balance);
 		goto out;
@@ -14716,7 +14716,8 @@ static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
 
 		update_next_balance(sd, &next_balance);
 
-		if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
+		if (!sched_feat(LB_PROMOTE) &&
+		    this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
 			break;
 
 		if (sd->flags & SD_BALANCE_NEWIDLE) {
Signature · 1 line
2.34.1
author
#9 lore raw

PATCH 9/10 sched/fair: Not goto more_balance if newly idle and has pending task when LBF_NEED_BREAK

In reply to Xin Zhao

When LBF_NEED_BREAK flag is set in env.flags, no longer unconditionally go to more_balance. Instead, we exclude the case when it is newly idle and there are pending tasks. This helps avoid unnecessary CPU wastage caused by repeatedly going to more_balance when the task load is too high during sched_balance_rq().

In another 'goto more_balance' case when LBF_DST_PINNED flag is set in env.flags, we do not need to add the check. Because LBF_DST_PINNED flag is only set within can_migrate_task(). Before setting LBF_DST_PINNED flag in can_migrate_task(), there is a check to see if it is newly idle. can_migrate_task() will exit without setting the LBF_DST_PINNED flag if it is newly idle.

---
 kernel/sched/fair.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/sched/fair.c +3 -1
index 8a1d2763a923..1ae351ea5949 100644
@@ -13561,7 +13561,9 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 
 		if (env.flags & LBF_NEED_BREAK) {
 			env.flags &= ~LBF_NEED_BREAK;
-			goto more_balance;
+			if (!(env.idle == CPU_NEWLY_IDLE &&
+			      (env.dst_rq->nr_running > 0 || env.dst_rq->ttwu_pending)))
+				goto more_balance;
 		}
 
 		/*
Signature · 1 line
2.34.1
author
#10 lore raw

PATCH 10/10 sched/fair: Strive to find a task to migrate if newly idle when LB_PROMOTE

In reply to Xin Zhao

This patch is a core modification within this patch set. The simple_find label in this patch implements a straightforward logic for finding a migration task. It allows any instances in sched_balance_rq() that are unable to find a migration task for various reasons to fallback to logic executing the simple_find label to find one before exiting newly idle process.

This patch addresses the newly idle scenario by preventing early exit in cases when !ld_moved && !active_balance, effectively executing the logic of simple_find label. Testing has shown that the situations listed below, account for a significant proportion of early exits:
1. Failure in sched_balance_find_src_group
2. Failure in sched_balance_find_src_rq
3. ld_moved is 0 and active_balance has not been triggered

Of course, even with this change, it is still possible that no migration task can be found. However, it at least ensures that all selectable CPUs within the sched_domain have been thoroughly traversed.

---
 kernel/sched/fair.c | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)
kernel/sched/fair.c +37 -1
index 1ae351ea5949..10ec7bb9e18c 100644
@@ -13470,6 +13470,8 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 	struct rq *busiest;
 	struct rq_flags rf;
 	struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
+	int cpu;
+	bool sfind = false;
 	struct lb_env env = {
 		.sd		= sd,
 		.dst_cpu	= this_cpu,
@@ -13504,15 +13506,41 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 	group = sched_balance_find_src_group(&env);
 	if (!group) {
 		schedstat_inc(sd->lb_nobusyg[idle]);
+		if (sched_feat(LB_PROMOTE))
+			goto simple_find;
 		goto out_balanced;
 	}
 
 	busiest = sched_balance_find_src_rq(&env, group);
 	if (!busiest) {
 		schedstat_inc(sd->lb_nobusyq[idle]);
+		if (sched_feat(LB_PROMOTE))
+			goto simple_find;
 		goto out_balanced;
 	}
+	goto begin_balance;
+
+simple_find:
+	if (env.idle != CPU_NEWLY_IDLE ||
+	    (env.dst_rq->nr_running > 0 || env.dst_rq->ttwu_pending))
+		goto out_balanced;
 
+	sfind = true;
+	env.migration_type = migrate_task;
+	env.imbalance = 1;
+
+	for_each_cpu_andnot(cpu, env.cpus, env.dst_grpmask) {
+		busiest = cpu_rq(cpu);
+		if (busiest->nr_running <= 1) {
+			__cpumask_clear_cpu(cpu, cpus);
+			continue;
+		}
+		break;
+	}
+	if (cpu >= nr_cpu_ids)
+		goto out_balanced;
+
+begin_balance:
 	WARN_ON_ONCE(busiest == env.dst_rq);
 
 	update_lb_imbalance_stat(&env, sd, idle);
@@ -13615,6 +13643,7 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 
 		/* All tasks on this runqueue were pinned by CPU affinity */
 		if (unlikely(env.flags & LBF_ALL_PINNED)) {
+check_redo:
 			__cpumask_clear_cpu(cpu_of(busiest), cpus);
 			/*
 			 * Attempting to continue load balancing at the current
@@ -13627,6 +13656,8 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 			if (!cpumask_subset(cpus, env.dst_grpmask)) {
 				env.loop = 0;
 				env.loop_break = SCHED_NR_MIGRATE_BREAK;
+				if (sfind)
+					goto simple_find;
 				goto redo;
 			}
 			goto out_all_pinned;
@@ -13668,8 +13699,11 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 		 * if the curr task on busiest CPU can't be
 		 * moved to this_cpu:
 		 */
-		if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr))
+		if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
+			if (sched_feat(LB_PROMOTE) && env.idle == CPU_NEWLY_IDLE)
+				goto check_redo;
 			goto out_one_pinned;
+		}
 
 		/* Record that we found at least one task that could run on this_cpu */
 		env.flags &= ~LBF_ALL_PINNED;
@@ -13703,6 +13737,8 @@ static int sched_balance_rq(int this_cpu, struct rq *this_rq,
 	preempt_enable();
 
 out_unbalanced:
+	if (sched_feat(LB_PROMOTE) && !active_balance && env.idle == CPU_NEWLY_IDLE)
+		goto check_redo;
 	/* We were unbalanced, so reset the balancing interval */
 	sd->balance_interval = sd->min_interval;
 	goto out;
Signature · 1 line
2.34.1