sched/core: Fixes and enhancements around spurious need_resched() and idle load balancing
K Prateek Nayak
reviewercover sched/core: Fixes and enhancements around spurious need_resched() and idle load balancing
Since commit b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()"), an idle CPU in TIF_POLLING_NRFLAG can be pulled out of idle by setting TIF_NEED_RESCHED instead of sending an actual IPI. This affects at least three scenarios that have been described below:
o A need_resched() check within a call function does not necessarily indicate a task wakeup since a CPU intending to send an IPI to an idle target in TIF_POLLING_NRFLAG mode can simply queue the SMP-call-function and set the TIF_NEED_RESCHED flag to pull the polling target out of idle. The SMP-call-function will be executed by flush_smp_call_function_queue() on the idle-exit path. On x86, where mwait_idle_with_hints() sets TIF_POLLING_NRFLAG for long idling, this leads to idle load balancer bailing out early since need_resched() check in nohz_csd_func() returns true in most instances.
o A TIF_POLLING_NRFLAG idling CPU woken up to process an IPI will end up calling schedule() even in cases where the call function does not wake up a new task on the idle CPU, thus delaying the idle re-entry.
o Julia Lawall reported a case where a softirq raised from a SMP-call-function on an idle CPU will wake up ksoftirqd since flush_smp_call_function_queue() executes in the idle thread's context. This can throw off the idle load balancer by making the idle CPU appear busy since ksoftirqd just woke on the said CPU [1].
The three patches address each of the above issue individually, the first one by removing the need_resched() check in nohz_csd_func() with a proper justification, the second by introducing a fast-path in __schedule() to speed up idle re-entry in case TIF_NEED_RESCHED was set simply to process an IPI that did not perform a wakeup, and the third by notifying raise_softirq() that the softirq was raised from a SMP-call-function executed by the idle or migration thread in flush_smp_call_function_queue(), and waking ksoftirqd is unnecessary since a call to do_softirq_post_smp_call_flush() will follow soon.
Previous attempts to solve these problems involved introducing a new TIF_NOTIFY_IPI flag to notify a TIF_POLLING_NRFLAG CPU of a pending IPI and skip calling __schedule() in such cases but it involved using atomic ops which could have performance implications [2]. Instead, Peter suggested the approach outlined in the first two patches of the series. The third one is an RFC to that (hopefully) solves the problem Julia was chasing down related to idle load balancing.
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/
This patch is based on tip:sched/core at commit c793a62823d1 ("sched/core: Drop spinlocks on contention iff kernel is preemptible")
--
K Prateek Nayak (2):
sched/core: Remove the unnecessary need_resched() check in
nohz_csd_func()
softirq: Avoid waking up ksoftirqd from
flush_smp_call_function_queue()
Peter Zijlstra (1):
sched/core: Introduce SM_IDLE and an idle re-entry fast-path in
__schedule()
kernel/sched/core.c | 40 ++++++++++++++++++++-------------------- kernel/sched/smp.h | 2 ++ kernel/smp.c | 32 ++++++++++++++++++++++++++++++++ kernel/softirq.c | 10 +++++++++- 4 files changed, 63 insertions(+), 21 deletions(-)
base-commit: c793a62823d1ce8f70d9cfc7803e3ea436277cda
Signature · 1 line
2.34.1
K Prateek Nayak
reviewerPATCH 1/3 sched/core: Remove the unnecessary need_resched() check in nohz_csd_func()
The need_resched() check currently in nohz_csd_func() can be tracked to have been added in scheduler_ipi() back in 2011 via commit ca38062e57e9 ("sched: Use resched IPI to kick off the nohz idle balance")
Since then, it has travelled quite a bit but it seems like an idle_cpu() check currently is sufficient to detect the need to bail out from an idle load balancing. To justify this removal, consider all the following case where an idle load balancing could race with a task wakeup:
o Since commit f3dd3f674555b ("sched: Remove the limitation of WF_ON_CPU on wakelist if wakee cpu is idle") a target perceived to be idle (target_rq->nr_running == 0) will return true for ttwu_queue_cond(target) which will offload the task wakeup to the idle target via an IPI.
In all such cases target_rq->ttwu_pending will be set to 1 before queuing the wake function.
If an idle load balance races here, following scenarios are possible:
- The CPU is not in TIF_POLLING_NRFLAG mode in which case an actual IPI is sent to the CPU to wake it out of idle. If the nohz_csd_func() queues before sched_ttwu_pending(), the idle load balance will bail out since idle_cpu(target) returns 0 since target_rq->ttwu_pending is 1. If the nohz_csd_func() is queued after sched_ttwu_pending() it should see rq->nr_running to be non-zero and bail out of idle load balancing.
- The CPU is in TIF_POLLING_NRFLAG mode and instead of an actual IPI, the sender will simply set TIF_NEED_RESCHED for the target to put it out of idle and flush_smp_call_function_queue() in do_idle() will execute the call function. Depending on the ordering of the queuing of nohz_csd_func() and sched_ttwu_pending(), the idle_cpu() check in nohz_csd_func() should either see target_rq->ttwu_pending = 1 or target_rq->nr_running to be non-zero if there is a genuine task wakeup racing with the idle load balance kick.
o The waker CPU perceives the target CPU to be busy (targer_rq->nr_running != 0) but the CPU is in fact going idle and due to a series of unfortunate events, the system reaches a case where the waker CPU decides to perform the wakeup by itself in ttwu_queue() on the target CPU but target is concurrently selected for idle load balance (Can this happen? I'm not sure, but we'll consider its possibility to estimate the worst case scenario).
ttwu_do_activate() calls enqueue_task() which would increment "rq->nr_running" post which it calls wakeup_preempt() which is responsible for setting TIF_NEED_RESCHED (via a resched IPI or by setting TIF_NEED_RESCHED on a TIF_POLLING_NRFLAG idle CPU) The key thing to note in this case is that rq->nr_running is already non-zero in case of a wakeup before TIF_NEED_RESCHED is set which would lead to idle_cpu() check returning false.
In all cases, it seems that need_resched() check is unnecessary when checking for idle_cpu() first since an impending wakeup racing with idle load balancer will either set the "rq->ttwu_pending" or indicate a newly woken task via "rq->nr_running".
Chasing the reason why this check might have existed in the first place, I came across Peter's suggestion on the fist iteration of Suresh's patch from 2011 [1] where the condition to raise the SCHED_SOFTIRQ was:
sched_ttwu_do_pending(list); if (unlikely((rq->idle == current) && rq->nohz_balance_kick && !need_resched())) raise_softirq_irqoff(SCHED_SOFTIRQ);
However, since this was preceded by sched_ttwu_do_pending() which is equivalent of sched_ttwu_pending() in the current upstream kernel, the need_resched() check was necessary to catch a newly queued task. Peter suggested modifying it to:
if (idle_cpu() && rq->nohz_balance_kick && !need_resched()) raise_softirq_irqoff(SCHED_SOFTIRQ);
where idle_cpu() seems to have replaced "rq->idle == current" check. However, even back then, the idle_cpu() check would have been sufficient to have caught the enqueue of a new task and since commit b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()") overloads the interpretation of TIF_NEED_RESCHED for TIF_POLLING_NRFLAG idling, remove the need_resched() check in nohz_csd_func() to raise SCHED_SOFTIRQ based on Peter's suggestion.
--- kernel/sched/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/core.c +1 -1
@@ -1205,7 +1205,7 @@ static void nohz_csd_func(void *info)WARN_ON (!(flags &NOHZ_KICK_MASK )); rq->idle_balance =idle_cpu (cpu); -if (rq->idle_balance && !need_resched ()) { +if (rq->idle_balance) { rq->nohz_idle_balance = flags;raise_softirq_irqoff (SCHED_SOFTIRQ ); }
Signature · 1 line
2.34.1
Peter Zijlstra
maintainerRe: [PATCH 1/3] sched/core: Remove the unnecessary need_resched() check in nohz_csd_func()
Quoted 28 lines · K Prateek Nayak
The
need_resched()check currently innohz_csd_func()can be tracked to have been added inscheduler_ipi()back in 2011 via commitca38062e57e9("sched: Use resched IPI to kick off the nohz idle balance")Since then, it has travelled quite a bit but it seems like an
idle_cpu()check currently is sufficient to detect the need to bail out from an idle load balancing. To justify this removal, consider all the following case where an idle load balancing could race with a task wakeup:o Since commit
f3dd3f674555b("sched: Remove the limitation ofWF_ON_CPUon wakelist if wakee cpu is idle") a target perceived to be idle (target_rq->nr_running== 0) will return true forttwu_queue_cond(target)which will offload the task wakeup to the idle target via an IPI.In all such cases
target_rq->ttwu_pendingwill be set to 1 before queuing the wake function.If an idle load balance races here, following scenarios are possible:
- The CPU is not in
TIF_POLLING_NRFLAGmode in which case an actual IPI is sent to the CPU to wake it out of idle. If thenohz_csd_func()queues beforesched_ttwu_pending(), the idle load balance will bail out sinceidle_cpu(target)returns 0 sincetarget_rq->ttwu_pendingis 1. If thenohz_csd_func()is queued aftersched_ttwu_pending()it should seerq->nr_runningto be non-zero and bail out of idle load balancing.
Quoted 8 lines
- The CPU is in
TIF_POLLING_NRFLAGmode and instead of an actual IPI, the sender will simply setTIF_NEED_RESCHEDfor the target to put it out of idle andflush_smp_call_function_queue()indo_idle()will execute the call function. Depending on the ordering of the queuing ofnohz_csd_func()andsched_ttwu_pending(), theidle_cpu()check innohz_csd_func()should either seetarget_rq->ttwu_pending= 1 ortarget_rq->nr_runningto be non-zero if there is a genuine task wakeup racing with the idle load balance kick.
For completion sake, we should also consider the !TTWU_QUEUE case, this configuration is default for PREEMPT_RT, where the wake_list is a source of non-determinism.
In quick reading I think that case should be fine, since we directly enqueue remotely and ->nr_running adjusts accordingly, but it is late in the day and I'm easily mistaken.
Quoted 16 lines
o The waker CPU perceives the target CPU to be busy (
targer_rq->nr_running!= 0) but the CPU is in fact going idle and due to a series of unfortunate events, the system reaches a case where the waker CPU decides to perform the wakeup by itself inttwu_queue()on the target CPU but target is concurrently selected for idle load balance (Can this happen? I'm not sure, but we'll consider its possibility to estimate the worst case scenario).
ttwu_do_activate()callsenqueue_task()which would increment "rq->nr_running" post which it callswakeup_preempt()which is responsible for settingTIF_NEED_RESCHED(via a resched IPI or by settingTIF_NEED_RESCHEDon aTIF_POLLING_NRFLAGidle CPU) The key thing to note in this case is thatrq->nr_runningis already non-zero in case of a wakeup beforeTIF_NEED_RESCHEDis set which would lead toidle_cpu()check returning false.
Quoted 4 lines
In all cases, it seems that
need_resched()check is unnecessary when checking foridle_cpu()first since an impending wakeup racing with idle load balancer will either set the "rq->ttwu_pending" or indicate a newly woken task via "rq->nr_running".
Right.
Quoted 19 lines
Chasing the reason why this check might have existed in the first place, I came across Peter's suggestion on the fist iteration of Suresh's patch from 2011 [1] where the condition to raise the
SCHED_SOFTIRQwas:sched_ttwu_do_pending(list); if (unlikely((rq->idle == current) && rq->nohz_balance_kick && !need_resched())) raise_softirq_irqoff(SCHED_SOFTIRQ);However, since this was preceded by
sched_ttwu_do_pending()which is equivalent ofsched_ttwu_pending()in the current upstream kernel, theneed_resched()check was necessary to catch a newly queued task. Peter suggested modifying it to:if (idle_cpu() && rq->nohz_balance_kick && !need_resched()) raise_softirq_irqoff(SCHED_SOFTIRQ);
Quoted 7 lines
where
idle_cpu()seems to have replaced "rq->idle== current" check. However, even back then, theidle_cpu()check would have been sufficient to have caught the enqueue of a new task and since commitb2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") overloads the interpretation ofTIF_NEED_RESCHEDforTIF_POLLING_NRFLAGidling, remove theneed_resched()check innohz_csd_func()to raiseSCHED_SOFTIRQbased on Peter's suggestion.
... sooo many years ago :-)
Quoted 25 lines
Fixes b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()")Suggested-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>--- kernel/sched/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)kernel/sched/core.c +1
-1@@ -1205,7 +1205,7 @@ static void nohz_csd_func(void *info)WARN_ON (!(flags &NOHZ_KICK_MASK )); rq->idle_balance =idle_cpu (cpu); -if (rq->idle_balance && !need_resched ()) { +if (rq->idle_balance) { rq->nohz_idle_balance = flags;raise_softirq_irqoff (SCHED_SOFTIRQ ); }Signature · 1 line
2.34.1
K Prateek Nayak
reviewerRe: [PATCH 1/3] sched/core: Remove the unnecessary need_resched() check in nohz_csd_func()
Hello Peter,
Quoted 38 lines · Peter Zijlstra
Quoted 28 lines · K Prateek Nayak
The
need_resched()check currently innohz_csd_func()can be tracked to have been added inscheduler_ipi()back in 2011 via commitca38062e57e9("sched: Use resched IPI to kick off the nohz idle balance")Since then, it has travelled quite a bit but it seems like an
idle_cpu()check currently is sufficient to detect the need to bail out from an idle load balancing. To justify this removal, consider all the following case where an idle load balancing could race with a task wakeup:o Since commit
f3dd3f674555b("sched: Remove the limitation ofWF_ON_CPUon wakelist if wakee cpu is idle") a target perceived to be idle (target_rq->nr_running== 0) will return true forttwu_queue_cond(target)which will offload the task wakeup to the idle target via an IPI.In all such cases
target_rq->ttwu_pendingwill be set to 1 before queuing the wake function.If an idle load balance races here, following scenarios are possible:
- The CPU is not in
TIF_POLLING_NRFLAGmode in which case an actual IPI is sent to the CPU to wake it out of idle. If thenohz_csd_func()queues beforesched_ttwu_pending(), the idle load balance will bail out sinceidle_cpu(target)returns 0 sincetarget_rq->ttwu_pendingis 1. If thenohz_csd_func()is queued aftersched_ttwu_pending()it should seerq->nr_runningto be non-zero and bail out of idle load balancing.Quoted 8 lines
- The CPU is in
TIF_POLLING_NRFLAGmode and instead of an actual IPI, the sender will simply setTIF_NEED_RESCHEDfor the target to put it out of idle andflush_smp_call_function_queue()indo_idle()will execute the call function. Depending on the ordering of the queuing ofnohz_csd_func()andsched_ttwu_pending(), theidle_cpu()check innohz_csd_func()should either seetarget_rq->ttwu_pending= 1 ortarget_rq->nr_runningto be non-zero if there is a genuine task wakeup racing with the idle load balance kick.
Quoted 7 lines
For completion sake, we should also consider the !TTWU_QUEUE case, this configuration is default for
PREEMPT_RT, where thewake_listis a source of non-determinism.In quick reading I think that case should be fine, since we directly enqueue remotely and ->nr_running adjusts accordingly, but it is late in the day and I'm easily mistaken.
From what I've seen, an enqueue will always update "rq->nr_running" before setting the "NEED_RESCHED" flag but I'll go confirm that again and report back in case what that is false.
Quoted 25 lines
Quoted 17 lines
o The waker CPU perceives the target CPU to be busy (
targer_rq->nr_running!= 0) but the CPU is in fact going idle and due to a series of unfortunate events, the system reaches a case where the waker CPU decides to perform the wakeup by itself inttwu_queue()on the target CPU but target is concurrently selected for idle load balance (Can this happen? I'm not sure, but we'll consider its possibility to estimate the worst case scenario).
ttwu_do_activate()callsenqueue_task()which would increment "rq->nr_running" post which it callswakeup_preempt()which is responsible for settingTIF_NEED_RESCHED(via a resched IPI or by settingTIF_NEED_RESCHEDon aTIF_POLLING_NRFLAGidle CPU) The key thing to note in this case is thatrq->nr_runningis already non-zero in case of a wakeup beforeTIF_NEED_RESCHEDis set which would lead toidle_cpu()check returning false.Quoted 4 lines
In all cases, it seems that
need_resched()check is unnecessary when checking foridle_cpu()first since an impending wakeup racing with idle load balancer will either set the "rq->ttwu_pending" or indicate a newly woken task via "rq->nr_running".Right.
Quoted 1 line
[..snip..]
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [PATCH 1/3] sched/core: Remove the unnecessary need_resched() check in nohz_csd_func()
In reply to K Prateek Nayak(+ Thomas, Sebastian, Christoph)
Hello everyone,
Adding folks who were cc'd on
https://lore.kernel.org/all/[email protected]/
Quoted 85 lines · K Prateek Nayak
The
need_resched()check currently innohz_csd_func()can be tracked to have been added inscheduler_ipi()back in 2011 via commitca38062e57e9("sched: Use resched IPI to kick off the nohz idle balance")Since then, it has travelled quite a bit but it seems like an
idle_cpu()check currently is sufficient to detect the need to bail out from an idle load balancing. To justify this removal, consider all the following case where an idle load balancing could race with a task wakeup:o Since commit
f3dd3f674555b("sched: Remove the limitation ofWF_ON_CPUon wakelist if wakee cpu is idle") a target perceived to be idle (target_rq->nr_running== 0) will return true forttwu_queue_cond(target)which will offload the task wakeup to the idle target via an IPI.In all such cases
target_rq->ttwu_pendingwill be set to 1 before queuing the wake function.If an idle load balance races here, following scenarios are possible:
- The CPU is not in
TIF_POLLING_NRFLAGmode in which case an actual IPI is sent to the CPU to wake it out of idle. If thenohz_csd_func()queues beforesched_ttwu_pending(), the idle load balance will bail out sinceidle_cpu(target)returns 0 sincetarget_rq->ttwu_pendingis 1. If thenohz_csd_func()is queued aftersched_ttwu_pending()it should seerq->nr_runningto be non-zero and bail out of idle load balancing.- The CPU is in
TIF_POLLING_NRFLAGmode and instead of an actual IPI, the sender will simply setTIF_NEED_RESCHEDfor the target to put it out of idle andflush_smp_call_function_queue()indo_idle()will execute the call function. Depending on the ordering of the queuing ofnohz_csd_func()andsched_ttwu_pending(), theidle_cpu()check innohz_csd_func()should either seetarget_rq->ttwu_pending= 1 ortarget_rq->nr_runningto be non-zero if there is a genuine task wakeup racing with the idle load balance kick.o The waker CPU perceives the target CPU to be busy (
targer_rq->nr_running!= 0) but the CPU is in fact going idle and due to a series of unfortunate events, the system reaches a case where the waker CPU decides to perform the wakeup by itself inttwu_queue()on the target CPU but target is concurrently selected for idle load balance (Can this happen? I'm not sure, but we'll consider its possibility to estimate the worst case scenario).
ttwu_do_activate()callsenqueue_task()which would increment "rq->nr_running" post which it callswakeup_preempt()which is responsible for settingTIF_NEED_RESCHED(via a resched IPI or by settingTIF_NEED_RESCHEDon aTIF_POLLING_NRFLAGidle CPU) The key thing to note in this case is thatrq->nr_runningis already non-zero in case of a wakeup beforeTIF_NEED_RESCHEDis set which would lead toidle_cpu()check returning false.In all cases, it seems that
need_resched()check is unnecessary when checking foridle_cpu()first since an impending wakeup racing with idle load balancer will either set the "rq->ttwu_pending" or indicate a newly woken task via "rq->nr_running".Chasing the reason why this check might have existed in the first place, I came across Peter's suggestion on the fist iteration of Suresh's patch from 2011 [1] where the condition to raise the
SCHED_SOFTIRQwas:sched_ttwu_do_pending(list); if (unlikely((rq->idle == current) && rq->nohz_balance_kick && !need_resched())) raise_softirq_irqoff(SCHED_SOFTIRQ);However, since this was preceded by
sched_ttwu_do_pending()which is equivalent ofsched_ttwu_pending()in the current upstream kernel, theneed_resched()check was necessary to catch a newly queued task. Peter suggested modifying it to:if (idle_cpu() && rq->nohz_balance_kick && !need_resched()) raise_softirq_irqoff(SCHED_SOFTIRQ);where
idle_cpu()seems to have replaced "rq->idle== current" check. However, even back then, theidle_cpu()check would have been sufficient to have caught the enqueue of a new task and since commitb2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") overloads the interpretation ofTIF_NEED_RESCHEDforTIF_POLLING_NRFLAGidling, remove theneed_resched()check innohz_csd_func()to raiseSCHED_SOFTIRQbased on Peter's suggestion.
Quoted 3 lines
Fixes b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()")
Turns out the above commit + commit 1a90bfd22020 ("smp: Make softirq handling RT safe in flush_smp_call_function_queue()") will trigger the WARN_ON_ONCE() in do_softirq_post_smp_call_flush for RT kernels after this change since the nohz_csd_func() will now raise a SCHED_SOFTIRQ to trigger the idle balance and is executed from flush_smp_call_function_queue() in do_idle().
I noticed the following splat early into the boot during my testing of the series:
------------[ cut here ]------------
WARNING: CPU: 4 PID: 0 at kernel/softirq.c:326 do_softirq_post_smp_call_flush+0x1a/0x40
Modules linked in:
CPU: 4 PID: 0 Comm: swapper/4 Not tainted 6.10.0-rc6-rt11-test-rt+ #1160
Hardware name: Dell Inc. PowerEdge R6525/024PW1, BIOS 2.7.3 03/30/2022
RIP: 0010:do_softirq_post_smp_call_flush+0x1a/0x40
Code: ...
RSP: 0018:ffffb3ae003a7eb8 EFLAGS: 00010002
RAX: 0000000000000080 RBX: 0000000000000282 RCX: 0000000000000007
RDX: 0000000000000000 RSI: ffff9fc3fb4492e0 RDI: 0000000000000000
RBP: 0000000000000000 R08: 0000000000000000 R09: 00000000ffffffff
R10: 000000000000009b R11: ffff9f8586e2d4d0 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
FS: 0000000000000000(0000) GS:ffff9fc3fb400000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000000000000 CR3: 000000807d470001 CR4: 0000000000770ef0
PKRU: 55555554
Call Trace:
<TASK>
? __warn+0x88/0x180
? do_softirq_post_smp_call_flush+0x1a/0x40
? report_bug+0x18e/0x1a0
? handle_bug+0x42/0x70
? exc_invalid_op+0x18/0x70
? asm_exc_invalid_op+0x1a/0x20
? do_softirq_post_smp_call_flush+0x1a/0x40
? srso_alias_return_thunk+0x5/0xfbef5
flush_smp_call_function_queue+0x7a/0x90
do_idle+0x15f/0x270
cpu_startup_entry+0x29/0x30
start_secondary+0x12b/0x160
common_startup_64+0x13e/0x141
</TASK>
---[ end trace 0000000000000000 ]---which points to:
WARN_ON_ONCE(was_pending != local_softirq_pending())
Since MWAIT based idling on x86 sets the TIF_POLLING_NRFLAG, IPIs to an idle CPU are optimized out by commit b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()") and the logic instead relies on flush_smp_call_function_queue() in the idle exit path to execute the SMP-call-function. This previously went undetected since the sender of IPI sets the TIF_NEED_RESCHED bit which would have tripped the need_resched() check in nohz_csd_func() and prevented it from raising the SOFTIRQ.
Would it be okay to allow raising a SCHED_SOFTIRQ from flush_smp_call_function_queue() on PREEMPT_RT kernels? Something like:
kernel/softirq.c +11 -4
@@ -314,17 +314,24 @@ static inline void invoke_softirq(void) wakeup_softirqd(); } +#define SCHED_SOFTIRQ_MASK BIT(SCHED_SOFTIRQ) +/* * flush_smp_call_function_queue() can raise a soft interrupt in a function -* call. On RT kernels this is undesired and the only known functionality -* in the block layer which does this is disabled on RT. If soft interrupts -* get raised which haven't been raised before the flush, warn so it can be +* call. On RT kernels this is undesired and the only known functionalities +* are in the block layer which is disabled on RT, and in the scheduler for +* idle load balancing. If soft interrupts get raised which haven't been +* raised before the flush, warn if it is not a SCHED_SOFTIRQ so it can be * investigated. */ void do_softirq_post_smp_call_flush (unsigned int was_pending) { -if (WARN_ON_ONCE (was_pending !=local_softirq_pending ())) +unsigned int is_pending =local_softirq_pending (); + +if (unlikely (was_pending != is_pending)) { +WARN_ON_ONCE (was_pending != (is_pending & ~SCHED_SOFTIRQ_MASK ));invoke_softirq (); + } }#else /* CONFIG_PREEMPT_RT */
--
With the above diff, I do not see the splat I was seeing initially. If there are no strong objections, I can fold in the above diff in v2.
Signature · 2 lines
Thanks and Regards, Prateek
Quoted 19 lines
Suggested-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>--- kernel/sched/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)kernel/sched/core.c +1
-1@@ -1205,7 +1205,7 @@ static void nohz_csd_func(void *info)WARN_ON (!(flags &NOHZ_KICK_MASK )); rq->idle_balance =idle_cpu (cpu); -if (rq->idle_balance && !need_resched ()) { +if (rq->idle_balance) { rq->nohz_idle_balance = flags;raise_softirq_irqoff (SCHED_SOFTIRQ ); }
K Prateek Nayak
reviewerPATCH 2/3 sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
In reply to K Prateek NayakFrom: Peter Zijlstra <[email protected]>
Since commit b2a02fc43a1f ("smp: Optimize send_call_function_single_ipi()") an idle CPU in TIF_POLLING_NRFLAG mode can be pulled out of idle by setting TIF_NEED_RESCHED flag to service an IPI without actually sending an interrupt. Even in cases where the IPI handler does not queue a task on the idle CPU, do_idle() will call __schedule() since need_resched() returns true in these cases.
Introduce and use SM_IDLE to identify call to __schedule() from schedule_idle() and shorten the idle re-entry time by skipping pick_next_task() when nr_running is 0 and the previous task is the idle task.
With the SM_IDLE fast-path, the time taken to complete a fixed set of IPIs using ipistorm improves significantly. Following are the numbers from a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) running ipistorm between CPU8 and CPU16:
cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
==================================================================
Test : ipistorm (modified)
Units : Normalized runtime
Interpretation: Lower is better
Statistic : AMean
==================================================================
kernel: time [pct imp]
tip:sched/core 1.00 [baseline]
tip:sched/core + SM_IDLE 0.25 [75.11%]
[ kprateek: Commit log and testing ]
--- kernel/sched/core.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-)
kernel/sched/core.c +19 -19
@@ -6343,19 +6343,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a -* preemption from blocking on an 'sleeping' spin/rwlock. Note that -* SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to -* optimize the AND operation out and just check for zero. +* preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_NONE 0x0 -#define SM_PREEMPT 0x1 -#define SM_RTLOCK_WAIT 0x2 - -#ifndef CONFIG_PREEMPT_RT -# define SM_MASK_PREEMPT (~0U) -#else -# define SM_MASK_PREEMPT SM_PREEMPT -#endif +#define SM_IDLE (-1) +#define SM_NONE 0 +#define SM_PREEMPT 1 +#define SM_RTLOCK_WAIT 2/* * __schedule() is the main scheduler function.
@@ -6396,11 +6389,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static void __sched notrace __schedule(int sched_mode) {struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; +bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;
@@ -6409,13 +6403,13 @@ static void __sched notrace __schedule(unsigned int sched_mode) rq =cpu_rq (cpu); prev = rq->curr; -schedule_debug (prev, !!sched_mode); +schedule_debug (prev, preempt);if (sched_feat (HRTICK ) ||sched_feat (HRTICK_DL ))hrtick_clear (rq);local_irq_disable (); -rcu_note_context_switch (!!sched_mode); +rcu_note_context_switch (preempt);/* * Make sure that signal_pending_state()->signal_pending() below
@@ -6449,7 +6443,12 @@ static void __sched notrace __schedule(unsigned int sched_mode)* that we form a control dependency vs deactivate_task() below. */ prev_state =READ_ONCE (prev->__state); -if (!(sched_mode &SM_MASK_PREEMPT ) && prev_state) { +if (sched_mode ==SM_IDLE ) { +if (!rq->nr_running) { + next = prev; + goto picked; + } + }else if (!preempt && prev_state) {if (signal_pending_state (prev_state, prev)) {WRITE_ONCE (prev->__state,TASK_RUNNING ); }else {
@@ -6483,6 +6482,7 @@ static void __sched notrace __schedule(unsigned int sched_mode) } next =pick_next_task (rq, prev, &rf); +picked:clear_tsk_need_resched (prev);clear_preempt_need_resched ();#ifdef CONFIG_SCHED_DEBUG
@@ -6523,7 +6523,7 @@ static void __sched notrace __schedule(unsigned int sched_mode)migrate_disable_switch (rq, prev);psi_sched_switch (prev, next, !task_on_rq_queued (prev)); -trace_sched_switch (sched_mode &SM_MASK_PREEMPT , prev, next, prev_state); +trace_sched_switch (preempt, prev, next, prev_state);/* Also unlocks the rq: */ rq =context_switch (rq, prev, next, &rf);
@@ -6599,7 +6599,7 @@ static void sched_update_worker(struct task_struct *tsk) } } -static __always_inline void __schedule_loop(unsigned int sched_mode) +static __always_inline void __schedule_loop(int sched_mode) { do { preempt_disable();
@@ -6644,7 +6644,7 @@ void __sched schedule_idle(void)*/ WARN_ON_ONCE (current->__state);do { -__schedule (SM_NONE ); +__schedule (SM_IDLE ); }while (need_resched ()); }
Signature · 1 line
2.34.1
Vincent Guittot
maintainerRe: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Quoted 101 lines · K Prateek Nayak
From: Peter Zijlstra <[email protected]>
Since commit
b2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") an idle CPU inTIF_POLLING_NRFLAGmode can be pulled out of idle by settingTIF_NEED_RESCHEDflag to service an IPI without actually sending an interrupt. Even in cases where the IPI handler does not queue a task on the idle CPU,do_idle()will call__schedule()sinceneed_resched()returns true in these cases.Introduce and use
SM_IDLEto identify call to__schedule()fromschedule_idle()and shorten the idle re-entry time by skippingpick_next_task()whennr_runningis 0 and the previous task is the idle task.With the
SM_IDLEfast-path, the time taken to complete a fixed set of IPIs using ipistorm improves significantly. Following are the numbers from a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) running ipistorm between CPU8 and CPU16:cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
==================================================================
Test : ipistorm (modified)
Units : Normalized runtime
Interpretation: Lower is better
Statistic : AMean
==================================================================kernel: time [pct imp] tip:sched/core 1.00 [baseline] tip:sched/core + SM_IDLE 0.25 [75.11%][ kprateek: Commit log and testing ]
Not-yet-signed-off-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>--- kernel/sched/core.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-)kernel/sched/core.c +9
-15@@ -6343,19 +6343,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a -* preemption from blocking on an 'sleeping' spin/rwlock. Note that -* SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to -* optimize the AND operation out and just check for zero. +* preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_NONE 0x0 -#define SM_PREEMPT 0x1 -#define SM_RTLOCK_WAIT 0x2 - -#ifndef CONFIG_PREEMPT_RT -# define SM_MASK_PREEMPT (~0U) -#else -# define SM_MASK_PREEMPT SM_PREEMPT -#endif +#define SM_IDLE (-1) +#define SM_NONE 0 +#define SM_PREEMPT 1 +#define SM_RTLOCK_WAIT 2/* * __schedule() is the main scheduler function. @@ -6396,11 +6389,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static void __sched notrace __schedule(int sched_mode) {struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; +bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;@@ -6409,13 +6403,13 @@ static void __sched notrace __schedule(unsigned int sched_mode) rq =cpu_rq (cpu); prev = rq->curr; -schedule_debug (prev, !!sched_mode); +schedule_debug (prev, preempt);if (sched_feat (HRTICK ) ||sched_feat (HRTICK_DL ))hrtick_clear (rq);local_irq_disable (); -rcu_note_context_switch (!!sched_mode); +rcu_note_context_switch (preempt);/* * Make sure that signal_pending_state()->signal_pending() below
kernel/sched/core.c static void __sched notrace __schedule(unsigned int sched_mode) · line 6451
Quoted 10 lines
kernel/sched/core.c +6
-1@@ -6449,7 +6443,12 @@ static void __sched notrace __schedule(unsigned int sched_mode)* that we form a control dependency vs deactivate_task() below. */ prev_state =READ_ONCE (prev->__state); -if (!(sched_mode &SM_MASK_PREEMPT ) && prev_state) { +if (sched_mode ==SM_IDLE ) { +if (!rq->nr_running) { + next = prev; + goto picked; + } + }else if (!preempt && prev_state) {
With CONFIG_PREEMPT_RT, it was only for SM_PREEMPT but not for SM_RTLOCK_WAIT
Quoted 41 lines
kernel/sched/core.c +4
-4if (signal_pending_state (prev_state, prev)) {WRITE_ONCE (prev->__state,TASK_RUNNING ); }else {@@ -6483,6 +6482,7 @@ static void __sched notrace __schedule(unsigned int sched_mode) } next =pick_next_task (rq, prev, &rf); +picked:clear_tsk_need_resched (prev);clear_preempt_need_resched ();#ifdef CONFIG_SCHED_DEBUG @@ -6523,7 +6523,7 @@ static void __sched notrace __schedule(unsigned int sched_mode)migrate_disable_switch (rq, prev);psi_sched_switch (prev, next, !task_on_rq_queued (prev)); -trace_sched_switch (sched_mode &SM_MASK_PREEMPT , prev, next, prev_state); +trace_sched_switch (preempt, prev, next, prev_state);/* Also unlocks the rq: */ rq =context_switch (rq, prev, next, &rf);@@ -6599,7 +6599,7 @@ static void sched_update_worker(struct task_struct *tsk) } } -static __always_inline void __schedule_loop(unsigned int sched_mode) +static __always_inline void __schedule_loop(int sched_mode) { do { preempt_disable();@@ -6644,7 +6644,7 @@ void __sched schedule_idle(void)*/ WARN_ON_ONCE (current->__state);do { -__schedule (SM_NONE ); +__schedule (SM_IDLE ); }while (need_resched ()); } --2.34.1
Peter Zijlstra
maintainerRe: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Quoted 59 lines · Vincent Guittot
Quoted 57 lines · K Prateek Nayak
kernel/sched/core.c +9
-15@@ -6343,19 +6343,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a -* preemption from blocking on an 'sleeping' spin/rwlock. Note that -* SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to -* optimize the AND operation out and just check for zero. +* preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_NONE 0x0 -#define SM_PREEMPT 0x1 -#define SM_RTLOCK_WAIT 0x2 - -#ifndef CONFIG_PREEMPT_RT -# define SM_MASK_PREEMPT (~0U) -#else -# define SM_MASK_PREEMPT SM_PREEMPT -#endif +#define SM_IDLE (-1) +#define SM_NONE 0 +#define SM_PREEMPT 1 +#define SM_RTLOCK_WAIT 2/* * __schedule() is the main scheduler function. @@ -6396,11 +6389,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static void __sched notrace __schedule(int sched_mode) {struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; +bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;@@ -6409,13 +6403,13 @@ static void __sched notrace __schedule(unsigned int sched_mode) rq =cpu_rq (cpu); prev = rq->curr; -schedule_debug (prev, !!sched_mode); +schedule_debug (prev, preempt);if (sched_feat (HRTICK ) ||sched_feat (HRTICK_DL ))hrtick_clear (rq);local_irq_disable (); -rcu_note_context_switch (!!sched_mode); +rcu_note_context_switch (preempt);
Quoted 15 lines
kernel/sched/core.c static void __sched notrace __schedule(unsigned int sched_mode) · line 6451
Quoted 13 lines
kernel/sched/core.c +6
-1/* * Make sure that signal_pending_state()->signal_pending() below @@ -6449,7 +6443,12 @@ static void __sched notrace __schedule(unsigned int sched_mode)* that we form a control dependency vs deactivate_task() below. */ prev_state =READ_ONCE (prev->__state); -if (!(sched_mode &SM_MASK_PREEMPT ) && prev_state) { +if (sched_mode ==SM_IDLE ) { +if (!rq->nr_running) { + next = prev; + goto picked; + } + }else if (!preempt && prev_state) {With
CONFIG_PREEMPT_RT, it was only forSM_PREEMPTbut not forSM_RTLOCK_WAIT
Bah, yes. But then schedule_debug() and rcu_note_context_switch() have an argument that is called 'preempt' but is set for SM_RTLOCK_WAIT.
Now, I think the RCU think is actually correct here, it doesn't want to consider SM_RTLOCK_WAIT as a voluntary schedule point, because spinlocks don't either. But it is confusing as heck.
We can either write things like:
} else if (sched_mode != SM_PREEMPT && prev_state) {or do silly things like:
#define SM_IDLE (-16)
keep the SM_MASK_PREEMPT trickery and do:
} else if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {Not sure that is actually going to matter at this point though.
Vincent Guittot
maintainerRe: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Quoted 80 lines · Peter Zijlstra
Quoted 59 lines · Vincent Guittot
Quoted 57 lines · K Prateek Nayak
kernel/sched/core.c +9
-15@@ -6343,19 +6343,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a -* preemption from blocking on an 'sleeping' spin/rwlock. Note that -* SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to -* optimize the AND operation out and just check for zero. +* preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_NONE 0x0 -#define SM_PREEMPT 0x1 -#define SM_RTLOCK_WAIT 0x2 - -#ifndef CONFIG_PREEMPT_RT -# define SM_MASK_PREEMPT (~0U) -#else -# define SM_MASK_PREEMPT SM_PREEMPT -#endif +#define SM_IDLE (-1) +#define SM_NONE 0 +#define SM_PREEMPT 1 +#define SM_RTLOCK_WAIT 2/* * __schedule() is the main scheduler function. @@ -6396,11 +6389,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static void __sched notrace __schedule(int sched_mode) {struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; +bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;@@ -6409,13 +6403,13 @@ static void __sched notrace __schedule(unsigned int sched_mode) rq =cpu_rq (cpu); prev = rq->curr; -schedule_debug (prev, !!sched_mode); +schedule_debug (prev, preempt);if (sched_feat (HRTICK ) ||sched_feat (HRTICK_DL ))hrtick_clear (rq);local_irq_disable (); -rcu_note_context_switch (!!sched_mode); +rcu_note_context_switch (preempt);Quoted 15 lines
kernel/sched/core.c static void __sched notrace __schedule(unsigned int sched_mode) · line 6451
Quoted 13 lines
kernel/sched/core.c +6
-1/* * Make sure that signal_pending_state()->signal_pending() below @@ -6449,7 +6443,12 @@ static void __sched notrace __schedule(unsigned int sched_mode)* that we form a control dependency vs deactivate_task() below. */ prev_state =READ_ONCE (prev->__state); -if (!(sched_mode &SM_MASK_PREEMPT ) && prev_state) { +if (sched_mode ==SM_IDLE ) { +if (!rq->nr_running) { + next = prev; + goto picked; + } + }else if (!preempt && prev_state) {With
CONFIG_PREEMPT_RT, it was only forSM_PREEMPTbut not forSM_RTLOCK_WAITBah, yes. But then
schedule_debug()andrcu_note_context_switch()have an argument that is called 'preempt' but is set forSM_RTLOCK_WAIT.
Quoted 7 lines
Now, I think the RCU think is actually correct here, it doesn't want to consider
SM_RTLOCK_WAITas a voluntary schedule point, because spinlocks don't either. But it is confusing as heck.We can either write things like:
} else if (sched_mode != SM_PREEMPT && prev_state) {
this would work with something like below
#ifdef CONFIG_PREEMPT_RT
# define SM_RTLOCK_WAIT 2
#else
# define SM_RTLOCK_WAIT SM_PREEMPT
#endifQuoted 10 lines
or do silly things like:
#define
SM_IDLE(-16)keep the
SM_MASK_PREEMPTtrickery and do:} else if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {Not sure that is actually going to matter at this point though.
K Prateek Nayak
reviewerRe: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Hello Vincent, Peter,
Quoted 89 lines · Vincent Guittot
Quoted 80 lines · Peter Zijlstra
Quoted 59 lines · Vincent Guittot
Quoted 57 lines · K Prateek Nayak
kernel/sched/core.c +9
-15@@ -6343,19 +6343,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a -* preemption from blocking on an 'sleeping' spin/rwlock. Note that -* SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to -* optimize the AND operation out and just check for zero. +* preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_NONE 0x0 -#define SM_PREEMPT 0x1 -#define SM_RTLOCK_WAIT 0x2 - -#ifndef CONFIG_PREEMPT_RT -# define SM_MASK_PREEMPT (~0U) -#else -# define SM_MASK_PREEMPT SM_PREEMPT -#endif +#define SM_IDLE (-1) +#define SM_NONE 0 +#define SM_PREEMPT 1 +#define SM_RTLOCK_WAIT 2/* * __schedule() is the main scheduler function. @@ -6396,11 +6389,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* * WARNING: must be called with preemption disabled! */ -static void __sched notrace __schedule(unsigned int sched_mode) +static void __sched notrace __schedule(int sched_mode) {struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; +bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;@@ -6409,13 +6403,13 @@ static void __sched notrace __schedule(unsigned int sched_mode) rq =cpu_rq (cpu); prev = rq->curr; -schedule_debug (prev, !!sched_mode); +schedule_debug (prev, preempt);if (sched_feat (HRTICK ) ||sched_feat (HRTICK_DL ))hrtick_clear (rq);local_irq_disable (); -rcu_note_context_switch (!!sched_mode); +rcu_note_context_switch (preempt);Quoted 15 lines
kernel/sched/core.c static void __sched notrace __schedule(unsigned int sched_mode) · line 6451
Quoted 13 lines
kernel/sched/core.c +6
-1/* * Make sure that signal_pending_state()->signal_pending() below @@ -6449,7 +6443,12 @@ static void __sched notrace __schedule(unsigned int sched_mode)* that we form a control dependency vs deactivate_task() below. */ prev_state =READ_ONCE (prev->__state); -if (!(sched_mode &SM_MASK_PREEMPT ) && prev_state) { +if (sched_mode ==SM_IDLE ) { +if (!rq->nr_running) { + next = prev; + goto picked; + } + }else if (!preempt && prev_state) {With
CONFIG_PREEMPT_RT, it was only forSM_PREEMPTbut not forSM_RTLOCK_WAITBah, yes. But then
schedule_debug()andrcu_note_context_switch()have an argument that is called 'preempt' but is set forSM_RTLOCK_WAIT.Quoted 7 lines
Now, I think the RCU think is actually correct here, it doesn't want to consider
SM_RTLOCK_WAITas a voluntary schedule point, because spinlocks don't either. But it is confusing as heck.We can either write things like:
} else if (sched_mode != SM_PREEMPT && prev_state) {
Quoted 7 lines
this would work with something like below
#ifdef
CONFIG_PREEMPT_RT# define SM_RTLOCK_WAIT 2 #else # define SM_RTLOCK_WAIT SM_PREEMPT #endif
Since "SM_RTLOCK_WAIT" is only used by "schedule_rtlock()" which is only defined for PREEMPT_RT kernels (from a quick grep on linux-6.10.y-rt), it should just work (famous last words) and we can perhaps skip the else part too?
With this patch, we need to have the following view of what "preempt" should be for the components in __schedule() looking at "sched_mode":
schedule_debug()/ SM_MASK_PREEMPT check/
rcu_note_context_switch() trace_sched_switch()SM_IDLE F FSM_NONE F FSM_PREEMPT T TSM_RTLOCK_WAIT * T F
* SM_RTLOCK_WAIT is only used in PREEMPT_RT
Quoted 3 lines
Quoted 3 lines
or do silly things like:
... and since we are talking about silly ideas, here is one:
(only build tested on tip:sched/core and linux-6.10.y-rt)
kernel/sched/core.c +20 -5
@@ -6345,10 +6345,12 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)* The mode argument allows RT enabled kernels to differentiate a * preemption from blocking on an 'sleeping' spin/rwlock. */ -#define SM_IDLE (-1) -#define SM_NONE 0 -#define SM_PREEMPT 1 -#define SM_RTLOCK_WAIT 2 +#ifdef CONFIG_PREEMPT_RT +#define SM_RTLOCK_WAIT (-2) +#endif +#define SM_IDLE 0 +#define SM_NONE 1 +#define SM_PREEMPT 2/* * __schedule() is the main scheduler function.
@@ -6391,10 +6393,15 @@ pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)*/ static void __sched notrace __schedule(int sched_mode) { +/* +* For PREEMPT_RT kernel, SM_RTLOCK_WAIT is considered as +* preemption by schedule_debug() and +* rcu_note_context_switch(). +*/ +bool preempt = (unsigned int ) sched_mode >SM_NONE ;struct task_struct *prev, *next;unsigned long *switch_count;unsigned long prev_state; -bool preempt = sched_mode >0 ;struct rq_flags rf;struct rq *rq;int cpu;
@@ -6438,6 +6445,14 @@ static void __sched notrace __schedule(int sched_mode) switch_count = &prev->nivcsw; +#ifdef CONFIG_PREEMPT_RT +/* +* PREEMPT_RT kernel do not consider SM_RTLOCK_WAIT as +* preemption when looking at prev->state. +*/ + preempt = sched_mode >SM_NONE ; +#endif +/* * We must load prev->state once (task_struct::state is volatile), such * that we form a control dependency vs deactivate_task() below.
--
Quoted 8 lines
Quoted 8 lines
#define
SM_IDLE(-16)keep the
SM_MASK_PREEMPTtrickery and do:} else if (!(sched_mode & SM_MASK_PREEMPT) && prev_state) {Not sure that is actually going to matter at this point though.
Signature · 2 lines
Thanks and Regards, Prateek
Re: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
In reply to K Prateek NayakQuoted 31 lines · K Prateek Nayak
From: Peter Zijlstra <[email protected]>
Since commit
b2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") an idle CPU inTIF_POLLING_NRFLAGmode can be pulled out of idle by settingTIF_NEED_RESCHEDflag to service an IPI without actually sending an interrupt. Even in cases where the IPI handler does not queue a task on the idle CPU,do_idle()will call__schedule()sinceneed_resched()returns true in these cases.Introduce and use
SM_IDLEto identify call to__schedule()fromschedule_idle()and shorten the idle re-entry time by skippingpick_next_task()whennr_runningis 0 and the previous task is the idle task.With the
SM_IDLEfast-path, the time taken to complete a fixed set of IPIs using ipistorm improves significantly. Following are the numbers from a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) running ipistorm between CPU8 and CPU16:cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
================================================================== Test : ipistorm (modified) Units : Normalized runtime Interpretation: Lower is better Statistic : AMean ================================================================== kernel: time [pct imp] tip:sched/core 1.00 [baseline] tip:sched/core + SM_IDLE 0.25 [75.11%]
Quoted 6 lines
[ kprateek: Commit log and testing ]
Not-yet-signed-off-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>
Only with current patch applied on top of sched/core commit c793a62823d1, a significant throughput/run-to-run variance improvement is observed on an Intel 240 CPUs/ 2 Nodes server. C-states >= C1E are disabled, CPU frequency governor is set to performance and turbo-boost disabled.
Without the patch(lower the better):
158490995
113086433
737869191
302454894
731262790
677283357
729767478
830949261
399824606
743681976
(Amean): 542467098
(Std): 257011706
With the patch(lower the better):
128060992
115646768
132734621
150330954
113143538
169875051
145010400
151589193
162165800
159963320
(Amean): 142852063
(Std): 18646313
I've launched full tests for schbench/hackbench/netperf/tbench to see if there is any difference.
thanks,
Chenyu
Re: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Quoted 73 lines · Chen Yu
Quoted 31 lines · K Prateek Nayak
From: Peter Zijlstra <[email protected]>
Since commit
b2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") an idle CPU inTIF_POLLING_NRFLAGmode can be pulled out of idle by settingTIF_NEED_RESCHEDflag to service an IPI without actually sending an interrupt. Even in cases where the IPI handler does not queue a task on the idle CPU,do_idle()will call__schedule()sinceneed_resched()returns true in these cases.Introduce and use
SM_IDLEto identify call to__schedule()fromschedule_idle()and shorten the idle re-entry time by skippingpick_next_task()whennr_runningis 0 and the previous task is the idle task.With the
SM_IDLEfast-path, the time taken to complete a fixed set of IPIs using ipistorm improves significantly. Following are the numbers from a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) running ipistorm between CPU8 and CPU16:cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
================================================================== Test : ipistorm (modified) Units : Normalized runtime Interpretation: Lower is better Statistic : AMean ================================================================== kernel: time [pct imp] tip:sched/core 1.00 [baseline] tip:sched/core + SM_IDLE 0.25 [75.11%]Quoted 6 lines
[ kprateek: Commit log and testing ]
Not-yet-signed-off-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>Only with current patch applied on top of sched/core commit
c793a62823d1, a significant throughput/run-to-run variance improvement is observed on an Intel 240 CPUs/ 2 Nodes server. C-states >= C1E are disabled, CPU frequency governor is set to performance and turbo-boost disabled.Without the patch(lower the better):
158490995
113086433
737869191
302454894
731262790
677283357
729767478
830949261
399824606
743681976(Amean): 542467098
(Std): 257011706With the patch(lower the better):
128060992
115646768
132734621
150330954
113143538
169875051
145010400
151589193
162165800
159963320
Quoted 6 lines
(Amean): 142852063
(Std): 18646313I've launched full tests for schbench/hackbench/netperf/tbench to see if there is any difference.
Tested without CONFIG_PREEMPT_RT, so issue for SM_RTLOCK_WAIT as mentioned by Vincent might not bring any impact. There is no obvious difference (regression) detected according to the test in the 0day environment. Overall this patch looks good to me. Once you send a refresh version out I'll re-launch the test.
Tested on Xeon server with 128 CPUs, 4 Numa nodes, under different
baseline with-SM_IDLE
hackbench
load level (25% ~ 100%)
hackbench-pipe-process.throughput
%25:
846099 -0.3% 843217
%50:
972015 +0.0% 972185%100:
1395650 -1.3% 1376963
hackbench-pipe-threads.throughput
%25:
746629 -0.0% 746345
%50:
885165 -0.4% 881602%100:
1227790 +1.3% 1243757
hackbench-socket-process.throughput
%25:
395784 +1.2% 400717
%50:
441312 +0.3% 442783
%100:
324283 ± 2% +6.0% 343826hackbench-socket-threads.throughput
%25:
379700 -0.8% 376642
%50:
425315 -0.4% 423749
%100:
311937 ± 2% +0.9% 314892
baseline with-SM_IDLEschbench.request_latency_90%_us
1-mthread-1-worker:
4562 -0.0% 4560
1-mthread-16-workers:
4564 -0.0% 4563
12.5%-mthread-1:
4565 +0.0% 4567
12.5%-mthread-16-workers:
39204 +0.1% 39248
25%-mthread-1-worker:
4574 +0.0% 4574
25%-mthread-16-workers:
161944 +0.1% 162053
50%-mthread-1-workers:
4784 ± 5% +0.1% 4789 ± 5%
50%-mthread-16-workers:
659156 +0.4% 661679
100%-mthread-1-workers:
9328 +0.0% 9329100%-mthread-16-workers:
2489753 -0.7% 2472140
baseline with-SM_IDLE
netperf.Throughput:
25%-TCP_RR:
2449875 +0.0% 2450622 netperf.Throughput_total_tps
25%-UDP_RR:
2746806 +0.1% 2748935 netperf.Throughput_total_tps
25%-TCP_STREAM:
1352061 +0.7% 1361497 netperf.Throughput_total_Mbps
25%-UDP_STREAM:
1815205 +0.1% 1816202 netperf.Throughput_total_Mbps
50%-TCP_RR:
3981514 -0.3% 3970327 netperf.Throughput_total_tps
50%-UDP_RR:
4496584 -1.3% 4438363 netperf.Throughput_total_tps
50%-TCP_STREAM:
1478872 +0.4% 1484196 netperf.Throughput_total_Mbps
50%-UDP_STREAM:
1739540 +0.3% 1744074 netperf.Throughput_total_Mbps
75%-TCP_RR:
3696607 -0.5% 3677044 netperf.Throughput_total_tps
75%-UDP_RR:
4161206 +1.3% 4217274 ± 2% netperf.Throughput_total_tps
75%-TCP_STREAM:
895874 +5.7% 946546 ± 5% netperf.Throughput_total_Mbps
75%-UDP_STREAM:
4100019 -0.3% 4088367 netperf.Throughput_total_Mbps
100%-TCP_RR:
6724456 -1.7% 6610976 netperf.Throughput_total_tps
100%-UDP_RR:
7329959 -0.5% 7294653 netperf.Throughput_total_tps
100%-TCP_STREAM:
808165 +0.3% 810360 netperf.Throughput_total_Mbps
100%-UDP_STREAM:
5562651 +0.0% 5564106 netperf.Throughput_total_Mbps
thanks,
Chenyu
K Prateek Nayak
reviewerRe: [PATCH 2/3] sched/core: Introduce SM_IDLE and an idle re-entry fast-path in __schedule()
Hello Chenyu,
Thank you for testing the series. I'll have a second version out soon.
Quoted 81 lines · Chen Yu
Quoted 73 lines · Chen Yu
Quoted 31 lines · K Prateek Nayak
From: Peter Zijlstra <[email protected]>
Since commit
b2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()") an idle CPU inTIF_POLLING_NRFLAGmode can be pulled out of idle by settingTIF_NEED_RESCHEDflag to service an IPI without actually sending an interrupt. Even in cases where the IPI handler does not queue a task on the idle CPU,do_idle()will call__schedule()sinceneed_resched()returns true in these cases.Introduce and use
SM_IDLEto identify call to__schedule()fromschedule_idle()and shorten the idle re-entry time by skippingpick_next_task()whennr_runningis 0 and the previous task is the idle task.With the
SM_IDLEfast-path, the time taken to complete a fixed set of IPIs using ipistorm improves significantly. Following are the numbers from a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) running ipistorm between CPU8 and CPU16:cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
================================================================== Test : ipistorm (modified) Units : Normalized runtime Interpretation: Lower is better Statistic : AMean ================================================================== kernel: time [pct imp] tip:sched/core 1.00 [baseline] tip:sched/core + SM_IDLE 0.25 [75.11%]Quoted 6 lines
[ kprateek: Commit log and testing ]
Not-yet-signed-off-by Peter Zijlstra <[email protected]>Signed-off-by K Prateek Nayak <[email protected]>Only with current patch applied on top of sched/core commit
c793a62823d1, a significant throughput/run-to-run variance improvement is observed on an Intel 240 CPUs/ 2 Nodes server. C-states >= C1E are disabled, CPU frequency governor is set to performance and turbo-boost disabled.Without the patch(lower the better):
158490995
113086433
737869191
302454894
731262790
677283357
729767478
830949261
399824606
743681976(Amean): 542467098
(Std): 257011706With the patch(lower the better):
128060992
115646768
132734621
150330954
113143538
169875051
145010400
151589193
162165800
159963320Quoted 6 lines
(Amean): 142852063
(Std): 18646313I've launched full tests for schbench/hackbench/netperf/tbench to see if there is any difference.
Quoted 5 lines
Tested without
CONFIG_PREEMPT_RT, so issue forSM_RTLOCK_WAITas mentioned by Vincent might not bring any impact. There is no obvious difference (regression) detected according to the test in the 0day environment. Overall this patch looks good to me. Once you send a refresh version out I'll re-launch the test.
Since SM_RTLOCK_WAIT is only used by schedule_rtlock(), which is only defined for PREEMPT_RT kernels, non RT build should have no issue. I could spot at least one case in rtlock_slowlock_locked() where the pre->__state is set to "TASK_RTLOCK_WAIT" and schedule_rtlock() is called. With this patch, it would pass the "sched_mode > SM_NONE" check and call it an involuntary context-switch but on tip, (preempt & SM_MASK_PREEMPT) would return false and eventually it'll call deactivate_task() to dequeue the waiting task so this does need fixing.
From a brief look, all calls to schedule with "SM_RTLOCK_WAIT" already set the task->__state to a non-zero value. I'll look into this further after the respin and see if there is some optimization possible there but for the time being, I'll respin this with the condition changed to:
...
} else if (preempt != SM_PREEMPT && prev_state) {
...just to keep it explicit.
Thank you again for testing this version.
Signature · 2 lines
Thanks and Regards, Prateek
Quoted 107 lines
Tested on Xeon server with 128 CPUs, 4 Numa nodes, under different
baseline with-SM_IDLE
hackbench
load level (25% ~ 100%)hackbench-pipe-process.throughput
%25:846099 -0.3% 843217 %50: 972015 +0.0% 972185 %100: 1395650 -1.3% 1376963hackbench-pipe-threads.throughput
%25:746629 -0.0% 746345 %50: 885165 -0.4% 881602 %100: 1227790 +1.3% 1243757hackbench-socket-process.throughput
%25:395784 +1.2% 400717 %50: 441312 +0.3% 442783 %100: 324283 ± 2% +6.0% 343826hackbench-socket-threads.throughput
%25:379700 -0.8% 376642 %50: 425315 -0.4% 423749 %100: 311937 ± 2% +0.9% 314892 baseline with-SM_IDLEschbench.request_latency_90%_us
1-mthread-1-worker:
4562 -0.0% 4560 1-mthread-16-workers: 4564 -0.0% 4563 12.5%-mthread-1: 4565 +0.0% 4567 12.5%-mthread-16-workers: 39204 +0.1% 39248 25%-mthread-1-worker: 4574 +0.0% 4574 25%-mthread-16-workers: 161944 +0.1% 162053 50%-mthread-1-workers: 4784 ± 5% +0.1% 4789 ± 5% 50%-mthread-16-workers: 659156 +0.4% 661679 100%-mthread-1-workers: 9328 +0.0% 9329 100%-mthread-16-workers: 2489753 -0.7% 2472140 baseline with-SM_IDLEnetperf.Throughput:
25%-TCP_RR:
2449875 +0.0% 2450622 netperf.Throughput_total_tps 25%-UDP_RR: 2746806 +0.1% 2748935 netperf.Throughput_total_tps 25%-TCP_STREAM: 1352061 +0.7% 1361497 netperf.Throughput_total_Mbps 25%-UDP_STREAM: 1815205 +0.1% 1816202 netperf.Throughput_total_Mbps 50%-TCP_RR: 3981514 -0.3% 3970327 netperf.Throughput_total_tps 50%-UDP_RR: 4496584 -1.3% 4438363 netperf.Throughput_total_tps 50%-TCP_STREAM: 1478872 +0.4% 1484196 netperf.Throughput_total_Mbps 50%-UDP_STREAM: 1739540 +0.3% 1744074 netperf.Throughput_total_Mbps 75%-TCP_RR: 3696607 -0.5% 3677044 netperf.Throughput_total_tps 75%-UDP_RR: 4161206 +1.3% 4217274 ± 2% netperf.Throughput_total_tps 75%-TCP_STREAM: 895874 +5.7% 946546 ± 5% netperf.Throughput_total_Mbps 75%-UDP_STREAM: 4100019 -0.3% 4088367 netperf.Throughput_total_Mbps 100%-TCP_RR: 6724456 -1.7% 6610976 netperf.Throughput_total_tps 100%-UDP_RR: 7329959 -0.5% 7294653 netperf.Throughput_total_tps 100%-TCP_STREAM: 808165 +0.3% 810360 netperf.Throughput_total_Mbps 100%-UDP_STREAM: 5562651 +0.0% 5564106 netperf.Throughput_total_Mbpsthanks,
Chenyu
K Prateek Nayak
reviewerRFC PATCH 3/3 softirq: Avoid waking up ksoftirqd from flush_smp_call_function_queue()
In reply to K Prateek NayakSince commit b2a02fc43a1f4 ("smp: Optimize send_call_function_single_ipi()"), sending an actual interrupt to an idle CPU in TIF_POLLING_NRFLAG mode can be avoided by queuing the SMP call function on the call function queue of the CPU and setting the TIF_NEED_RESCHED bit in idle task's thread info. The call function is handled in the idle exit path when do_idle() calls flush_smp_call_function_queue().
However, since flush_smp_call_function_queue() is executed in idle thread's context, in_interrupt() check within a call function will return false. raise_softirq() uses this check to decide whether to wake ksoftirqd, since, a softirq raised from an interrupt context will be handled at irq exit. In all other cases, raise_softirq() wakes up ksoftirqd to handle the softirq on !PREEMPT_RT kernel.
Since flush_smp_call_function_queue() calls do_softirq_post_smp_call_flush(), waking up ksoftirqd is not necessary since the softirqs raised by the call functions will be handled soon after the call function queue is flushed. Mark __flush_smp_call_function_queue() within flush_smp_call_function_queue() with "will_do_softirq_post_flush" and use "do_softirq_pending()" to notify raise_softirq() an impending call to do_softirq() and avoid waking up ksoftirqd.
Adding a trace_printk() in nohz_csd_func() at the spot of raising SCHED_SOFTIRQ and enabling trace events for sched_switch, sched_wakeup, and softirq_entry (for SCHED_SOFTIRQ vector alone) helps observing the current behavior:
<idle>-0 [000] dN.1. nohz_csd_func: Raise SCHED_SOFTIRQ for idle balance
<idle>-0 [000] dN.4. sched_wakeup: comm=ksoftirqd/0 pid=16 prio=120 target_cpu=000
<idle>-0 [000] .Ns1. softirq_entry: vec=7 [action=SCHED]
<idle>-0 [000] d..2. sched_switch: prev_comm=swapper/0 ==> next_comm=ksoftirqd/0
ksoftirqd/0-16 [000] d..2. sched_switch: prev_comm=ksoftirqd/0 ==> next_comm=swapper/0ksoftirqd is woken up before the idle thread calls do_softirq_post_smp_call_flush() which can make the runqueue appear busy and prevent the idle load balancer from pulling task from an overloaded runqueue towards itself[1]. Following are the observations with the changes when enabling the same set of events:
<idle>-0 [000] dN.1. 106.134226: nohz_csd_func: Raise SCHED_SOFTIRQ for idle balance <idle>-0 [000] .Ns1. 106.134227: softirq_entry: vec=7 [action=SCHED] ...
No unnecessary ksoftirqd wakeups are seen from idle task's context to service the softirq. When doing performance testing, it was noticed that per-CPU "will_do_softirq_post_flush" variable needs to be defined as cacheline aligned to minimize performance overheads of the writes in flush_smp_call_function_queue(). Following is the IPI throughput measured using a modified version of ipistorm that performs a fixed set of IPIs between two CPUs on a dual socket 3rd Generation EPYC system (2 x 64C/128T) (boost on, C2 disabled) by running ipistorm between CPU8 and CPU16:
cmdline: insmod ipistorm.ko numipi=100000 single=1 offset=8 cpulist=8 wait=1
==================================================================
Test : ipistorm (modified)
Units : Normalized runtime
Interpretation: Lower is better
Statistic : AMean
==================================================================
kernel: time [pct imp]
tip:sched/core 1.00 [baseline]
tip:sched/core + SM_IDLE 0.25 [75.11%]
tip:sched/core + SM_IDLE + unaligned var 0.47 [53.74%] *
tip:sched/core + SM_IDLE + aligned var 0.25 [75.04%]
* The version where "will_do_softirq_post_flush" was not cacheline aligned takes twice as long as the cacheline aligned version to perform a fixed set of IPIs.
--- kernel/sched/smp.h | 2 ++ kernel/smp.c | 32 ++++++++++++++++++++++++++++++++ kernel/softirq.c | 10 +++++++++- 3 files changed, 43 insertions(+), 1 deletion(-)
kernel/sched/smp.h +2 -0
@@ -9,7 +9,9 @@ extern void sched_ttwu_pending(void *arg);extern bool call_function_single_prep_ipi (int cpu);#ifdef CONFIG_SMP +extern bool do_softirq_pending (void );extern void flush_smp_call_function_queue (void );#else +static inline bool do_softirq_pending (void ) {return false; }static inline void flush_smp_call_function_queue (void ) { }#endif
kernel/smp.c +32 -0
@@ -559,6 +559,36 @@ static void __flush_smp_call_function_queue(bool warn_cpu_offline) } } +/* Indicate an impending call to do_softirq_post_smp_call_flush() */ +static DEFINE_PER_CPU_ALIGNED(bool, will_do_softirq_post_flush); + +static __always_inline void __set_will_do_softirq_post_flush(void) +{ +this_cpu_write (will_do_softirq_post_flush, true); +} + +static __always_inline void __clr_will_do_softirq_post_flush(void) +{ +this_cpu_write (will_do_softirq_post_flush, false); +} + +/** +* do_softirq_pending - Check if do_softirq_post_smp_call_flush() will +* be called after the invocation of +* __flush_smp_call_function_queue() +* +* When flush_smp_call_function_queue() executes in the context of idle, +* migration thread, a softirq raised from the smp-call-function ends up +* waking ksoftirqd despite an impending softirq processing via +* do_softirq_post_smp_call_flush(). +* +* Indicate an impending do_softirq() to should_wake_ksoftirqd() despite +* not being in an interrupt context. +*/ +__always_inline bool do_softirq_pending(void) +{ +return this_cpu_read (will_do_softirq_post_flush); +}/** * flush_smp_call_function_queue - Flush pending smp-call-function callbacks
@@ -583,7 +613,9 @@ void flush_smp_call_function_queue(void)local_irq_save (flags);/* Get the already pending soft interrupts for RT enabled kernels */ was_pending =local_softirq_pending (); +__set_will_do_softirq_post_flush ();__flush_smp_call_function_queue (true); +__clr_will_do_softirq_post_flush ();if (local_softirq_pending ())do_softirq_post_smp_call_flush (was_pending);
kernel/softirq.c +9 -1
@@ -34,6 +34,8 @@#define CREATE_TRACE_POINTS #include <trace/events/irq.h> +#include "sched/smp.h" +/* - No shared variables, all the data are CPU local. - If a softirq needs serialization, let it serialize itself
@@ -413,7 +415,13 @@ static inline void ksoftirqd_run_end(void)static inline bool should_wake_ksoftirqd (void ) { -return true; +/* +* Avoid waking up ksoftirqd when a softirq is raised from a +* call-function executed by flush_smp_call_function_queue() +* in idle, migration thread's context since it'll soon call +* do_softirq_post_smp_call_flush(). +*/ +return !do_softirq_pending (); }static inline void invoke_softirq (void )
Signature · 1 line
2.34.1
Peter Zijlstra
maintainerRe: [RFC PATCH 3/3] softirq: Avoid waking up ksoftirqd from flush_smp_call_function_queue()
Quoted 81 lines · K Prateek Nayak
kernel/sched/smp.h +2
-0@@ -9,7 +9,9 @@ extern void sched_ttwu_pending(void *arg);extern bool call_function_single_prep_ipi (int cpu);#ifdef CONFIG_SMP +extern bool do_softirq_pending (void );extern void flush_smp_call_function_queue (void );#else +static inline bool do_softirq_pending (void ) {return false; }static inline void flush_smp_call_function_queue (void ) { }#endif kernel/smp.c +32
-0@@ -559,6 +559,36 @@ static void __flush_smp_call_function_queue(bool warn_cpu_offline) } } +/* Indicate an impending call to do_softirq_post_smp_call_flush() */ +static DEFINE_PER_CPU_ALIGNED(bool, will_do_softirq_post_flush); + +static __always_inline void __set_will_do_softirq_post_flush(void) +{ +this_cpu_write (will_do_softirq_post_flush, true); +} + +static __always_inline void __clr_will_do_softirq_post_flush(void) +{ +this_cpu_write (will_do_softirq_post_flush, false); +} + +/** +* do_softirq_pending - Check if do_softirq_post_smp_call_flush() will +* be called after the invocation of +* __flush_smp_call_function_queue() +* +* When flush_smp_call_function_queue() executes in the context of idle, +* migration thread, a softirq raised from the smp-call-function ends up +* waking ksoftirqd despite an impending softirq processing via +* do_softirq_post_smp_call_flush(). +* +* Indicate an impending do_softirq() to should_wake_ksoftirqd() despite +* not being in an interrupt context. +*/ +__always_inline bool do_softirq_pending(void) +{ +return this_cpu_read (will_do_softirq_post_flush); +}/** * flush_smp_call_function_queue - Flush pending smp-call-function callbacks @@ -583,7 +613,9 @@ void flush_smp_call_function_queue(void)local_irq_save (flags);/* Get the already pending soft interrupts for RT enabled kernels */ was_pending =local_softirq_pending (); +__set_will_do_softirq_post_flush ();__flush_smp_call_function_queue (true); +__clr_will_do_softirq_post_flush ();if (local_softirq_pending ())do_softirq_post_smp_call_flush (was_pending);kernel/softirq.c +2
-0@@ -34,6 +34,8 @@#define CREATE_TRACE_POINTS #include <trace/events/irq.h> +#include "sched/smp.h" +/* - No shared variables, all the data are CPU local. - If a softirq needs serialization, let it serialize itself @@ -413,7 +415,13 @@ static inline void ksoftirqd_run_end(void)static inline bool should_wake_ksoftirqd (void )
kernel/softirq.c static inline void ksoftirqd_run_end(void) · line 425
Quoted 10 lines
kernel/softirq.c +7
-1{ -return true; +/* +* Avoid waking up ksoftirqd when a softirq is raised from a +* call-function executed by flush_smp_call_function_queue() +* in idle, migration thread's context since it'll soon call +* do_softirq_post_smp_call_flush(). +*/ +return !do_softirq_pending (); }
On first reading I wonder why you've not re-used and hooked into the PREEMPT_RT variant of should_wake_ksoftirqd(). That already has a per CPU variable to do exactly this.
K Prateek Nayak
reviewerRe: [RFC PATCH 3/3] softirq: Avoid waking up ksoftirqd from flush_smp_call_function_queue()
Hello Peter,
Thank you for the feedback.
Quoted 7 lines · Peter Zijlstra
Quoted 1 line · K Prateek Nayak
[..snip..]
On first reading I wonder why you've not re-used and hooked into the
PREEMPT_RTvariant ofshould_wake_ksoftirqd(). That already has a per CPU variable to do exactly this.
With this RFC, I intended to check if everyone was onboard with the idea and of the use-case. One caveat with re-using the existing "softirq_ctrl.cnt" hook that PREEMPT_RT uses is that we'll need to expose the functions that increment and decrement it, for it to be used in kernel/smp.c. I'll make those changes in v2 and we can see if there are sufficient WARN_ON() to catch any incorrect usage in !PREEMPT_RT case.
Signature · 2 lines
Thanks and Regards, Prateek
K Prateek Nayak
reviewerRe: [RFC PATCH 3/3] softirq: Avoid waking up ksoftirqd from flush_smp_call_function_queue()
Hello Peter,
Quoted 13 lines · K Prateek Nayak
Hello Peter,
Thank you for the feedback.
Quoted 7 lines · Peter Zijlstra
Quoted 1 line · K Prateek Nayak
[..snip..]
On first reading I wonder why you've not re-used and hooked into the
PREEMPT_RTvariant ofshould_wake_ksoftirqd(). That already has a per CPU variable to do exactly this.
Quoted 8 lines
With this RFC, I intended to check if everyone was onboard with the idea and of the use-case. One caveat with re-using the existing "softirq_ctrl.cnt" hook that
PREEMPT_RTuses is that we'll need to expose the functions that increment and decrement it, for it to be used inkernel/smp.c. I'll make those changes in v2 and we can see if there are sufficientWARN_ON()to catch any incorrect usage in !PREEMPT_RT case.
Reusing the PREEMPT_RT bits, I was able to come up with the approach below. Following are some nuances with this approach:
- Although I don't believe "set_do_softirq_pending()" can be nested, since it is used only from flush_smp_call_function_queue() which is called with IRQs disabled, I'm still using inc and dec since I'm not sure if it can be nested in a local_bh_{disable,enable}() or if those can be called from SMP-call-function.
- I used the same modified version of ipistorm to test the changes on top of v6.10-rc6-rt11 with LOCKDEP enabled and did not see any splats during the run of the benchmark. If there are better tests that stress this part on RT kernels, I'm all ears.
- I've abandoned any micro-optimization since I see different numbers on different machines and am sticking to the simplest approach since it works and is an improvement over the baseline.
I'll leave the diff below:
kernel/sched/smp.h +9 -0
@@ -9,7 +9,16 @@ extern void sched_ttwu_pending(void *arg);extern bool call_function_single_prep_ipi (int cpu);#ifdef CONFIG_SMP +/* +* Used to indicate a pending call to do_softirq() from +* flush_smp_call_function_queue() +*/ +extern void set_do_softirq_pending (void ); +extern void clr_do_softirq_pending (void ); +extern void flush_smp_call_function_queue (void );#else +static inline void set_do_softirq_pending (void ) { } +static inline void clr_do_softirq_pending (void ) { }static inline void flush_smp_call_function_queue (void ) { }#endif
kernel/smp.c +2 -0
@@ -583,7 +583,9 @@ void flush_smp_call_function_queue(void)local_irq_save (flags);/* Get the already pending soft interrupts for RT enabled kernels */ was_pending =local_softirq_pending (); +set_do_softirq_pending ();__flush_smp_call_function_queue (true); +clr_do_softirq_pending ();if (local_softirq_pending ())do_softirq_post_smp_call_flush (was_pending);
kernel/softirq.c +49 -33
158 lines not on this page · raw message
--
Some of the (softirq_ctrl.cnt & SOFTIRQ_MASK) masking might be unnecessary but I'm not familiar enough with all these bits to make a sound call. Any and all comments are appreciated :)
--
Thanks and Regards,
Prateek
Hi Prateek,
Quoted 45 lines · K Prateek Nayak
Since commit
b2a02fc43a1f("smp: Optimizesend_call_function_single_ipi()"), an idle CPU inTIF_POLLING_NRFLAGcan be pulled out of idle by settingTIF_NEED_RESCHEDinstead of sending an actual IPI. This affects at least three scenarios that have been described below:o A
need_resched()check within a call function does not necessarily indicate a task wakeup since a CPU intending to send an IPI to an idle target inTIF_POLLING_NRFLAGmode can simply queue the SMP-call-function and set theTIF_NEED_RESCHEDflag to pull the polling target out of idle. The SMP-call-function will be executed byflush_smp_call_function_queue()on the idle-exit path. On x86, wheremwait_idle_with_hints()setsTIF_POLLING_NRFLAGfor long idling, this leads to idle load balancer bailing out early sinceneed_resched()check innohz_csd_func()returns true in most instances.o A
TIF_POLLING_NRFLAGidling CPU woken up to process an IPI will end up callingschedule()even in cases where the call function does not wake up a new task on the idle CPU, thus delaying the idle re-entry.o Julia Lawall reported a case where a softirq raised from a SMP-call-function on an idle CPU will wake up ksoftirqd since
flush_smp_call_function_queue()executes in the idle thread's context. This can throw off the idle load balancer by making the idle CPU appear busy since ksoftirqd just woke on the said CPU [1].The three patches address each of the above issue individually, the first one by removing the
need_resched()check innohz_csd_func()with a proper justification, the second by introducing a fast-path in__schedule()to speed up idle re-entry in caseTIF_NEED_RESCHEDwas set simply to process an IPI that did not perform a wakeup, and the third by notifyingraise_softirq()that the softirq was raised from a SMP-call-function executed by the idle or migration thread inflush_smp_call_function_queue(), and waking ksoftirqd is unnecessary since a call todo_softirq_post_smp_call_flush()will follow soon.Previous attempts to solve these problems involved introducing a new
TIF_NOTIFY_IPIflag to notify aTIF_POLLING_NRFLAGCPU of a pending IPI and skip calling__schedule()in such cases but it involved using atomic ops which could have performance implications [2]. Instead, Peter suggested the approach outlined in the first two patches of the series. The third one is an RFC to that (hopefully) solves the problem Julia was chasing down related to idle load balancing.
Quoted 6 lines
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/This patch is based on tip:sched/core at commit
c793a62823d1("sched/core: Drop spinlocks on contention iff kernel is preemptible")
As discussed in another thread[1], I did a simple test to stress the newidle balance with this patch applied, to see if there is any impact on newidle balance cost.
This synthetic test script(shown below) launches NR_CPU process (on my platform it is 240). Each process is a loop of nanosleep(1 us), which is supposed to trigger newidle balance as much as possible.
Before the 3 patches are applied, on commit c793a62823d1:
3.67% 0.33% [kernel.kallsyms] [k] sched_balance_newidle 2.85% 2.16% [kernel.kallsyms] [k] update_sd_lb_stats.constprop.0
After 3 patches are applied:
3.51% 0.32% [kernel.kallsyms] [k] sched_balance_newidle 2.71% 2.06% [kernel.kallsyms] [k] update_sd_lb_stats.constprop.0
It seems that there is no much difference regarding the precent of newidle balance. My understanding is that, the current patch set mainly deals with the false positive of need_resched() caused by IPI, thus avoid newidle balance if it is IPI. In the synthetic test, it is always a real wakeup, so it does not cause much difference. I think ipi intensive workload would benefit most from this change, so I'm planning to use ipistorm to have a double check.
According to the scenario of this synthetic test, it seems that there is no need to launch the newidle balance, because the sleeping task will be woken up soon, there is no need to pull another task to it. Besides, the calculating statistics is not linealy scalable and remains the bottleneck of newly idle balance. I'm thinking of doing some evaluation based on your fix.
The test code:
i=1;while [ $i -le "240" ]; do ./nano_sleep 1000 & i=$(($i+1)); done;
int main(int argc, char **argv)
{
int response, sleep_ns;
struct timespec remaining, request = { 0, 100 };
if (argc != 2) {
printf("please specify the sleep nanosleep\n");
return -1;
}
sleep_ns = atoi(argv[1]);
while (1) {
request.tv_sec = 0;
request.tv_nsec = sleep_ns;
response = nanosleep(&request, &remaining);
}
return 0;
}[1] https://lore.kernel.org/lkml/[email protected]/
thanks,
Chenyu