Allow preemption during IPI completion waiting to improve real-time performance
Subsystems (6)
v5 cover Allow preemption during IPI completion waiting to improve real-time performance
Changes in v5:
- Replace "smp: Remove get_cpu from smp_call_function_any" with a new approach that extracts a common __smp_call_function_single() to safely keep the remote CPU selection and IPI dispatch process within a single preemption-disabled region in [PATCH v5 3/12].
- Fix a typo in comments (s/cpumask_stack/task_mask/) and remove the obsolete "Preemption must be disabled" constraint from the kernel-doc in [PATCH v5 6/12].
- Adjust the WARN_ON_ONCE() validation condition to avoid a false positive warning caused by CPU hotplug races when use_cpus_read_lock is false in [PATCH v5 9/12].
- Move the preemptible() check in smp_call_function_many_cond() from [PATCH v5 4/12] to [PATCH v5 6/12].
- Rebase to commit 4ac4d6549a65 ("sched: Use trace_call__<tp>() to save a static branch").
Changes in v4:
- Use task-local IPI cpumask rather than on-stack cpumask in [PATCH v4 4/12] (suggested by sebastian).
- Skip to free csd memory in smpcfd_dead_cpu() to guarantee csd memory access safety, instead of using RCU mechanism in [PATCH v4 5/12] (suggested by sebastian).
- Align flush_tlb_info with SMP_CACHE_BYTES to avoid performance degradation caused by unnecessary cache line movements in [PATCH v4 10/12](suggested by sebastian and Nadav).
- Collect Acked-bys and Reviewed-bys.
Changes in v3:
- Add benchmarks to measure the performance impact of changing flush_tlb_info to stack variable in [PATCH v3 10/12] (suggested by peter)
- Adjust the rcu_read_unlock() location in [PATCH v3 5/12] (suggested by muchun)
- Use raw_smp_processor_id() to prevent warning[1] from check_preemption_disabled() in [PATCH v3 12/12].
- Collect Acked-bys and Reviewed-by.
[1]: https://lore.kernel.org/lkml/[email protected]/T/#mc39999cbeb3f50be176f0903d0fa4075688b073d
Changes in v2:
- Simplify the code comments in [PATCH v2 2/12] (pointed by peter and muchun)
- Adjust the preemption disabling logic in smp_call_function_any() in [PATCH v2 3/12] (suggested by peter).
- Use on-stack cpumask only when !CONFIG_CPUMASK_OFFSTACK in [PATCH V2 4/12] (pointed by peter)
- Add [PATCH v2 5/12] to replace migrate_disable with the rcu mechanism
- Adjust the preemption disabling logic to allow flush_tlb_multi() to be preemptible and migratable in [PATCH v2 11/12]
- Collect Acked-bys and Reviewed-bys
Introduction
============
The vast majority of smp_call_function*() callers block until remote CPUs complete the IPI function execution. As smp_call_function*() runs with preemption disabled throughout, scheduling latency increases dramatically with the number of remote CPUs and other factors (such as interrupts being disabled).
On x86-64 architectures, TLB flushes are performed via IPIs; thus, during process exit or when process-mapped pages are reclaimed, numerous IPI operations must be awaited, leading to increased scheduling latency for other threads on the current CPU. In our production environment, we observed IPI wait-induced scheduling latency reaching up to 16ms on a 16-core machine. Our goal is to allow preemption during IPI completion waiting to improve real-time performance.
Background
============
In our production environments, latency-sensitive workloads (DPDK) are configured with the highest priority to preempt lower-priority tasks at any time. We discovered that DPDK's wake-up latency is primarily caused by the current CPU having preemption disabled. Therefore, we collected the maximum preemption disabled events within every 30-second interval and then calculated the P50/P99 of these max preemption disabled events:
p50(ns) p99(ns) cpu0 254956 5465050 cpu1 115801 120782 cpu2 43324 72957 cpu3 256637 16723307 cpu4 58979 87237 cpu5 47464 79815 cpu6 48881 81371 cpu7 52263 82294 cpu8 263555 4657713 cpu9 44935 73962 cpu10 37659 65026 cpu11 257008 2706878 cpu12 49669 90006 cpu13 45186 74666 cpu14 60705 83866 cpu15 51311 86885
Meanwhile, we have collected the distribution of preemption disabling events exceeding 1ms across different CPUs over several hours(I omitted CPU data that were all zeros):
CPU 1~10ms 10~50ms 50~100ms
cpu0 29 5 0 cpu3 38 13 0 cpu8 34 6 0 cpu11 24 10 0
The preemption disabled for several milliseconds or even 10ms+ mostly originates from TLB flush:
@stack[
trace_preempt_on+143
trace_preempt_on+143
preempt_count_sub+67
arch_tlbbatch_flush/flush_tlb_mm_range
task_exit/page_reclaim/...]
Further analysis confirms that the majority of the time is consumed in csd_lock_wait().
Now smp_call*() always needs to disable preemption, mainly to protect its internal per‑CPU data structures and synchronize with CPU offline operations. This patchset attempts to make csd_lock_wait() preemptible, thereby reducing the preemption‑disabled critical section and improving kernel real‑time performance.
Effect
======
After applying this patchset, we no longer observe preemption disabled for more than 1ms on the arch_tlbbatch_flush/flush_tlb_mm_range path. The overall P99 of max preemption disabled events in every 30-second is reduced to around 1.5ms (the remaining latency is primarily due to lock contention.
before patch after patch reduced by
----------- -------------- ------------
p99(ns) 16723307 1556034 ~90.70%
Chuyi Zhou (12):
smp: Disable preemption explicitly in __csd_lock_wait
smp: Enable preemption early in smp_call_function_single
smp: Refactor remote CPU selection in smp_call_function_any()
smp: Use task-local IPI cpumask in smp_call_function_many_cond()
smp: Alloc percpu csd data in smpcfd_prepare_cpu() only once
smp: Enable preemption early in smp_call_function_many_cond
smp: Remove preempt_disable from smp_call_function
smp: Remove preempt_disable from on_each_cpu_cond_mask
scftorture: Remove preempt_disable in scftorture_invoke_one x86/mm: Move flush_tlb_info back to the stack
x86/mm: Enable preemption during native_flush_tlb_multi x86/mm: Enable preemption during flush_tlb_kernel_range
arch/x86/include/asm/tlbflush.h | 8 +- arch/x86/kernel/kvm.c | 4 +- arch/x86/mm/tlb.c | 86 ++++++----------- include/linux/sched.h | 6 ++ include/linux/smp.h | 20 ++++ kernel/fork.c | 9 +- kernel/scftorture.c | 13 +-- kernel/smp.c | 157 ++++++++++++++++++++++++-------- 8 files changed, 195 insertions(+), 108 deletions(-)
Signature · 1 line
2.20.1
PATCH RESEND v5 1/12 smp: Disable preemption explicitly in __csd_lock_wait
The latter patches will enable preemption before csd_lock_wait(), which could break csdlock_debug. Because the slice of other tasks on the CPU may be accounted between ktime_get_mono_fast_ns() calls, disable preemption explicitly in __csd_lock_wait(). This is a preparation for the next patches.
--- kernel/smp.c | 2 ++ 1 file changed, 2 insertions(+)
kernel/smp.c +2 -0
@@ -323,6 +323,8 @@ static void __csd_lock_wait(call_single_data_t *csd)int bug_id =0 ;u64 ts0, ts1; +guard (preempt)(); + ts1 = ts0 =ktime_get_mono_fast_ns ();for (;;) {if (csd_lock_wait_toolong (csd, ts0, &ts1, &bug_id, &nmessages))
Signature · 1 line
2.20.1
PATCH RESEND v5 2/12 smp: Enable preemption early in smp_call_function_single
In reply to Chuyi ZhouNow smp_call_function_single() disables preemption mainly for the following reasons:
- To protect the per-cpu csd_data from concurrent modification by other tasks on the current CPU in the !wait case. For the wait case, synchronization is not a concern as on-stack csd is used.
- To prevent the remote online CPU from being offlined. Specifically, we want to ensure that no new IPIs are queued after smpcfd_dying_cpu() has finished.
Disabling preemption for the entire execution is unnecessary, especially csd_lock_wait() part does not require preemption protection. This patch enables preemption before csd_lock_wait() to reduce the preemption-disabled critical section.
--- kernel/smp.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/smp.c +7 -2
@@ -700,11 +700,16 @@ int smp_call_function_single(int cpu, smp_call_func_t func, void *info, err =generic_exec_single (cpu, csd); +/* +* @csd is stack-allocated when @wait is true. No concurrent access +* except from the IPI completion path, so we can re-enable preemption +* early to reduce latency. +*/ +put_cpu (); +if (wait)csd_lock_wait (csd); -put_cpu (); -return err; }EXPORT_SYMBOL (smp_call_function_single);
Signature · 1 line
2.20.1
PATCH RESEND v5 3/12 smp: Refactor remote CPU selection in smp_call_function_any()
In reply to Chuyi ZhouCurrently, smp_call_function_any() disables preemption across the entire process of picking a target CPU, enqueueing the IPI, and synchronously waiting for the remote CPU. Since smp_call_function_single() has already been optimized to re-enable preemption before the synchronous csd_lock_wait(), callers of smp_call_function_any() should also benefit from this optimization to reduce the preemption-disabled critical section.
A naive approach would be to simply remove get_cpu() and put_cpu() from smp_call_function_any(), leaving the preemption disablement entirely to smp_call_function_single(). However, doing so opens a dangerous preemption window between picking the remote CPU (e.g., via sched_numa_find_nth_cpu()) and dispatching the IPI inside smp_call_function_single(). If the selected remote CPU is fully offlined during this window, smp_call_function_single() will fail its cpu_online() check and return -ENXIO directly to the caller, violating the guarantee to execute on *any* online CPU in the mask.
To safely enable this optimization, this patch refactors the logic of smp_call_function_any() and smp_call_function_single(). By moving the random remote CPU selection into a common __smp_call_function_single(), and keep the entire selection and IPI dispatch process within a single preemption-disabled region.
--- kernel/smp.c | 48 ++++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-)
kernel/smp.c +26 -22
@@ -641,17 +641,8 @@ void flush_smp_call_function_queue(void)local_irq_restore (flags); } -/** -* smp_call_function_single - Run a function on a specific CPU -* @cpu: Specific target CPU for this function. -* @func: The function to run. This must be fast and non-blocking. -* @info: An arbitrary pointer to pass to the function. -* @wait: If true, wait until function has completed on other CPUs. -* -* Returns: %0 on success, else a negative status code. -*/ -int smp_call_function_single (int cpu,smp_call_func_t func,void *info, -int wait) +static int __smp_call_function_single (int cpu,smp_call_func_t func, +void *info,const struct cpumask *mask,int wait) {call_single_data_t *csd;call_single_data_t csd_stack = {
@@ -668,6 +659,14 @@ int smp_call_function_single(int cpu, smp_call_func_t func, void *info,*/ this_cpu =get_cpu (); +if (mask) { +/* Try for same CPU (cheapest) */ +if (!cpumask_test_cpu (this_cpu, mask)) + cpu =sched_numa_find_nth_cpu (mask,0 ,cpu_to_node (this_cpu)); +else + cpu = this_cpu; + } +/* * Can deadlock when called with interrupts disabled. * We allow cpu's that are not yet online though, as no one else can
@@ -712,6 +711,21 @@ int smp_call_function_single(int cpu, smp_call_func_t func, void *info,return err; } + +/** +* smp_call_function_single - Run a function on a specific CPU +* @cpu: Specific target CPU for this function. +* @func: The function to run. This must be fast and non-blocking. +* @info: An arbitrary pointer to pass to the function. +* @wait: If true, wait until function has completed on other CPUs. +* +* Returns: %0 on success, else a negative status code. +*/ +int smp_call_function_single (int cpu,smp_call_func_t func,void *info, +int wait) +{ +return __smp_call_function_single (cpu, func, info,NULL , wait); +}EXPORT_SYMBOL (smp_call_function_single);/**
@@ -776,17 +790,7 @@ EXPORT_SYMBOL_GPL(smp_call_function_single_async);int smp_call_function_any (const struct cpumask *mask,smp_call_func_t func,void *info,int wait) { -unsigned int cpu; -int ret; - -/* Try for same CPU (cheapest) */ - cpu =get_cpu (); -if (!cpumask_test_cpu (cpu, mask)) - cpu =sched_numa_find_nth_cpu (mask,0 ,cpu_to_node (cpu)); - - ret =smp_call_function_single (cpu, func, info, wait); -put_cpu (); -return ret; +return __smp_call_function_single (-1 , func, info, mask, wait); }EXPORT_SYMBOL_GPL (smp_call_function_any);
Signature · 1 line
2.20.1
PATCH RESEND v5 4/12 smp: Use task-local IPI cpumask in smp_call_function_many_cond()
In reply to Chuyi ZhouThis patch prepares the task-local IPI cpumask during thread creation, and uses the local cpumask to replace the percpu cfd cpumask in smp_call_function_many_cond(). We will enable preemption during csd_lock_wait() later, and this can prevent concurrent access to the cfd->cpumask from other tasks on the current CPU. For cases where cpumask_size() is smaller than or equal to the pointer size, it tries to stash the cpumask in the pointer itself to avoid extra memory allocations.
--- include/linux/sched.h | 6 +++++ include/linux/smp.h | 20 +++++++++++++++ kernel/fork.c | 9 ++++++- kernel/smp.c | 59 ++++++++++++++++++++++++++++++++++++++----- 4 files changed, 87 insertions(+), 7 deletions(-)
include/linux/sched.h +6 -0
@@ -1348,6 +1348,12 @@ struct task_struct {struct list_head perf_event_list;struct perf_ctx_data __rcu *perf_ctx_data;#endif +#if defined(CONFIG_SMP ) && defined(CONFIG_PREEMPTION ) +union { +cpumask_t *ipi_mask_ptr; +unsigned long ipi_mask_val; + }; +#endif #ifdef CONFIG_DEBUG_PREEMPT unsigned long preempt_disable_ip;#endif
include/linux/smp.h +20 -0
@@ -167,6 +167,12 @@ void smp_call_function_many(const struct cpumask *mask,int smp_call_function_any (const struct cpumask *mask,smp_call_func_t func,void *info,int wait); +#ifdef CONFIG_PREEMPTION +int smp_task_ipi_mask_alloc (struct task_struct *task); +void smp_task_ipi_mask_free (struct task_struct *task); +cpumask_t *smp_task_ipi_mask (struct task_struct *cur); +#endif +void kick_all_cpus_sync (void );void wake_up_all_idle_cpus (void );bool cpus_peek_for_pending_ipi (const struct cpumask *mask);
@@ -310,4 +316,18 @@ bool csd_lock_is_stuck(void);static inline bool csd_lock_is_stuck (void ) {return false; }#endif +#if !defined(CONFIG_SMP ) || !defined(CONFIG_PREEMPTION ) +static inline int smp_task_ipi_mask_alloc (struct task_struct *task) +{ +return 0 ; +} +static inline void smp_task_ipi_mask_free (struct task_struct *task) +{ +} +static inline cpumask_t *smp_task_ipi_mask (struct task_struct *cur) +{ +return NULL ; +} +#endif +#endif /* __LINUX_SMP_H */
kernel/fork.c +8 -1
@@ -535,6 +535,7 @@ void free_task(struct task_struct *tsk)#endif release_user_cpus_ptr (tsk);scs_release (tsk); +smp_task_ipi_mask_free (tsk);#ifndef CONFIG_THREAD_INFO_IN_TASK /*
@@ -932,10 +933,14 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)#endif account_kernel_stack (tsk,1 ); - err =scs_prepare (tsk, node); + err =smp_task_ipi_mask_alloc (tsk);if (err) goto free_stack; + err =scs_prepare (tsk, node); +if (err) + goto free_ipi_mask; +#ifdef CONFIG_SECCOMP /* * We must handle setting up seccomp filters once we're under
@@ -1006,6 +1011,8 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)#endif return tsk; +free_ipi_mask: +smp_task_ipi_mask_free (tsk); free_stack:exit_task_stack_account (tsk);free_thread_stack (tsk);
kernel/smp.c +53 -6
99 lines not on this page · raw message
Signature · 1 line
2.20.1
Re: [RESEND PATCH v5 04/12] smp: Use task-local IPI cpumask in smp_call_function_many_cond()
Quoted 9 lines · Chuyi Zhou
kernel/smp.c +1
-0@@ -811,11 +849,18 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int cpu, last_cpu, this_cpu =smp_processor_id ();struct call_function_data *cfd;bool wait = scf_flags &SCF_WAIT ; +struct cpumask *cpumask, *task_mask;
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 862
Quoted 10 lines
kernel/smp.c +5
-0+bool preemptible_wait;int nr_cpus =0 ;bool run_remote = false;lockdep_assert_preemption_disabled (); + task_mask =smp_task_ipi_mask (current); + preemptible_wait = task_mask; + cfd =this_cpu_ptr (&cfd_data); + cpumask = preemptible_wait ? task_mask : cfd->cpumask;
Is this a porting artifact? preemptible_wait is a bool while task_mask is a pointer which is always != NULL.
UP to here the patches and the code made sense.
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 866
Quoted 4 lines
kernel/smp.c +1
-0+/* * Can deadlock when called with interrupts disabled. * We allow cpu's that are not yet online though, as no one else can
Sebastian
Re: [RESEND PATCH v5 04/12] smp: Use task-local IPI cpumask in smp_call_function_many_cond()
Quoted 16 lines · Sebastian Andrzej Siewior
Quoted 15 lines · Chuyi Zhou
kernel/smp.c +2
-0@@ -811,11 +849,18 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int cpu, last_cpu, this_cpu =smp_processor_id ();struct call_function_data *cfd;bool wait = scf_flags &SCF_WAIT ; +struct cpumask *cpumask, *task_mask; +bool preemptible_wait;int nr_cpus =0 ;bool run_remote = false;lockdep_assert_preemption_disabled ();
Quoted 8 lines
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 862
Quoted 4 lines
kernel/smp.c +4
-0+ task_mask =smp_task_ipi_mask (current); + preemptible_wait = task_mask; + cfd =this_cpu_ptr (&cfd_data); + cpumask = preemptible_wait ? task_mask : cfd->cpumask;Is this a porting artifact?
preemptible_waitis a bool whiletask_maskis a pointer which is always != NULL.
Not exactly. The NULL fallback is intentional: smp_task_ipi_mask() returns NULL for !CONFIG_PREEMPTION, and init_task may also not have an allocated ipi_mask_ptr in the non-inlined case.
But you are right that the name is confusing in this preparatory patch. Here it only means "task-local cpumask is available", not that the wait is actually preemptible. I will drop this bool in this patch, and keep the real preemptible wait condition in the later patch as:
preemptible_wait = task_mask && preemptible();
Quoted 8 lines
UP to here the patches and the code made sense.
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 866
Quoted 4 lines
kernel/smp.c +1
-0+/* * Can deadlock when called with interrupts disabled. * We allow cpu's that are not yet online though, as no one else can Sebastian
Re: [RESEND PATCH v5 04/12] smp: Use task-local IPI cpumask in smp_call_function_many_cond()
Quoted 26 lines · Chuyi Zhou
Quoted 16 lines · Sebastian Andrzej Siewior
Quoted 15 lines · Chuyi Zhou
kernel/smp.c +2
-0@@ -811,11 +849,18 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int cpu, last_cpu, this_cpu =smp_processor_id ();struct call_function_data *cfd;bool wait = scf_flags &SCF_WAIT ; +struct cpumask *cpumask, *task_mask; +bool preemptible_wait;int nr_cpus =0 ;bool run_remote = false;lockdep_assert_preemption_disabled ();Quoted 8 lines
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 862
Quoted 4 lines
kernel/smp.c +4
-0+ task_mask =smp_task_ipi_mask (current); + preemptible_wait = task_mask; + cfd =this_cpu_ptr (&cfd_data); + cpumask = preemptible_wait ? task_mask : cfd->cpumask;Is this a porting artifact?
preemptible_waitis a bool whiletask_maskis a pointer which is always != NULL.
Quoted 3 lines
Not exactly. The NULL fallback is intentional:
smp_task_ipi_mask()returns NULL for !CONFIG_PREEMPTION, andinit_taskmay also not have an allocatedipi_mask_ptrin the non-inlined case.
Okay, but please don't assign a cpumask to a bool and having one to guess all that behind it. Something like
cfd = this_cpu_ptr(&cfd_data);
task_mask = smp_task_ipi_mask(current);
if (task_mask)
cpumask = task_mask;
else
cpumask = cfd->cpumask;would make it probably obvious. You probably need a bool later on to check if you use task's mask and can open preemption while waiting. Hmm. Let me continue…
Quoted 6 lines
But you are right that the name is confusing in this preparatory patch. Here it only means "task-local cpumask is available", not that the wait is actually preemptible. I will drop this bool in this patch, and keep the real preemptible wait condition in the later patch as:
preemptible_wait = task_mask && preemptible();
There is a lockdep_assert_preemption_disabled() so that preemptible() must evaluate false.
Sebastian
PATCH RESEND v5 5/12 smp: Alloc percpu csd data in smpcfd_prepare_cpu() only once
In reply to Chuyi ZhouLater patch would enable preemption during csd_lock_wait() in smp_call_function_many_cond(), which may cause access cfd->csd data that has already been freed in smpcfd_dead_cpu().
One way to fix the above issue is to use the RCU mechanism to protect the csd data and wait for all read critical sections to exit before freeing the memory in smpcfd_dead_cpu(), but this could delay CPU shutdown. This patch chooses a simpler approach: allocate the percpu csd on the UP side only once and skip freeing the csd memory in smpcfd_dead_cpu().
--- kernel/smp.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/smp.c +9 -2
@@ -63,7 +63,15 @@ int smpcfd_prepare_cpu(unsigned int cpu)free_cpumask_var (cfd->cpumask);return -ENOMEM ; } - cfd->csd =alloc_percpu (call_single_data_t); + +/* +* The percpu csd is allocated only once and never freed. +* This ensures that smp_call_function_many_cond() can safely +* access the csd of an offlined CPU if it gets preempted +* during csd_lock_wait(). +*/ +if (!cfd->csd) + cfd->csd =alloc_percpu (call_single_data_t);if (!cfd->csd) {free_cpumask_var (cfd->cpumask);free_cpumask_var (cfd->cpumask_ipi);
@@ -79,7 +87,6 @@ int smpcfd_dead_cpu(unsigned int cpu)free_cpumask_var (cfd->cpumask);free_cpumask_var (cfd->cpumask_ipi); -free_percpu (cfd->csd);return 0 ; }
Signature · 1 line
2.20.1
PATCH RESEND v5 6/12 smp: Enable preemption early in smp_call_function_many_cond
In reply to Chuyi ZhouDisabling preemption entirely during smp_call_function_many_cond() was primarily for the following reasons:
- To prevent the remote online CPU from going offline. Specifically, we want to ensure that no new csds are queued after smpcfd_dying_cpu() has finished. Therefore, preemption must be disabled until all necessary IPIs are sent.
- To prevent current CPU from going offline. Being migrated to another CPU and calling csd_lock_wait() may cause UAF due to smpcfd_dead_cpu() during the current CPU offline process.
- To protect the per-cpu cfd_data from concurrent modification by other tasks on the current CPU. cfd_data contains cpumasks and per-cpu csds. Before enqueueing a csd, we block on the csd_lock() to ensure the previous async csd->func() has completed, and then initialize csd->func and csd->info. After sending the IPI, we spin-wait for the remote CPU to call csd_unlock(). Actually the csd_lock mechanism already guarantees csd serialization. If preemption occurs during csd_lock_wait, other concurrent smp_call_function_many_cond calls will simply block until the previous csd->func() completes:
task A task B
sd->func = fun_a
send ipis
preempted by B
--------------->
csd_lock(csd); // block until last
// fun_a finished
csd->func = func_b;
csd->info = info;
...
send ipis
switch back to A
<---------------csd_lock_wait(csd); // block until remote finish func_*
Previous patches replaced the per-cpu cfd->cpumask with task-local cpumask, and the percpu csd is allocated only once and is never freed to ensure we can safely access csd. Now we can enable preemption before csd_lock_wait() which makes the potentially unpredictable csd_lock_wait() preemptible and migratable.
--- kernel/smp.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-)
kernel/smp.c +21 -6
@@ -853,7 +853,7 @@ static void smp_call_function_many_cond(const struct cpumask *mask,unsigned int scf_flags, smp_cond_func_t cond_func) { - int cpu, last_cpu, this_cpu = smp_processor_id(); + int cpu, last_cpu, this_cpu;struct call_function_data *cfd;bool wait = scf_flags &SCF_WAIT ;struct cpumask *cpumask, *task_mask;
@@ -861,10 +861,10 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int nr_cpus =0 ;bool run_remote = false; -lockdep_assert_preemption_disabled (); - task_mask =smp_task_ipi_mask (current); - preemptible_wait = task_mask; + preemptible_wait = task_mask &&preemptible (); + + this_cpu =get_cpu (); cfd =this_cpu_ptr (&cfd_data); cpumask = preemptible_wait ? task_mask : cfd->cpumask;
@@ -946,6 +946,19 @@ static void smp_call_function_many_cond(const struct cpumask *mask,local_irq_restore (flags); } +/* +* We may block in csd_lock_wait() for a significant amount of time, +* especially when interrupts are disabled or with a large number of +* remote CPUs. Try to enable preemption before csd_lock_wait(). +* +* Use the task_mask instead of cfd->cpumask to avoid concurrency +* modification from tasks on the same cpu. If preemption occurs during +* csd_lock_wait, other concurrent smp_call_function_many_cond() calls +* will simply block until the previous csd->func() completes. +*/ +if (preemptible_wait) +put_cpu (); +if (run_remote && wait) {for_each_cpu (cpu, cpumask) {call_single_data_t *csd;
@@ -954,6 +967,9 @@ static void smp_call_function_many_cond(const struct cpumask *mask,csd_lock_wait (csd); } } + +if (!preemptible_wait) +put_cpu (); }/**
@@ -965,8 +981,7 @@ static void smp_call_function_many_cond(const struct cpumask *mask,* on other CPUs. * * You must not call this function with disabled interrupts or from a -* hardware interrupt handler or from a bottom half handler. Preemption -* must be disabled when calling this function. +* hardware interrupt handler or from a bottom half handler. * * @func is not called on the local CPU even if @mask contains it. Consider * using on_each_cpu_cond_mask() instead if this is not desirable.
Signature · 1 line
2.20.1
Re: [RESEND PATCH v5 06/12] smp: Enable preemption early in smp_call_function_many_cond
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 865
Quoted 11 lines · Chuyi Zhou
kernel/smp.c +1
-3@@ -861,10 +861,10 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int nr_cpus =0 ;bool run_remote = false; -lockdep_assert_preemption_disabled (); - task_mask =smp_task_ipi_mask (current); - preemptible_wait = task_mask; + preemptible_wait = task_mask &&preemptible ();
Now that I stare at this again, why is preemptible() a thing here? You care about doing put_cpu() below before csd_lock_wait(). This can only be done if you get a cpumask from smp_task_ipi_mask(). If preemption or interrupts is/are disabled then you still can use the "private" cpumask and do the early put_cpu(). It simply is no optimisation.
This basically reduces the check to a CONFIG_PREEMPTION=y kernel because otherwise you have no cpumask. And this is not done on !SMP kernels. smp_task_ipi_mask() is only used here so there is no need to export it via headers.
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 952
Quoted 13 lines
kernel/smp.c +6
-0+ + this_cpu =get_cpu (); cfd =this_cpu_ptr (&cfd_data); cpumask = preemptible_wait ? task_mask : cfd->cpumask;@@ -946,6 +946,19 @@ static void smp_call_function_many_cond(const struct cpumask *mask,local_irq_restore (flags); } +/* +* We may block in csd_lock_wait() for a significant amount of time, +* especially when interrupts are disabled or with a large number of +* remote CPUs. Try to enable preemption before csd_lock_wait().
If interrupts are disabled there is no gain. Also we sort of expect interrupts to be enabled here.
Waiting for completion can take time especially with many CPUs. On a PREEMPTIBLE kernel a per-task cpumask is used to track CPUs with pending IPI request. This allows to enable preemption and potentially wait while allowing task preemption. On a !PREEMPTIBLE the cpumask is shared and the call must block until completion to avoid modifications by a another caller on this CPU.
Quoted 13 lines
kernel/smp.c +9
-0+* +* Use the task_mask instead of cfd->cpumask to avoid concurrency +* modification from tasks on the same cpu. If preemption occurs during +* csd_lock_wait, other concurrent smp_call_function_many_cond() calls +* will simply block until the previous csd->func() completes. +*/ +if (preemptible_wait) +put_cpu (); +if (run_remote && wait) {for_each_cpu (cpu, cpumask) {call_single_data_t *csd;
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 975
Quoted 9 lines
kernel/smp.c +3
-0@@ -954,6 +967,9 @@ static void smp_call_function_many_cond(const struct cpumask *mask,csd_lock_wait (csd); } } + +if (!preemptible_wait) +put_cpu (); }/**
Sebastian
Re: [RESEND PATCH v5 06/12] smp: Enable preemption early in smp_call_function_many_cond
Quoted 20 lines · Sebastian Andrzej Siewior
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 865
Quoted 11 lines · Chuyi Zhou
kernel/smp.c +1
-3@@ -861,10 +861,10 @@ static void smp_call_function_many_cond(const struct cpumask *mask,int nr_cpus =0 ;bool run_remote = false; -lockdep_assert_preemption_disabled (); - task_mask =smp_task_ipi_mask (current); - preemptible_wait = task_mask; + preemptible_wait = task_mask &&preemptible ();Now that I stare at this again, why is
preemptible()a thing here? You care about doingput_cpu()below beforecsd_lock_wait(). This can only be done if you get a cpumask fromsmp_task_ipi_mask(). If preemption or interrupts is/are disabled then you still can use the "private" cpumask and do the earlyput_cpu(). It simply is no optimisation.
Quoted 5 lines
This basically reduces the check to a
CONFIG_PREEMPTION=ykernel because otherwise you have no cpumask. And this is not done on !SMP kernels.smp_task_ipi_mask()is only used here so there is no need to export it via headers.
Agreed. The safety condition for the early put_cpu() is the availability of the task-local cpumask, not preemptible(). If an outer context already keeps preemption or interrupts disabled, the early put_cpu() simply does not buy anything.
I will make the condition depend on task_mask directly, drop the preemptible() check, keep smp_task_ipi_mask() local to kernel/smp.c, and adjust the comment as suggested.
Thanks.
Quoted 48 lines
kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 952
Quoted 13 lines
kernel/smp.c +6
-0+ + this_cpu =get_cpu (); cfd =this_cpu_ptr (&cfd_data); cpumask = preemptible_wait ? task_mask : cfd->cpumask;@@ -946,6 +946,19 @@ static void smp_call_function_many_cond(const struct cpumask *mask,local_irq_restore (flags); } +/* +* We may block in csd_lock_wait() for a significant amount of time, +* especially when interrupts are disabled or with a large number of +* remote CPUs. Try to enable preemption before csd_lock_wait(). If interrupts are disabled there is no gain. Also we sort of expect interrupts to be enabled here.
Waiting for completion can take time especially with many CPUs. On a PREEMPTIBLE kernel a per-task cpumask is used to track CPUs with pending IPI request. This allows to enable preemption and potentially wait while allowing task preemption. On a !PREEMPTIBLE the cpumask is shared and the call must block until completion to avoid modifications by a another caller on this CPU.
Quoted 13 lines
kernel/smp.c +9
-0+* +* Use the task_mask instead of cfd->cpumask to avoid concurrency +* modification from tasks on the same cpu. If preemption occurs during +* csd_lock_wait, other concurrent smp_call_function_many_cond() calls +* will simply block until the previous csd->func() completes. +*/ +if (preemptible_wait) +put_cpu (); +if (run_remote && wait) {for_each_cpu (cpu, cpumask) {call_single_data_t *csd;kernel/smp.c static void smp_call_function_many_cond(const struct cpumask *mask, · line 975
Quoted 9 lines
kernel/smp.c +3
-0@@ -954,6 +967,9 @@ static void smp_call_function_many_cond(const struct cpumask *mask,csd_lock_wait (csd); } } + +if (!preemptible_wait) +put_cpu (); }/** Sebastian
PATCH RESEND v5 7/12 smp: Remove preempt_disable from smp_call_function
In reply to Chuyi ZhouNow smp_call_function_many_cond() internally handles the preemption logic, so smp_call_function() does not need to explicitly disable preemption. Remove preempt_{enable, disable} from smp_call_function().
--- kernel/smp.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
kernel/smp.c +2 -3
@@ -1008,9 +1008,8 @@ EXPORT_SYMBOL(smp_call_function_many);*/ void smp_call_function (smp_call_func_t func,void *info,int wait) { -preempt_disable (); -smp_call_function_many (cpu_online_mask, func, info, wait); -preempt_enable (); +smp_call_function_many_cond (cpu_online_mask, func, info, + wait ?SCF_WAIT :0 ,NULL ); }EXPORT_SYMBOL (smp_call_function);
Signature · 1 line
2.20.1
PATCH RESEND v5 8/12 smp: Remove preempt_disable from on_each_cpu_cond_mask
In reply to Chuyi ZhouNow smp_call_function_many_cond() internally handles the preemption logic, so on_each_cpu_cond_mask does not need to explicitly disable preemption. Remove preempt_{enable, disable} from on_each_cpu_cond_mask().
--- kernel/smp.c | 2 -- 1 file changed, 2 deletions(-)
kernel/smp.c +0 -2
@@ -1132,9 +1132,7 @@ void on_each_cpu_cond_mask(smp_cond_func_t cond_func, smp_call_func_t func,if (wait) scf_flags |=SCF_WAIT ; -preempt_disable ();smp_call_function_many_cond (mask, func, info, scf_flags, cond_func); -preempt_enable (); }EXPORT_SYMBOL (on_each_cpu_cond_mask);
Signature · 1 line
2.20.1
PATCH RESEND v5 9/12 scftorture: Remove preempt_disable in scftorture_invoke_one
In reply to Chuyi ZhouPrevious patches make smp_call*() functions handle preemption logic internally. Thus, the explicit preempt_disable() surrounding these calls becomes unnecessary. Furthermore, keeping the external preempt_disable() would prevent scftorture from exercising the newly narrowed internal preemption-disabled regions during IPI dispatch. This patch removes the preempt_{enable, disable} pairs in scftorture_invoke_one().
Removing this preemption protection could expose a race condition with CPU hotplug when use_cpus_read_lock is false. Specifically, for multi-cast operations (SCF_PRIM_MANY or SCF_PRIM_ALL), if only 1 CPU is online, smp_call_function_many() correctly skips sending IPIs and leaves scfc_out as false. Without preemption disabled, a CPU hotplug thread could preempt the test thread, bring a second CPU online, and increment num_online_cpus(). When the test thread resumes, the validation check would see num_online_cpus() > 1 and falsely trigger the memory-ordering warning, leaking the scfcp structure.
To avoid this potential false positive, restrict the num_online_cpus() > 1 condition to only apply when use_cpus_read_lock is true, ensuring the CPU count remains stable during evaluation.
--- kernel/scftorture.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-)
kernel/scftorture.c +4 -9
@@ -348,6 +348,8 @@ static void scftorture_invoke_one(struct scf_statistics *scfp, struct torture_raint ret =0 ;struct scf_check *scfcp =NULL ;struct scf_selector *scfsp =scf_sel_rand (trsp); +bool is_single = (scfsp->scfs_prim ==SCF_PRIM_SINGLE || + scfsp->scfs_prim ==SCF_PRIM_SINGLE_RPC );if (scfsp->scfs_prim ==SCF_PRIM_SINGLE || scfsp->scfs_wait) { scfcp =kmalloc_obj (*scfcp,GFP_ATOMIC );
@@ -364,8 +366,6 @@ static void scftorture_invoke_one(struct scf_statistics *scfp, struct torture_ra }if (use_cpus_read_lock)cpus_read_lock (); -else -preempt_disable ();switch (scfsp->scfs_prim) {case SCF_PRIM_RESCHED :if (IS_BUILTIN (CONFIG_SCF_TORTURE_TEST )) {
@@ -411,13 +411,10 @@ static void scftorture_invoke_one(struct scf_statistics *scfp, struct torture_raif (!ret) {if (use_cpus_read_lock)cpus_read_unlock (); -else -preempt_enable (); +wait_for_completion (&scfcp->scfc_completion);if (use_cpus_read_lock)cpus_read_lock (); -else -preempt_disable (); }else { scfp->n_single_rpc_ofl++;scf_add_to_free_list (scfcp);
@@ -452,7 +449,7 @@ static void scftorture_invoke_one(struct scf_statistics *scfp, struct torture_ra scfcp->scfc_out = true; }if (scfcp && scfsp->scfs_wait) { -if (WARN_ON_ONCE ((num_online_cpus () >1 || scfsp->scfs_prim ==SCF_PRIM_SINGLE ) && +if (WARN_ON_ONCE (((use_cpus_read_lock &&num_online_cpus () >1 ) || is_single) && !scfcp->scfc_out)) {pr_warn ("%s: Memory-ordering failure, scfs_prim: %d.\n" , __func__, scfsp->scfs_prim);atomic_inc (&n_mb_out_errs);// Leak rather than trash!
@@ -463,8 +460,6 @@ static void scftorture_invoke_one(struct scf_statistics *scfp, struct torture_ra }if (use_cpus_read_lock)cpus_read_unlock (); -else -preempt_enable ();if (allocfail)schedule_timeout_idle ((1 + longwait) *HZ );// Let no-wait handlers complete. else if (!(torture_random (trsp) &0xfff ))
Signature · 1 line
2.20.1
PATCH RESEND v5 10/12 x86/mm: Move flush_tlb_info back to the stack
In reply to Chuyi ZhouCommit 3db6d5a5ecaf ("x86/mm/tlb: Remove 'struct flush_tlb_info' from the stack") converted flush_tlb_info from stack variable to per-CPU variable. This brought about a performance improvement of around 3% in extreme test. However, it also required that all flush_tlb* operations keep preemption disabled entirely to prevent concurrent modifications of flush_tlb_info. flush_tlb* needs to send IPIs to remote CPUs and synchronously wait for all remote CPUs to complete their local TLB flushes. The process could take tens of milliseconds when interrupts are disabled or with a large number of remote CPUs.
From the perspective of improving kernel real-time performance, this patch reverts flush_tlb_info back to stack variables and align it with SMP_CACHE_BYTES. In certain configurations, SMP_CACHE_BYTES may be large, so the alignment size is limited to 64. This is a preparation for enabling preemption during TLB flush in next patch.
To evaluate the performance impact of this patch, use the following script to reproduce the microbenchmark mentioned in commit 3db6d5a5ecaf ("x86/mm/tlb: Remove 'struct flush_tlb_info' from the stack"). The test environment is an Ice Lake system (Intel(R) Xeon(R) Platinum 8336C) with 128 CPUs and 2 NUMA nodes. During the test, the threads were bound to specific CPUs, and both pti and mitigations were disabled:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <unistd.h>
#define NUM_OPS 1000000
#define NUM_THREADS 3
#define NUM_RUNS 5
#define PAGE_SIZE 4096
volatile int stop_threads = 0;
void *busy_wait_thread(void *arg) {
while (!stop_threads) {
__asm__ volatile ("nop");
}
return NULL;
}
long long get_usec() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000LL + tv.tv_usec;
}
int main() {
pthread_t threads[NUM_THREADS];
char *addr;
int i, r;
addr = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE
| MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(1);
}
for (i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&threads[i], NULL, busy_wait_thread, NULL))
exit(1);
}
printf("Running benchmark: %d runs, %d ops each, %d background\n"
"threads\n", NUM_RUNS, NUM_OPS, NUM_THREADS);
for (r = 0; r < NUM_RUNS; r++) {
long long start, end;
start = get_usec();
for (i = 0; i < NUM_OPS; i++) {
addr[0] = 1;
if (madvise(addr, PAGE_SIZE, MADV_DONTNEED)) {
perror("madvise");
exit(1);
}
}
end = get_usec();
double duration = (double)(end - start);
double avg_lat = duration / NUM_OPS;
printf("Run %d: Total time %.2f us, Avg latency %.4f us/op\n",
r + 1, duration, avg_lat);
}
stop_threads = 1;
for (i = 0; i < NUM_THREADS; i++)
pthread_join(threads[i], NULL);
munmap(addr, PAGE_SIZE);
return 0;
}
base on-stack-aligned on-stack-not-aligned
---- --------- -----------
avg (usec/op) 2.5278 2.5261 2.5508
stddev 0.0007 0.0027 0.0023The benchmark results show that the average latency difference between the baseline (base) and the properly aligned stack variable (on-stack-aligned) is within the standard deviation (stddev). This indicates that the variations are caused by testing noise, and reverting to a stack variable with proper alignment causes no performance regression compared to the per-CPU implementation. The unaligned version (on-stack-not-aligned) shows a minor performance drop. This demonstrates that we can improve the real-time performance without sacrificing performance.
--- arch/x86/include/asm/tlbflush.h | 8 +++- arch/x86/mm/tlb.c | 72 +++++++++------------------------ 2 files changed, 27 insertions(+), 53 deletions(-)
arch/x86/include/asm/tlbflush.h +7 -1
@@ -211,6 +211,12 @@ extern u16 invlpgb_count_max;extern void initialize_tlbstate_and_flush (void ); +#if SMP_CACHE_BYTES >64 +#define FLUSH_TLB_INFO_ALIGN 64 +#else +#define FLUSH_TLB_INFO_ALIGN SMP_CACHE_BYTES +#endif +/* * TLB flushing: *
@@ -249,7 +255,7 @@ struct flush_tlb_info {u8 stride_shift;u8 freed_tables;u8 trim_cpumask; -}; +}__aligned(FLUSH_TLB_INFO_ALIGN) ;void flush_tlb_local (void );void flush_tlb_one_user (unsigned long addr);
arch/x86/mm/tlb.c +20 -52
135 lines not on this page · raw message
Signature · 1 line
2.20.1
PATCH RESEND v5 11/12 x86/mm: Enable preemption during native_flush_tlb_multi
In reply to Chuyi Zhounative_flush_tlb_multi() may be frequently called by flush_tlb_mm_range() and arch_tlbbatch_flush() in production environments. When pages are reclaimed or process exit, native_flush_tlb_multi() sends IPIs to remote CPUs and waits for all remote CPUs to complete their local TLB flushes. The overall latency may reach tens of milliseconds due to a large number of remote CPUs and other factors (such as interrupts being disabled). Since flush_tlb_mm_range() and arch_tlbbatch_flush() always disable preemption, which may cause increased scheduling latency for other threads on the current CPU.
Previous patch converted flush_tlb_info from per-cpu variable to on-stack variable. Additionally, it's no longer necessary to explicitly disable preemption before calling smp_call*() since they internally handle the preemption logic. Now it's safe to enable preemption during native_flush_tlb_multi().
--- arch/x86/kernel/kvm.c | 4 +++- arch/x86/mm/tlb.c | 9 +++++++-- 2 files changed, 10 insertions(+), 3 deletions(-)
arch/x86/kernel/kvm.c +3 -1
@@ -662,8 +662,10 @@ static void kvm_flush_tlb_multi(const struct cpumask *cpumask,u8 state;int cpu;struct kvm_steal_time *src; -struct cpumask *flushmask =this_cpu_cpumask_var_ptr (__pv_cpu_mask); +struct cpumask *flushmask; +guard (preempt)(); + flushmask =this_cpu_cpumask_var_ptr (__pv_cpu_mask);cpumask_copy (flushmask, cpumask);/* * We have to call flush only on online vCPUs. And
arch/x86/mm/tlb.c +7 -2
@@ -1421,9 +1421,11 @@ void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,if (mm_global_asid (mm)) {broadcast_tlb_flush (info); }else if (cpumask_any_but (mm_cpumask (mm), cpu) < nr_cpu_ids) { +put_cpu (); info->trim_cpumask =should_trim_cpumask (mm);flush_tlb_multi (mm_cpumask (mm), info);consider_global_asid (mm); + goto invalidate; }else if (mm ==this_cpu_read (cpu_tlbstate.loaded_mm)) {lockdep_assert_irqs_enabled ();local_irq_disable ();
@@ -1432,6 +1434,7 @@ void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start, }put_cpu (); +invalidate:mmu_notifier_arch_invalidate_secondary_tlbs (mm, start, end); }
@@ -1691,7 +1694,9 @@ void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)invlpgb_flush_all_nonglobals (); batch->unmapped_pages = false; }else if (cpumask_any_but (&batch->cpumask, cpu) < nr_cpu_ids) { +put_cpu ();flush_tlb_multi (&batch->cpumask, &info); + goto clear; }else if (cpumask_test_cpu (cpu, &batch->cpumask)) {lockdep_assert_irqs_enabled ();local_irq_disable ();
@@ -1699,9 +1704,9 @@ void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)local_irq_enable (); } -cpumask_clear (&batch->cpumask); -put_cpu (); +clear: +cpumask_clear (&batch->cpumask); }/*
Signature · 1 line
2.20.1
PATCH RESEND v5 12/12 x86/mm: Enable preemption during flush_tlb_kernel_range
In reply to Chuyi Zhouflush_tlb_kernel_range() is invoked when kernel memory mapping changes. On x86 platforms without the INVLPGB feature enabled, we need to send IPIs to every online CPU and synchronously wait for them to complete do_kernel_range_flush(). This process can be time-consuming due to factors such as a large number of CPUs or other issues (like interrupts being disabled). flush_tlb_kernel_range() always disables preemption, this may affect the scheduling latency of other tasks on the current CPU.
Previous patch converted flush_tlb_info from per-cpu variable to on-stack variable. Additionally, it's no longer necessary to explicitly disable preemption before calling smp_call*() since they internally handles the preemption logic. Now it's safe to enable preemption during flush_tlb_kernel_range(). Additionally, in get_flush_tlb_info() use raw_smp_processor_id() to avoid warnings from check_preemption_disabled().
--- arch/x86/mm/tlb.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
arch/x86/mm/tlb.c +3 -2
@@ -1394,7 +1394,7 @@ static void get_flush_tlb_info(struct flush_tlb_info *info, info->stride_shift = stride_shift; info->freed_tables = freed_tables; info->new_tlb_gen = new_tlb_gen; - info->initiating_cpu =smp_processor_id (); + info->initiating_cpu =raw_smp_processor_id (); info->trim_cpumask =0 ; }
@@ -1461,6 +1461,8 @@ static void invlpgb_kernel_range_flush(struct flush_tlb_info *info) {unsigned long addr, nr; +guard (preempt)(); +for (addr = info->start; addr < info->end; addr += nr <<PAGE_SHIFT ) { nr = (info->end - addr) >>PAGE_SHIFT ;
@@ -1505,7 +1507,6 @@ void flush_tlb_kernel_range(unsigned long start, unsigned long end) {struct flush_tlb_info info; -guard (preempt)();get_flush_tlb_info (&info,NULL , start, end,PAGE_SHIFT , false,TLB_GENERATION_INVALID );
Signature · 1 line
2.20.1
Re: [RESEND PATCH v5 12/12] x86/mm: Enable preemption during flush_tlb_kernel_range
Quoted 8 lines · Chuyi Zhou
flush_tlb_kernel_range()is invoked when kernel memory mapping changes. On x86 platforms without the INVLPGB feature enabled, we need to send IPIs to every online CPU and synchronously wait for them to completedo_kernel_range_flush(). This process can be time-consuming due to factors such as a large number of CPUs or other issues (like interrupts being disabled).flush_tlb_kernel_range()always disables preemption, this may affect the scheduling latency of other tasks on the current CPU.
Quoted 6 lines
Previous patch converted
flush_tlb_infofrom per-cpu variable to on-stack variable. Additionally, it's no longer necessary to explicitly disable preemption before calling smp_call*() since they internally handles the preemption logic. Now it's safe to enable preemption duringflush_tlb_kernel_range(). Additionally, inget_flush_tlb_info()useraw_smp_processor_id()to avoid warnings fromcheck_preemption_disabled().
This is a bit odd. That smp_processor_id() is there to catch users with enabled CPU migration. The only reason is the accounting done in flush_tlb_func(). This raw_smp_processor_id() is only needed in flush_tlb_kernel_range() which does not call flush_tlb_func(). This is only statistics.
kernel_tlb_flush_all() does not need info at all. kernel_tlb_flush_range() needs only start and end.
Oh well.
Quoted 1 line
Signed-off-by Chuyi Zhou <[email protected]>
Sebastian
Re: [RESEND PATCH v5 12/12] x86/mm: Enable preemption during flush_tlb_kernel_range
Quoted 16 lines · Sebastian Andrzej Siewior
Quoted 8 lines · Chuyi Zhou
flush_tlb_kernel_range()is invoked when kernel memory mapping changes. On x86 platforms without the INVLPGB feature enabled, we need to send IPIs to every online CPU and synchronously wait for them to completedo_kernel_range_flush(). This process can be time-consuming due to factors such as a large number of CPUs or other issues (like interrupts being disabled).flush_tlb_kernel_range()always disables preemption, this may affect the scheduling latency of other tasks on the current CPU.Quoted 6 lines
Previous patch converted
flush_tlb_infofrom per-cpu variable to on-stack variable. Additionally, it's no longer necessary to explicitly disable preemption before calling smp_call*() since they internally handles the preemption logic. Now it's safe to enable preemption duringflush_tlb_kernel_range(). Additionally, inget_flush_tlb_info()useraw_smp_processor_id()to avoid warnings fromcheck_preemption_disabled().
Quoted 9 lines
This is a bit odd. That
smp_processor_id()is there to catch users with enabled CPU migration. The only reason is the accounting done inflush_tlb_func(). Thisraw_smp_processor_id()is only needed inflush_tlb_kernel_range()which does not callflush_tlb_func(). This is only statistics.
kernel_tlb_flush_all()does not need info at all.kernel_tlb_flush_range()needs only start and end.
Agreed, I see the concern about changing get_flush_tlb_info() to use raw_smp_processor_id(). The smp_processor_id() check is useful for the mm TLB flush paths.
For flush_tlb_kernel_range(), however, the kernel range path only needs start/end, and the full kernel flush case does not need flush_tlb_info at all. One possible way to address this is:
- keep get_flush_tlb_info() using smp_processor_id();
- factor the range-to-full-flush decision out of get_flush_tlb_info(),
so flush_tlb_kernel_range() can reuse that logic without building a full flush_tlb_info;
- make flush_tlb_kernel_range() use a small kernel-only range
descriptor containing only start/end for the range case;
- make kernel_tlb_flush_all() take no flush_tlb_info argument.
That would avoid weakening the smp_processor_id() debug check and make the kernel range path use only the data it actually needs.
That said, this does add some extra churn to this patch. Since the main goal of the series is to enable preemption during flush_tlb_kernel_range(), I am also fine with keeping this series smaller if the x86 maintainers prefer, and doing the kernel-range/flush_tlb_info cleanup as a seperate follow-up patch.
Quoted 5 lines
Oh well.
Quoted 1 line
Signed-off-by Chuyi Zhou <[email protected]>Sebastian
friendly ping...
Quoted 165 lines · Chuyi Zhou
Changes in v5:
- Replace "smp: Removeget_cpufromsmp_call_function_any" with a new approach that extracts a common__smp_call_function_single()to safely keep the remote CPU selection and IPI dispatch process within a single preemption-disabled region in [PATCH v5 3/12].
- Fix a typo in comments (s/cpumask_stack/task_mask/) and remove the obsolete "Preemption must be disabled" constraint from the kernel-doc in [PATCH v5 6/12].
- Adjust theWARN_ON_ONCE()validation condition to avoid a false positive warning caused by CPU hotplug races whenuse_cpus_read_lockis false in [PATCH v5 9/12].
- Move thepreemptible()check insmp_call_function_many_cond()from[PATCH v5 4/12] to [PATCH v5 6/12].- Rebase to commit
4ac4d6549a65("sched: Use trace_call__<tp>() to save a static branch").Changes in v4:
- Use task-local IPI cpumask rather than on-stack cpumask in [PATCH v4 4/12] (suggested by sebastian).
- Skip to free csd memory insmpcfd_dead_cpu()to guarantee csd memory access safety, instead of using RCU mechanism in [PATCH v4 5/12] (suggested by sebastian).
- Alignflush_tlb_infowithSMP_CACHE_BYTESto avoid performance degradation caused by unnecessary cache line movements in [PATCH v4 10/12](suggested by sebastian and Nadav).
- Collect Acked-bys and Reviewed-bys.Changes in v3:
- Add benchmarks to measure the performance impact of changingflush_tlb_infoto stack variable in [PATCH v3 10/12] (suggested by peter)
- Adjust thercu_read_unlock()location in [PATCH v3 5/12] (suggested by muchun)
- Useraw_smp_processor_id()to prevent warning[1] fromcheck_preemption_disabled() in [PATCH v3 12/12].- Collect Acked-bys and Reviewed-by.
[1]: https://lore.kernel.org/lkml/[email protected]/T/#mc39999cbeb3f50be176f0903d0fa4075688b073d
Changes in v2:
- Simplify the code comments in [PATCH v2 2/12] (pointed by peter and muchun)
- Adjust the preemption disabling logic insmp_call_function_any()in[PATCH v2 3/12] (suggested by peter). - Use on-stack cpumask only when !CONFIG_CPUMASK_OFFSTACK in [PATCH V2 4/12] (pointed by peter)- Add [PATCH v2 5/12] to replace
migrate_disablewith the rcu mechanism
- Adjust the preemption disabling logic to allowflush_tlb_multi()to be preemptible and migratable in [PATCH v2 11/12]
- Collect Acked-bys and Reviewed-bysIntroduction
============The vast majority of smp_call_function*() callers block until remote CPUs complete the IPI function execution. As smp_call_function*() runs with preemption disabled throughout, scheduling latency increases dramatically with the number of remote CPUs and other factors (such as interrupts being disabled).
On x86-64 architectures, TLB flushes are performed via IPIs; thus, during process exit or when process-mapped pages are reclaimed, numerous IPI operations must be awaited, leading to increased scheduling latency for other threads on the current CPU. In our production environment, we observed IPI wait-induced scheduling latency reaching up to 16ms on a 16-core machine. Our goal is to allow preemption during IPI completion waiting to improve real-time performance.
Background
============In our production environments, latency-sensitive workloads (DPDK) are configured with the highest priority to preempt lower-priority tasks at any time. We discovered that DPDK's wake-up latency is primarily caused by the current CPU having preemption disabled. Therefore, we collected the maximum preemption disabled events within every 30-second interval and then calculated the P50/P99 of these max preemption disabled events:
p50(ns) p99(ns) cpu0 254956 5465050 cpu1 115801 120782 cpu2 43324 72957 cpu3 256637 16723307 cpu4 58979 87237 cpu5 47464 79815 cpu6 48881 81371 cpu7 52263 82294 cpu8 263555 4657713 cpu9 44935 73962 cpu10 37659 65026 cpu11 257008 2706878 cpu12 49669 90006 cpu13 45186 74666 cpu14 60705 83866 cpu15 51311 86885Meanwhile, we have collected the distribution of preemption disabling events exceeding 1ms across different CPUs over several hours(I omitted CPU data that were all zeros):
CPU 1~10ms 10~50ms 50~100ms
cpu0 29 5 0 cpu3 38 13 0 cpu8 34 6 0 cpu11 24 10 0The preemption disabled for several milliseconds or even 10ms+ mostly originates from TLB flush:
@stack[
trace_preempt_on+143 trace_preempt_on+143 preempt_count_sub+67 arch_tlbbatch_flush/flush_tlb_mm_range task_exit/page_reclaim/...]
Further analysis confirms that the majority of the time is consumed in
csd_lock_wait().Now smp_call*() always needs to disable preemption, mainly to protect its internal per‑CPU data structures and synchronize with CPU offline operations. This patchset attempts to make
csd_lock_wait()preemptible, thereby reducing the preemption‑disabled critical section and improving kernel real‑time performance.Effect
======
After applying this patchset, we no longer observe preemption disabled for more than 1ms on the arch_tlbbatch_flush/flush_tlb_mm_range path. The overall P99 of max preemption disabled events in every 30-second is reduced to around 1.5ms (the remaining latency is primarily due to lock contention.
before patch after patch reduced by
----------- -------------- ------------
p99(ns) 16723307 1556034 ~90.70%Chuyi Zhou (12):
smp: Disable preemption explicitly in__csd_lock_wait
smp: Enable preemption early insmp_call_function_single
smp: Refactor remote CPU selection insmp_call_function_any()
smp: Use task-local IPI cpumask insmp_call_function_many_cond()
smp: Alloc percpu csd data insmpcfd_prepare_cpu()only once
smp: Enable preemption early insmp_call_function_many_cond
smp: Removepreempt_disablefromsmp_call_function
smp: Removepreempt_disablefromon_each_cpu_cond_mask
scftorture: Removepreempt_disableinscftorture_invoke_onex86/mm: Moveflush_tlb_infoback to the stack
x86/mm: Enable preemption duringnative_flush_tlb_multix86/mm: Enable preemption duringflush_tlb_kernel_rangearch/x86/include/asm/tlbflush.h | 8 +- arch/x86/kernel/kvm.c | 4 +- arch/x86/mm/tlb.c | 86 ++++++----------- include/linux/sched.h | 6 ++ include/linux/smp.h | 20 ++++ kernel/fork.c | 9 +- kernel/scftorture.c | 13 +-- kernel/smp.c | 157 ++++++++++++++++++++++++-------- 8 files changed, 195 insertions(+), 108 deletions(-)
Quoted 8 lines · Chuyi Zhou
Introduction
============The vast majority of smp_call_function*() callers block until remote CPUs complete the IPI function execution. As smp_call_function*() runs with preemption disabled throughout, scheduling latency increases dramatically with the number of remote CPUs and other factors (such as interrupts being disabled).
…
Thank you for working on this.
I went through the series and I don't see anything wrong with it conceptionally. I made a few comments on how to get smp_call_function_many_cond() a bit improved/ readable but this is about it.
For 1-3, 6-12:
I am not too keen about that smp_processor_id() change, not sure if flush_tlb_kernel_range() could get its own structure. Don't want to make this series too complicated, that is the call of the x86 folks here.
Sebastian
Steven Rostedt
reviewerQuoted 17 lines · On Fri, 22 May 2026 12:57:04 +0200 Sebastian Andrzej Siewior…
Quoted 8 lines · Chuyi Zhou
Introduction
============The vast majority of smp_call_function*() callers block until remote CPUs complete the IPI function execution. As smp_call_function*() runs with preemption disabled throughout, scheduling latency increases dramatically with the number of remote CPUs and other factors (such as interrupts being disabled).
…
Thank you for working on this.
I went through the series and I don't see anything wrong with it conceptionally. I made a few comments on how to getsmp_call_function_many_cond()a bit improved/ readable but this is about it.
Quoted 7 lines
For 1-3, 6-12:
Reviewed-by Sebastian Andrzej Siewior <[email protected]>I am not too keen about that
smp_processor_id()change, not sure ifflush_tlb_kernel_range()could get its own structure. Don't want to make this series too complicated, that is the call of the x86 folks here.
Sashiko may have found some minor issues too:
https://sashiko.dev/#/patchset/20260513124524.2569867-1-zhouchuyi%40bytedance.com
Thanks,
-- Steve
Quoted 3 lines · Steven Rostedt
Sashiko may have found some minor issues too:
https://sashiko.dev/#/patchset/20260513124524.2569867-1-zhouchuyi%40bytedance.com
Didn't see anything substantial. The kmalloc() comment might be worth considering. The sched_numa_find_nth_cpu() is comment is "inherited".
Quoted 2 lines
Thanks,
Sebastian