mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Cong Wang <xiyou.wangcong@gmail.com>
To: linux-kernel@vger.kernel.org, Paul Walmsley <pjw@kernel.org>,
	Palmer Dabbelt <palmer@dabbelt.com>,
	Albert Ou <aou@eecs.berkeley.edu>,
	Alexandre Ghiti <alex@ghiti.fr>
Cc: Andy Chiu <tchiu@tenstorrent.com>,
	daichengrong <daichengrong@iscas.ac.cn>,
	Troy Mitchell <troy@kernel.org>,
	linux-riscv@lists.infradead.org, Cong Wang <cwang@multikernel.io>
Subject: [RFC PATCH 2/2] riscv: lib: Use the vector registers for large memcpy()
Date: Tue,  1 Dec 2026 20:03:44 -0800	[thread overview]
Message-ID: <20261202040344.1259264-3-xiyou.wangcong@gmail.com> (raw)
In-Reply-To: <20261202040344.1259264-1-xiyou.wangcong@gmail.com>

From: Cong Wang <cwang@multikernel.io>

Copy with the vector registers when a memcpy() is large enough to pay for
a kernel-mode vector section. memmove() and memset() are left alone.

On a SpacemiT A100 core (1024-bit vectors), hot buffers, ns per copy:

            kernel thread         one copy per system call
  bytes     scalar    vector      scalar    vector
   4096        337       338         365       368
   8192        657       498         714       683
  16384       1304       775        1830       983
  65536       8240      2674        7780      2875
 262144      32400     10180       31800     10380
1048576     131700     45400      131800     47500

The first two columns are copies in a loop from a kernel thread, which
has no user vector state. The last two are from a task that uses the
vector registers itself. A system call leaves nothing of the user's to
save, but a page fault or an interrupt from user space does: there the
state has to be saved for the copy and loaded again on the return to
user space. That takes about 230 ns on this core, more than the 160 ns
the vector copy gains at 8192 bytes and less than the 530 ns it gains at
16384. Hence two thresholds: RISCV_ISA_V_MEMCPY_THRESHOLD, a build-time
option like the one for user copies, which defaults to 8192, and twice
that when the user's state is live in the registers.

The gain depends on the vector length. The same test on a SpacemiT X100
core (256-bit vectors):

            kernel thread         one copy per system call
  bytes     scalar    vector      scalar    vector
   4096        249       250         250       264
   8192        487       497         491       578
  16384        955       891         981      1074
  65536       3977      3769        5200      4825
 262144      27600     21200       27700     21900
1048576     110900     85100      109600     86400

There the vector copy pays from 16384 bytes in a kernel thread and from
65536 in a system call, so a kernel built for such cores wants a higher
RISCV_ISA_V_MEMCPY_THRESHOLD.

memcpy() gets a short entry sequence, patched in only when the vector
extension is present, that sends copies of at least the first threshold to
a helper. Smaller copies pay about 1 ns for it here. Cores that have only
XTheadVector keep the scalar copy. The helper falls back to the scalar code
unless it runs in task context with interrupts on and no kernel-mode vector
section is active already. A softirq can interrupt a task between the load
and the store of an update of the status word in its user register frame,
for example in fstate_save(). A vector section updates that word too, and
the stale store would lose the task's vector state. Interrupts off is where
entry code and lock debugging run, and a nested section would have to save
the outer one's registers.

Vectorized memcpy() was part of the kernel-mode vector series and was
dropped from it [1] because kernel_vector_begin() changes state in the
task struct: the copy of the task struct in fork then captured a
softirq state that lockdep rejected. So a copy that overlaps the current
task struct, the user register frame on its stack or the task's vector
save areas, which are what a vector section writes to, stays scalar as
well.

Long copies are split into sections of 256 KB so that softirqs or a
reschedule are not held off for longer than that takes.

The purgatory builds memcpy.S without the entry sequence, as it has no
alternatives patching.

Link: https://lore.kernel.org/linux-riscv/20231229143627.22898-1-andy.chiu@sifive.com/ [1]
Signed-off-by: Cong Wang <cwang@multikernel.io>
Reviewed-by: Troy Mitchell <troy@kernel.org>
---
 arch/riscv/Kconfig                      |  10 +++
 arch/riscv/include/asm/asm-prototypes.h |   4 +
 arch/riscv/lib/Makefile                 |   1 +
 arch/riscv/lib/memcpy.S                 |  12 +++
 arch/riscv/lib/memcpy_vector.S          |  17 ++++
 arch/riscv/lib/riscv_v_helpers.c        | 102 ++++++++++++++++++++++--
 arch/riscv/purgatory/Makefile           |   2 +
 7 files changed, 143 insertions(+), 5 deletions(-)
 create mode 100644 arch/riscv/lib/memcpy_vector.S

diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig
index d2db8f40c616..88b2b9f8a88b 100644
--- a/arch/riscv/Kconfig
+++ b/arch/riscv/Kconfig
@@ -680,6 +680,16 @@ config RISCV_ISA_V_UCOPY_THRESHOLD
 	  Prefer using vectorized copy_to_user()/copy_from_user() when the
 	  workload size exceeds this value.
 
+config RISCV_ISA_V_MEMCPY_THRESHOLD
+	int "Threshold size for vectorized memcpy()"
+	depends on RISCV_ISA_V
+	range 1 1073741823
+	default 8192
+	help
+	  Prefer using vectorized memcpy() when the copy is at least this
+	  large. Twice this size is required when the user's Vector state
+	  has to be saved for the copy.
+
 config RISCV_ISA_V_PREEMPTIVE
 	bool "Run kernel-mode Vector with kernel preemption"
 	depends on PREEMPTION
diff --git a/arch/riscv/include/asm/asm-prototypes.h b/arch/riscv/include/asm/asm-prototypes.h
index a0ca9efff267..40988bf9bbf9 100644
--- a/arch/riscv/include/asm/asm-prototypes.h
+++ b/arch/riscv/include/asm/asm-prototypes.h
@@ -15,6 +15,10 @@ long long __ashlti3(long long a, int b);
 
 #ifdef CONFIG_RISCV_ISA_V
 
+asmlinkage void *__memcpy_scalar(void *dst, const void *src, size_t n);
+asmlinkage void *enter_vector_memcpy(void *dst, const void *src, size_t n);
+asmlinkage void __asm_vector_memcpy(void *dst, const void *src, size_t n);
+
 #ifdef CONFIG_MMU
 asmlinkage int enter_vector_usercopy(void *dst, void *src, size_t n, bool enable_sum);
 #endif /* CONFIG_MMU  */
diff --git a/arch/riscv/lib/Makefile b/arch/riscv/lib/Makefile
index f668b98970bd..c05db41d60c4 100644
--- a/arch/riscv/lib/Makefile
+++ b/arch/riscv/lib/Makefile
@@ -21,3 +21,4 @@ lib-$(CONFIG_64BIT)	+= tishift.o
 lib-$(CONFIG_RISCV_ISA_ZICBOZ)	+= clear_page.o
 obj-$(CONFIG_FUNCTION_ERROR_INJECTION) += error-inject.o
 lib-$(CONFIG_RISCV_ISA_V)	+= riscv_v_helpers.o
+lib-$(CONFIG_RISCV_ISA_V)	+= memcpy_vector.o
diff --git a/arch/riscv/lib/memcpy.S b/arch/riscv/lib/memcpy.S
index 6f1d3681fecf..6a33557e1d12 100644
--- a/arch/riscv/lib/memcpy.S
+++ b/arch/riscv/lib/memcpy.S
@@ -5,6 +5,8 @@
 
 #include <linux/linkage.h>
 #include <asm/asm.h>
+#include <asm/hwcap.h>
+#include <asm/alternative-macros.h>
 
 /* void *memcpy(void *, const void *, size_t) */
 SYM_FUNC_START(__memcpy_scalar)
@@ -105,7 +107,17 @@ SYM_FUNC_START(__memcpy_scalar)
 6:
 	ret
 SYM_FUNC_END(__memcpy_scalar)
+
+#if defined(CONFIG_RISCV_ISA_V) && !defined(RISCV_PURGATORY)
+SYM_FUNC_START(__memcpy)
+	ALTERNATIVE("j __memcpy_scalar", "nop", 0, RISCV_ISA_EXT_ZVE32X, CONFIG_RISCV_ISA_V)
+	li	t0, CONFIG_RISCV_ISA_V_MEMCPY_THRESHOLD
+	bltu	a2, t0, __memcpy_scalar
+	tail	enter_vector_memcpy
+SYM_FUNC_END(__memcpy)
+#else
 SYM_FUNC_ALIAS(__memcpy, __memcpy_scalar)
+#endif
 SYM_FUNC_ALIAS_WEAK(memcpy, __memcpy)
 SYM_FUNC_ALIAS(__pi_memcpy, __memcpy_scalar)
 SYM_FUNC_ALIAS(__pi___memcpy, __memcpy_scalar)
diff --git a/arch/riscv/lib/memcpy_vector.S b/arch/riscv/lib/memcpy_vector.S
new file mode 100644
index 000000000000..2b7e83b96059
--- /dev/null
+++ b/arch/riscv/lib/memcpy_vector.S
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include <linux/linkage.h>
+#include <asm/asm.h>
+
+/* void __asm_vector_memcpy(void *dst, const void *src, size_t len) */
+SYM_FUNC_START(__asm_vector_memcpy)
+1:
+	vsetvli	t0, a2, e8, m8, ta, ma
+	vle8.v	v0, (a1)
+	sub	a2, a2, t0
+	add	a1, a1, t0
+	vse8.v	v0, (a0)
+	add	a0, a0, t0
+	bnez	a2, 1b
+	ret
+SYM_FUNC_END(__asm_vector_memcpy)
diff --git a/arch/riscv/lib/riscv_v_helpers.c b/arch/riscv/lib/riscv_v_helpers.c
index 7bbdfc6d4552..2f7fc4f9fa9d 100644
--- a/arch/riscv/lib/riscv_v_helpers.c
+++ b/arch/riscv/lib/riscv_v_helpers.c
@@ -4,14 +4,106 @@
  * Author: Andy Chiu <andy.chiu@sifive.com>
  */
 #include <linux/linkage.h>
-#include <asm/asm.h>
+#include <linux/minmax.h>
+#include <linux/preempt.h>
+#include <linux/sched.h>
+#include <linux/sizes.h>
+#include <linux/string.h>
 
-#include <asm/vector.h>
+#include <asm/asm.h>
+#include <asm/asm-prototypes.h>
 #include <asm/simd.h>
+#include <asm/vector.h>
 
-#ifdef CONFIG_MMU
-#include <asm/asm-prototypes.h>
-#endif
+/*
+ * A vector section that is not preemptible keeps softirqs off, or preemption
+ * on PREEMPT_RT. Bounds how long one copy does that.
+ */
+#define VECTOR_MEMCPY_SECTION	SZ_256K
+
+/*
+ * Giving up the user's vector state and bringing it back on the return to
+ * user space costs about as much as the vector section itself.
+ */
+#define VECTOR_MEMCPY_USER_THRESHOLD	(2 * CONFIG_RISCV_ISA_V_MEMCPY_THRESHOLD)
+
+static bool memcpy_overlaps(const void *p, size_t n, const void *area, size_t size)
+{
+	return area && p < area + size && area < p + n;
+}
+
+/*
+ * kernel_vector_begin() and kernel_vector_end() write to the task struct,
+ * to the user register frame on the task's stack and to the task's vector
+ * save areas. A copy of those would read or overwrite that state while it
+ * is in flux.
+ */
+static bool touches_vector_state(const void *p, size_t n)
+{
+	struct thread_struct *thread = &current->thread;
+
+	return memcpy_overlaps(p, n, current, sizeof(*current)) ||
+	       memcpy_overlaps(p, n, task_pt_regs(current), sizeof(struct pt_regs)) ||
+	       memcpy_overlaps(p, n, thread->vstate.datap, riscv_v_vsize) ||
+	       memcpy_overlaps(p, n, thread->kernel_vstate.datap, riscv_v_vsize);
+}
+
+/* The registers hold user state that a vector section has to save. */
+static bool user_vstate_is_live(void)
+{
+	struct pt_regs *regs = task_pt_regs(current);
+
+	return riscv_v_vstate_query(regs) &&
+	       !__riscv_v_vstate_check(regs->status, INITIAL) &&
+	       !test_thread_flag(TIF_RISCV_V_DEFER_RESTORE);
+}
+
+static bool memcpy_may_use_vector(const void *dst, const void *src, size_t n)
+{
+	/*
+	 * A softirq can interrupt a task between the load and the store of
+	 * an update of regs->status, which a vector section updates too.
+	 * The stale store then loses the task's vector state.
+	 *
+	 * Interrupts off is allowed for kernel-mode vector, but it is where
+	 * entry code and lock debugging run, which must not end up here.
+	 *
+	 * Any vector flag means that the registers are spoken for: by a
+	 * vector section, preemptible or not, that this copy runs inside
+	 * or has interrupted, or by a KVM vcpu. Using them would mean
+	 * saving theirs first.
+	 */
+	if (!in_task() || irqs_disabled() || riscv_v_flags())
+		return false;
+
+	if (n < VECTOR_MEMCPY_USER_THRESHOLD && user_vstate_is_live())
+		return false;
+
+	return !touches_vector_state(dst, n) && !touches_vector_state(src, n);
+}
+
+/* Reached from memcpy() for copies of RISCV_ISA_V_MEMCPY_THRESHOLD or more. */
+asmlinkage notrace void *enter_vector_memcpy(void *dst, const void *src, size_t n)
+{
+	void *ret = dst;
+
+	if (!memcpy_may_use_vector(dst, src, n))
+		return __memcpy_scalar(dst, src, n);
+
+	do {
+		size_t len = min(n, VECTOR_MEMCPY_SECTION);
+
+		kernel_vector_begin();
+		__asm_vector_memcpy(dst, src, len);
+		kernel_vector_end();
+
+		dst += len;
+		src += len;
+		n -= len;
+	} while (n);
+
+	return ret;
+}
 
 #ifdef CONFIG_MMU
 size_t riscv_v_usercopy_threshold = CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD;
diff --git a/arch/riscv/purgatory/Makefile b/arch/riscv/purgatory/Makefile
index b0358a78f11a..cde246e846f3 100644
--- a/arch/riscv/purgatory/Makefile
+++ b/arch/riscv/purgatory/Makefile
@@ -44,6 +44,8 @@ $(obj)/strrchr.o: $(srctree)/arch/riscv/lib/strrchr.S FORCE
 CFLAGS_sha256.o := -D__DISABLE_EXPORTS -D__NO_FORTIFY
 CFLAGS_string.o := -D__DISABLE_EXPORTS
 CFLAGS_ctype.o := -D__DISABLE_EXPORTS
+# The purgatory has no alternatives patching and no kernel-mode vector.
+AFLAGS_memcpy.o := -DRISCV_PURGATORY
 
 # When profile-guided optimization is enabled, llvm emits two different
 # overlapping text sections, which is not supported by kexec. Remove profile
-- 
2.43.0


      parent reply	other threads:[~2026-12-02  4:03 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  4:03 [RFC PATCH 0/2] riscv: " Cong Wang
2026-12-02  4:03 ` [RFC PATCH 1/2] riscv: lib: Give the scalar memcpy() body a symbol of its own Cong Wang
2026-12-02  4:03 ` Cong Wang [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261202040344.1259264-3-xiyou.wangcong@gmail.com \
    --to=xiyou.wangcong@gmail.com \
    --cc=alex@ghiti.fr \
    --cc=aou@eecs.berkeley.edu \
    --cc=cwang@multikernel.io \
    --cc=daichengrong@iscas.ac.cn \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-riscv@lists.infradead.org \
    --cc=palmer@dabbelt.com \
    --cc=pjw@kernel.org \
    --cc=tchiu@tenstorrent.com \
    --cc=troy@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®