Skip to contentSkip to conversation

riscv: optimize string functions and add kunit tests

PATCH Applied Feng Jiang 4 participants 21 messages Jan 30 – Apr 3

Subsystems (3)
lore
Share & tools
lore

Feng Jiang

author
#0 lore raw

v7 cover riscv: optimize string functions and add kunit tests

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

The patch series is organized into three parts:
1. Correctness Testing: The first three patches add KUnit test cases for strlen(), strnlen(), and strrchr() to ensure the baseline and optimized versions are functionally correct.
2. Benchmarking Tool: Patches 4 and 5 extend string_kunit to include performance measurement capabilities, allowing for comparative analysis within the KUnit environment.
3. Architectural Optimizations: The final three patches introduce the RISC-V specific assembly implementations.

Following suggestions from Andy Shevchenko, performance benchmarks have been added to string_kunit.c to provide quantifiable evidence of the improvements. Andy provided many specific comments on the implementation of the benchmark logic, which is also inspired by Eric Biggers' crc_benchmark(). Performance was measured in a QEMU TCG (rv64) environment, comparing the generic C implementation with the new RISC-V assembly versions.

Performance Summary (Improvement %):
---------------------------------------------------------------
Function | 16 B (Short) | 512 B (Mid) | 4096 B (Long)
---------------------------------------------------------------

strnlen   |    +72.6%     |   +350.1%    |    +427.5%
strchr    |    +3.6%      |   +3.5%      |    -0.3%
strrchr   |    +5.3%      |   +5.8%      |    +0.8%

---------------------------------------------------------------
The benchmarks can be reproduced by enabling CONFIG_STRING_KUNIT_BENCH and running: ./tools/testing/kunit/kunit.py run --arch=riscv \
--cross_compile=riscv64-linux-gnu- --kunitconfig=my_string.kunitconfig \
--raw_output

The strnlen() implementation leverages the Zbb 'orc.b' instruction and word-at-a-time logic, showing significant gains as the string length increases. For strchr() and strrchr(), the handwritten assembly reduces fixed overhead by eliminating stack frame management. The gain is most prominent on short strings where function call overhead dominates, while the performance converges with the C implementation for longer strings in the TCG environment.

I would like to thank Andy Shevchenko for the suggestion to add benchmarks and for his detailed feedback on the test framework, and Eric Biggers for the benchmarking approach. I am also grateful to Kees Cook for his suggestion to use vmalloc-based over-read detection. I am also grateful to Qingfang Deng for providing the optimized implementation logic for strnlen(). Thanks also to Joel Stanley for testing support and feedback, and to David Laight for his suggestions regarding performance measurement.

Changes:

v7:
- Fix build error in 1/8 (call to undeclared function 'PAGE_ALIGN') as reported by kernel test robot.
- Link to v6: https://lore.kernel.org/all/[email protected]/

v6:
- Use vmalloc() and page-boundary alignment in strlen(), strnlen(), and strrchr() correctness tests to ensure over-reads are detected, as suggested by Kees Cook. Consequently, previous Acked-by and Tested-by tags for these tests have been dropped.
- Added <linux/minmax.h> include.
- Update STRING_BENCH_BUF macro to initialize variables inside the loop.
- Fixed operator positioning and removed redundant blank lines.
- Added warm-up iteration comment.

v5:
- Include <linux/ktime.h> for ktime_get_ns() and <linux/time64.h> for NSEC_PER_SEC.
- Use #if IS_ENABLED(CONFIG_STRING_KUNIT_BENCH) to define the macro instead of using if (!IS_ENABLED(...)) inside the function.
- Declare variables inside for-loops.
- Simplify the for-loop logic in alloc_max_bench_buffer().
- Replace the magic number 1000 with (NSEC_PER_SEC / MEGA) to clarify the bytes/ns to MB/s conversion.

v4:
- Refine formatting and terminology:
- Refer to '\0' as NUL.
- Append parentheses () when referencing function names.
- Ensure trailing commas are present in initializers.
- Reorder local variable declarations to follow the "reverse Xmas tree" style. (Style-only change; kept existing Acked-by tags).
- Improve documentation: Refine comments and commit messages for better clarity.
- Improve readability by using (1 * MEGA) instead of 1000000UL.
- Replace max_t() with max() where type-casting is unnecessary.
- Simplify the return value check for kunit_kzalloc() in alloc_max_bench_buffer().
- Remove redundant NUL-terminator handling in STRING_BENCH_BUF().
- Optimize strnlen() implementation by replacing bleu/bgeu instructions with minu, as suggested by Qingfang Deng.
- Remove incorrect Suggested-by tags from certain patches.
- Drop Tested-by tags for benchmark-related patches due to significant framework changes since v3.
- Re-run all tests and updated the performance data in the documentation.

v3:
- Re-implement benchmark logic inspired by crc_benchmark().
- Add 'len - 2' test case to strnlen correctness tests.
- Incorporate detailed benchmark data into individual commit messages.

v2:
- Refactored lib/string.c to export __generic_* functions and added corresponding functional/performance tests for strnlen, strchr, and strrchr (Andy Shevchenko).
- Replaced magic numbers with STRING_TEST_MAX_LEN etc. (Andy Shevchenko).

v1: Initial submission.

---

Feng Jiang (8):
lib/string_kunit: add correctness test for strlen() lib/string_kunit: add correctness test for strnlen() lib/string_kunit: add correctness test for strrchr() lib/string_kunit: add performance benchmark for strlen() lib/string_kunit: extend benchmarks to strnlen() and chr searches
riscv: lib: add strnlen() implementation
riscv: lib: add strchr() implementation
riscv: lib: add strrchr() implementation

 arch/riscv/include/asm/string.h |   9 ++
 arch/riscv/lib/Makefile         |   3 +
 arch/riscv/lib/strchr.S         |  35 ++++
 arch/riscv/lib/strnlen.S        | 164 +++++++++++++++++++
 arch/riscv/lib/strrchr.S        |  37 +++++
 arch/riscv/purgatory/Makefile   |  11 +-
 lib/Kconfig.debug               |  11 ++
 lib/tests/string_kunit.c        | 274 ++++++++++++++++++++++++++++++++
 8 files changed, 543 insertions(+), 1 deletion(-)
 create mode 100644 arch/riscv/lib/strchr.S
 create mode 100644 arch/riscv/lib/strnlen.S
 create mode 100644 arch/riscv/lib/strrchr.S
Signature · 1 line
2.25.1
author
#1 lore raw

PATCH v7 1/8 lib/string_kunit: add correctness test for strlen()

Add a KUnit test for strlen() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

---
 lib/tests/string_kunit.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
lib/tests/string_kunit.c +30 -0
index f9a8e557ba77..26962118768e 100644
@@ -6,10 +6,12 @@
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
 #include <kunit/test.h>
+#include <linux/mm.h>
 #include <linux/module.h>
 #include <linux/printk.h>
 #include <linux/slab.h>
 #include <linux/string.h>
+#include <linux/vmalloc.h>
 
 #define STRCMP_LARGE_BUF_LEN 2048
 #define STRCMP_CHANGE_POINT 1337
@@ -17,6 +19,9 @@
 #define STRCMP_TEST_EXPECT_LOWER(test, fn, ...) KUNIT_EXPECT_LT(test, fn(__VA_ARGS__), 0)
 #define STRCMP_TEST_EXPECT_GREATER(test, fn, ...) KUNIT_EXPECT_GT(test, fn(__VA_ARGS__), 0)
 
+#define STRING_TEST_MAX_LEN	128
+#define STRING_TEST_MAX_OFFSET	16
+
 static void string_test_memset16(struct kunit *test)
 {
 	unsigned i, j, k;
@@ -104,6 +109,30 @@ static void string_test_memset64(struct kunit *test)
 	}
 }
 
+static void string_test_strlen(struct kunit *test)
+{
+	size_t buf_size;
+	char *buf, *s;
+
+	buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1);
+	buf = vmalloc(buf_size);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
+
+	memset(buf, 'A', buf_size);
+
+	for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) {
+		for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) {
+			s = buf + buf_size - 1 - offset - len;
+			s[len] = '\0';
+			KUNIT_EXPECT_EQ_MSG(test, strlen(s), len,
+				"offset:%zu len:%zu", offset, len);
+			s[len] = 'A';
+		}
+	}
+
+	vfree(buf);
+}
+
 static void string_test_strchr(struct kunit *test)
 {
 	const char *test_string = "abcdefghijkl";
@@ -618,6 +647,7 @@ static struct kunit_case string_test_cases[] = {
 	KUNIT_CASE(string_test_memset16),
 	KUNIT_CASE(string_test_memset32),
 	KUNIT_CASE(string_test_memset64),
+	KUNIT_CASE(string_test_strlen),
 	KUNIT_CASE(string_test_strchr),
 	KUNIT_CASE(string_test_strnchr),
 	KUNIT_CASE(string_test_strspn),
Signature · 1 line
2.25.1
maintainer Reviewed-by on v7 1/8
#2 lore raw

Re: [PATCH v7 1/8] lib/string_kunit: add correctness test for strlen()

Quoted 7 lines · Feng Jiang

Add a KUnit test for strlen() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

Signature · 1 line
Kees Cook
author
#3 lore raw

PATCH v7 2/8 lib/string_kunit: add correctness test for strnlen()

In reply to Feng Jiang

Add a KUnit test for strnlen() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

---
 lib/tests/string_kunit.c | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
lib/tests/string_kunit.c +35 -0
index 26962118768e..1c2d57e05624 100644
@@ -133,6 +133,40 @@ static void string_test_strlen(struct kunit *test)
 	vfree(buf);
 }
 
+static void string_test_strnlen(struct kunit *test)
+{
+	size_t buf_size;
+	char *buf, *s;
+
+	buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1);
+	buf = vmalloc(buf_size);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
+
+	memset(buf, 'A', buf_size);
+
+	for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) {
+		for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) {
+			s = buf + buf_size - 1 - offset - len;
+			s[len] = '\0';
+
+			if (len > 0)
+				KUNIT_EXPECT_EQ(test, strnlen(s, len - 1), len - 1);
+			if (len > 1)
+				KUNIT_EXPECT_EQ(test, strnlen(s, len - 2), len - 2);
+
+			KUNIT_EXPECT_EQ(test, strnlen(s, len), len);
+
+			KUNIT_EXPECT_EQ(test, strnlen(s, len + 1), len);
+			KUNIT_EXPECT_EQ(test, strnlen(s, len + 2), len);
+			KUNIT_EXPECT_EQ(test, strnlen(s, len + 10), len);
+
+			s[len] = 'A';
+		}
+	}
+
+	vfree(buf);
+}
+
 static void string_test_strchr(struct kunit *test)
 {
 	const char *test_string = "abcdefghijkl";
@@ -648,6 +682,7 @@ static struct kunit_case string_test_cases[] = {
 	KUNIT_CASE(string_test_memset32),
 	KUNIT_CASE(string_test_memset64),
 	KUNIT_CASE(string_test_strlen),
+	KUNIT_CASE(string_test_strnlen),
 	KUNIT_CASE(string_test_strchr),
 	KUNIT_CASE(string_test_strnchr),
 	KUNIT_CASE(string_test_strspn),
Signature · 1 line
2.25.1
maintainer Reviewed-by on v7 2/8
#4 lore raw

Re: [PATCH v7 2/8] lib/string_kunit: add correctness test for strnlen()

Quoted 8 lines · Feng Jiang

Add a KUnit test for strnlen() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

Signature · 1 line
Kees Cook
author
#5 lore raw

PATCH v7 3/8 lib/string_kunit: add correctness test for strrchr()

In reply to Feng Jiang

Add a KUnit test for strrchr() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

---
 lib/tests/string_kunit.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
lib/tests/string_kunit.c +31 -0
index 1c2d57e05624..2bed641e1eae 100644
@@ -190,6 +190,36 @@ static void string_test_strchr(struct kunit *test)
 	KUNIT_ASSERT_NULL(test, result);
 }
 
+static void string_test_strrchr(struct kunit *test)
+{
+	size_t buf_size;
+	char *buf, *s;
+
+	buf_size = PAGE_ALIGN(STRING_TEST_MAX_LEN + STRING_TEST_MAX_OFFSET + 1);
+	buf = vmalloc(buf_size);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, buf);
+
+	memset(buf, 'A', buf_size);
+
+	for (size_t offset = 0; offset < STRING_TEST_MAX_OFFSET; offset++) {
+		for (size_t len = 0; len <= STRING_TEST_MAX_LEN; len++) {
+			s = buf + buf_size - 1 - offset - len;
+			s[len] = '\0';
+
+			KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'Z'), NULL);
+
+			if (len > 0)
+				KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'A'), s + len - 1);
+			else
+				KUNIT_EXPECT_PTR_EQ(test, strrchr(s, 'A'), NULL);
+
+			s[len] = 'A';
+		}
+	}
+
+	vfree(buf);
+}
+
 static void string_test_strnchr(struct kunit *test)
 {
 	const char *test_string = "abcdefghijkl";
@@ -685,6 +715,7 @@ static struct kunit_case string_test_cases[] = {
 	KUNIT_CASE(string_test_strnlen),
 	KUNIT_CASE(string_test_strchr),
 	KUNIT_CASE(string_test_strnchr),
+	KUNIT_CASE(string_test_strrchr),
 	KUNIT_CASE(string_test_strspn),
 	KUNIT_CASE(string_test_strcmp),
 	KUNIT_CASE(string_test_strcmp_long_strings),
Signature · 1 line
2.25.1
maintainer Reviewed-by on v7 3/8
#6 lore raw

Re: [PATCH v7 3/8] lib/string_kunit: add correctness test for strrchr()

Quoted 7 lines · Feng Jiang

Add a KUnit test for strrchr() to verify correctness across different string lengths and memory alignments. Use vmalloc() to place the NUL character at the page boundary to ensure over-reads are detected.

Signature · 1 line
Kees Cook
author
#7 lore raw

PATCH v7 4/8 lib/string_kunit: add performance benchmark for strlen()

In reply to Feng Jiang

Introduce a benchmarking framework to the string_kunit test suite to measure the execution efficiency of string functions.

The implementation is inspired by crc_benchmark(), measuring throughput (MB/s) and latency (ns/call) across a range of string lengths. It includes a warm-up phase, disables preemption during measurement, and uses a fixed seed for reproducible results.

This framework allows for comparing different implementations (e.g., generic C vs. architecture-optimized assembly) within the KUnit environment.

Initially, provide a benchmark for strlen().

---
 lib/Kconfig.debug        |  11 +++
 lib/tests/string_kunit.c | 160 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 171 insertions(+)
lib/Kconfig.debug +11 -0
index ba36939fda79..21b058ae815f 100644
@@ -2475,6 +2475,17 @@ config STRING_HELPERS_KUNIT_TEST
 	depends on KUNIT
 	default KUNIT_ALL_TESTS
 
+config STRING_KUNIT_BENCH
+       bool "Benchmark string functions at runtime"
+       depends on STRING_KUNIT_TEST
+       help
+         Enable performance measurement for string functions.
+
+         This measures the execution efficiency of string functions
+         during the KUnit test run.
+
+         If unsure, say N.
+
 config FFS_KUNIT_TEST
 	tristate "KUnit test ffs-family functions at runtime" if !KUNIT_ALL_TESTS
 	depends on KUNIT
lib/tests/string_kunit.c +160 -0

189 lines not on this page · raw message

Signature · 1 line
2.25.1
maintainer Reviewed-by on v7 4/8
#8 lore raw

Re: [PATCH v7 4/8] lib/string_kunit: add performance benchmark for strlen()

Quoted 12 lines · Feng Jiang

Introduce a benchmarking framework to the string_kunit test suite to measure the execution efficiency of string functions.

The implementation is inspired by crc_benchmark(), measuring throughput (MB/s) and latency (ns/call) across a range of string lengths. It includes a warm-up phase, disables preemption during measurement, and uses a fixed seed for reproducible results.

This framework allows for comparing different implementations (e.g., generic C vs. architecture-optimized assembly) within the KUnit environment.

Quoted 5 lines

Initially, provide a benchmark for strlen().

Signature · 1 line
Kees Cook
author
#9 lore raw

PATCH v7 5/8 lib/string_kunit: extend benchmarks to strnlen() and chr searches

In reply to Feng Jiang

Extend the string benchmarking suite to include strnlen(), strchr(), and strrchr().

For character search functions strchr() and strrchr(), the benchmark targets the NUL character. This ensures the entire string is scanned, providing a consistent measure of full-length processing efficiency comparable to strlen().

---
 lib/tests/string_kunit.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
lib/tests/string_kunit.c +18 -0
index 5f6d0409459b..a8d430aa5466 100644
@@ -866,6 +866,21 @@ static void string_bench_strlen(struct kunit *test)
 	STRING_BENCH_BUF(test, buf, len, strlen, buf);
 }
 
+static void string_bench_strnlen(struct kunit *test)
+{
+	STRING_BENCH_BUF(test, buf, len, strnlen, buf, len);
+}
+
+static void string_bench_strchr(struct kunit *test)
+{
+	STRING_BENCH_BUF(test, buf, len, strchr, buf, '\0');
+}
+
+static void string_bench_strrchr(struct kunit *test)
+{
+	STRING_BENCH_BUF(test, buf, len, strrchr, buf, '\0');
+}
+
 static struct kunit_case string_test_cases[] = {
 	KUNIT_CASE(string_test_memset16),
 	KUNIT_CASE(string_test_memset32),
@@ -892,6 +907,9 @@ static struct kunit_case string_test_cases[] = {
 	KUNIT_CASE(string_test_memtostr),
 	KUNIT_CASE(string_test_strends),
 	KUNIT_CASE(string_bench_strlen),
+	KUNIT_CASE(string_bench_strnlen),
+	KUNIT_CASE(string_bench_strchr),
+	KUNIT_CASE(string_bench_strrchr),
 	{}
 };
 
Signature · 1 line
2.25.1
maintainer Reviewed-by on v7 5/8
#10 lore raw

Re: [PATCH v7 5/8] lib/string_kunit: extend benchmarks to strnlen() and chr searches

Quoted 11 lines · Feng Jiang

Extend the string benchmarking suite to include strnlen(), strchr(), and strrchr().

For character search functions strchr() and strrchr(), the benchmark targets the NUL character. This ensures the entire string is scanned, providing a consistent measure of full-length processing efficiency comparable to strlen().

Signature · 1 line
Kees Cook
author
#11 lore raw

PATCH v7 6/8 riscv: lib: add strnlen() implementation

In reply to Feng Jiang

Add an optimized strnlen() implementation for RISC-V. This version includes a generic optimization and a Zbb-powered optimization using the 'orc.b' instruction, derived from the strlen() implementation.

Benchmark results (QEMU TCG, rv64):

  Length | Original (MB/s) | Optimized (MB/s) | Improvement
  -------|-----------------|------------------|------------
  16 B   | 179             | 309              | +72.6%
  512 B  | 347             | 1562             | +350.1%
  4096 B | 356             | 1878             | +427.5%
---
 arch/riscv/include/asm/string.h |   3 +
 arch/riscv/lib/Makefile         |   1 +
 arch/riscv/lib/strnlen.S        | 164 ++++++++++++++++++++++++++++++++
 arch/riscv/purgatory/Makefile   |   5 +-
 4 files changed, 172 insertions(+), 1 deletion(-)
 create mode 100644 arch/riscv/lib/strnlen.S
arch/riscv/include/asm/string.h +3 -0
index 5ba77f60bf0b..16634d67c217 100644
@@ -28,6 +28,9 @@ extern asmlinkage __kernel_size_t strlen(const char *);
 
 #define __HAVE_ARCH_STRNCMP
 extern asmlinkage int strncmp(const char *cs, const char *ct, size_t count);
+
+#define __HAVE_ARCH_STRNLEN
+extern asmlinkage __kernel_size_t strnlen(const char *, size_t);
 #endif
 
 /* For those files which don't want to check by kasan. */
arch/riscv/lib/Makefile +1 -0
index bbc031124974..0969d8136df0 100644
@@ -7,6 +7,7 @@ ifeq ($(CONFIG_KASAN_GENERIC)$(CONFIG_KASAN_SW_TAGS),)
 lib-y			+= strcmp.o
 lib-y			+= strlen.o
 lib-y			+= strncmp.o
+lib-y			+= strnlen.o
 endif
 lib-y			+= csum.o
 ifeq ($(CONFIG_MMU), y)
arch/riscv/lib/strnlen.S new file +164 -0

164 lines not on this page · raw message

arch/riscv/purgatory/Makefile +4 -1
index 530e497ca2f9..d7c0533108be 100644
@@ -2,7 +2,7 @@
 
 purgatory-y := purgatory.o sha256.o entry.o string.o ctype.o memcpy.o memset.o
 ifeq ($(CONFIG_KASAN_GENERIC)$(CONFIG_KASAN_SW_TAGS),)
-purgatory-y += strcmp.o strlen.o strncmp.o
+purgatory-y += strcmp.o strlen.o strncmp.o strnlen.o
 endif
 
 targets += $(purgatory-y)
@@ -32,6 +32,9 @@ $(obj)/strncmp.o: $(srctree)/arch/riscv/lib/strncmp.S FORCE
 $(obj)/sha256.o: $(srctree)/lib/crypto/sha256.c FORCE
 	$(call if_changed_rule,cc_o_c)
 
+$(obj)/strnlen.o: $(srctree)/arch/riscv/lib/strnlen.S FORCE
+	$(call if_changed_rule,as_o_S)
+
 CFLAGS_sha256.o := -D__DISABLE_EXPORTS -D__NO_FORTIFY
 CFLAGS_string.o := -D__DISABLE_EXPORTS
 CFLAGS_ctype.o := -D__DISABLE_EXPORTS
Signature · 1 line
2.25.1
author
#12 lore raw

PATCH v7 7/8 riscv: lib: add strchr() implementation

In reply to Feng Jiang

Add an assembly implementation of strchr() for RISC-V.

By eliminating stack frame management (prologue/epilogue) and optimizing the function entries, the assembly version provides significant relative gains for short strings where the fixed overhead of the C function is most prominent. As string length increases, performance converges with the generic C implementation.

Benchmark results (QEMU TCG, rv64):

  Length | Original (MB/s) | Optimized (MB/s) | Improvement
  -------|-----------------|------------------|------------
  1 B    | 21              | 22               | +4.8%
  7 B    | 113             | 121              | +7.1%
  16 B   | 195             | 202              | +3.6%
  512 B  | 376             | 389              | +3.5%
  4096 B | 394             | 393              | -0.3%
---
 arch/riscv/include/asm/string.h |  3 +++
 arch/riscv/lib/Makefile         |  1 +
 arch/riscv/lib/strchr.S         | 35 +++++++++++++++++++++++++++++++++
 arch/riscv/purgatory/Makefile   |  5 ++++-
 4 files changed, 43 insertions(+), 1 deletion(-)
 create mode 100644 arch/riscv/lib/strchr.S
arch/riscv/include/asm/string.h +3 -0
index 16634d67c217..ca3ade82b124 100644
@@ -31,6 +31,9 @@ extern asmlinkage int strncmp(const char *cs, const char *ct, size_t count);
 
 #define __HAVE_ARCH_STRNLEN
 extern asmlinkage __kernel_size_t strnlen(const char *, size_t);
+
+#define __HAVE_ARCH_STRCHR
+extern asmlinkage char *strchr(const char *, int);
 #endif
 
 /* For those files which don't want to check by kasan. */
arch/riscv/lib/Makefile +1 -0
index 0969d8136df0..b7f804dce1c3 100644
@@ -8,6 +8,7 @@ lib-y			+= strcmp.o
 lib-y			+= strlen.o
 lib-y			+= strncmp.o
 lib-y			+= strnlen.o
+lib-y			+= strchr.o
 endif
 lib-y			+= csum.o
 ifeq ($(CONFIG_MMU), y)
arch/riscv/lib/strchr.S new file +35 -0
new file mode 100644
index 000000000000..48c3a9da53e3
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+/*
+ * Copyright (C) 2025 Feng Jiang <[email protected]>
+ */
+
+#include <linux/linkage.h>
+#include <asm/asm.h>
+
+/* char *strchr(const char *s, int c) */
+SYM_FUNC_START(strchr)
+	/*
+	 * Parameters
+	 *   a0 - The string to be searched
+	 *   a1 - The character to search for
+	 *
+	 * Returns
+	 *   a0 - Address of first occurrence of 'c' or 0
+	 *
+	 * Clobbers
+	 *   t0
+	 */
+	andi	a1, a1, 0xff
+1:
+	lbu	t0, 0(a0)
+	beq	t0, a1, 2f
+	addi	a0, a0, 1
+	bnez	t0, 1b
+	li	a0, 0
+2:
+	ret
+SYM_FUNC_END(strchr)
+
+SYM_FUNC_ALIAS_WEAK(__pi_strchr, strchr)
+EXPORT_SYMBOL(strchr)
arch/riscv/purgatory/Makefile +4 -1
index d7c0533108be..e7b3d748c913 100644
@@ -2,7 +2,7 @@
 
 purgatory-y := purgatory.o sha256.o entry.o string.o ctype.o memcpy.o memset.o
 ifeq ($(CONFIG_KASAN_GENERIC)$(CONFIG_KASAN_SW_TAGS),)
-purgatory-y += strcmp.o strlen.o strncmp.o strnlen.o
+purgatory-y += strcmp.o strlen.o strncmp.o strnlen.o strchr.o
 endif
 
 targets += $(purgatory-y)
@@ -35,6 +35,9 @@ $(obj)/sha256.o: $(srctree)/lib/crypto/sha256.c FORCE
 $(obj)/strnlen.o: $(srctree)/arch/riscv/lib/strnlen.S FORCE
 	$(call if_changed_rule,as_o_S)
 
+$(obj)/strchr.o: $(srctree)/arch/riscv/lib/strchr.S FORCE
+	$(call if_changed_rule,as_o_S)
+
 CFLAGS_sha256.o := -D__DISABLE_EXPORTS -D__NO_FORTIFY
 CFLAGS_string.o := -D__DISABLE_EXPORTS
 CFLAGS_ctype.o := -D__DISABLE_EXPORTS
Signature · 1 line
2.25.1
author
#13 lore raw

PATCH v7 8/8 riscv: lib: add strrchr() implementation

In reply to Feng Jiang

Add an assembly implementation of strrchr() for RISC-V.

This implementation minimizes instruction count and avoids unnecessary memory access to the stack. The performance benefits are most visible on small workloads (1-16 bytes) where the architectural savings in function overhead outweigh the execution time of the scan loop.

Benchmark results (QEMU TCG, rv64):

  Length | Original (MB/s) | Optimized (MB/s) | Improvement
  -------|-----------------|------------------|------------
  1 B    | 20              | 21               | +5.0%
  7 B    | 111             | 120              | +8.1%
  16 B   | 189             | 199              | +5.3%
  512 B  | 361             | 382              | +5.8%
  4096 B | 388             | 391              | +0.8%
---
 arch/riscv/include/asm/string.h |  3 +++
 arch/riscv/lib/Makefile         |  1 +
 arch/riscv/lib/strrchr.S        | 37 +++++++++++++++++++++++++++++++++
 arch/riscv/purgatory/Makefile   |  5 ++++-
 4 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 arch/riscv/lib/strrchr.S
arch/riscv/include/asm/string.h +3 -0
index ca3ade82b124..764ffe8f6479 100644
@@ -34,6 +34,9 @@ extern asmlinkage __kernel_size_t strnlen(const char *, size_t);
 
 #define __HAVE_ARCH_STRCHR
 extern asmlinkage char *strchr(const char *, int);
+
+#define __HAVE_ARCH_STRRCHR
+extern asmlinkage char *strrchr(const char *, int);
 #endif
 
 /* For those files which don't want to check by kasan. */
arch/riscv/lib/Makefile +1 -0
index b7f804dce1c3..735d0b665536 100644
@@ -9,6 +9,7 @@ lib-y			+= strlen.o
 lib-y			+= strncmp.o
 lib-y			+= strnlen.o
 lib-y			+= strchr.o
+lib-y			+= strrchr.o
 endif
 lib-y			+= csum.o
 ifeq ($(CONFIG_MMU), y)
arch/riscv/lib/strrchr.S new file +37 -0
new file mode 100644
index 000000000000..ac58b20ca21d
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+/*
+ * Copyright (C) 2025 Feng Jiang <[email protected]>
+ */
+
+#include <linux/linkage.h>
+#include <asm/asm.h>
+
+/* char *strrchr(const char *s, int c) */
+SYM_FUNC_START(strrchr)
+	/*
+	 * Parameters
+	 *	a0 - The string to be searched
+	 *	a1 - The character to seaerch for
+	 *
+	 * Returns
+	 *	a0 - Address of last occurrence of 'c' or 0
+	 *
+	 * Clobbers
+	 *	t0, t1
+	 */
+	andi	a1, a1, 0xff
+	mv	t1, a0
+	li	a0, 0
+1:
+	lbu	t0, 0(t1)
+	bne	t0, a1, 2f
+	mv	a0, t1
+2:
+	addi	t1, t1, 1
+	bnez	t0, 1b
+	ret
+SYM_FUNC_END(strrchr)
+
+SYM_FUNC_ALIAS_WEAK(__pi_strrchr, strrchr)
+EXPORT_SYMBOL(strrchr)
arch/riscv/purgatory/Makefile +4 -1
index e7b3d748c913..b0358a78f11a 100644
@@ -2,7 +2,7 @@
 
 purgatory-y := purgatory.o sha256.o entry.o string.o ctype.o memcpy.o memset.o
 ifeq ($(CONFIG_KASAN_GENERIC)$(CONFIG_KASAN_SW_TAGS),)
-purgatory-y += strcmp.o strlen.o strncmp.o strnlen.o strchr.o
+purgatory-y += strcmp.o strlen.o strncmp.o strnlen.o strchr.o strrchr.o
 endif
 
 targets += $(purgatory-y)
@@ -38,6 +38,9 @@ $(obj)/strnlen.o: $(srctree)/arch/riscv/lib/strnlen.S FORCE
 $(obj)/strchr.o: $(srctree)/arch/riscv/lib/strchr.S FORCE
 	$(call if_changed_rule,as_o_S)
 
+$(obj)/strrchr.o: $(srctree)/arch/riscv/lib/strrchr.S FORCE
+	$(call if_changed_rule,as_o_S)
+
 CFLAGS_sha256.o := -D__DISABLE_EXPORTS -D__NO_FORTIFY
 CFLAGS_string.o := -D__DISABLE_EXPORTS
 CFLAGS_ctype.o := -D__DISABLE_EXPORTS
Signature · 1 line
2.25.1
maintainer
#14 lore raw
In reply to Feng Jiang
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

I'm happy with the Kunit elements here, so unless Andy has other feedback, please feel free to take this via the riscv tree. (Or if riscv maintainers would prefer, I can take it via string.)

Thanks for working on this!

-Kees

Signature · 1 line
Kees Cook
#15 lore raw
Quoted 10 lines · Kees Cook
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

I'm happy with the Kunit elements here, so unless Andy has other feedback, please feel free to take this via the riscv tree. (Or if riscv maintainers would prefer, I can take it via string.)

I have an impression that I already gave some tag. Why aren't not here?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
author
#16 lore raw
Quoted 8 lines · Andy Shevchenko
Quoted 7 lines · Kees Cook
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

Quoted 6 lines
Quoted 3 lines

I'm happy with the Kunit elements here, so unless Andy has other feedback, please feel free to take this via the riscv tree. (Or if riscv maintainers would prefer, I can take it via string.)

I have an impression that I already gave some tag. Why aren't not here?

I apologize for the confusion.

In v6, following Kees Cook's suggestion, I introduced a significant change to the correctness test logic—using vmalloc() and page-boundary alignment to detect over-reads. Since this part of the code was substantially rewritten, I felt it was more responsible to drop the previous Acked-by and Tested-by tags for the affected patches.

I would be very grateful if you could take a quick look at the new test implementation in v7. If you are satisfied with the changes, I would be honored to add your tags back.

Signature · 2 lines
With Best Regards,
Feng Jiang
author
#17 lore raw
In reply to Kees Cook
Quoted 7 lines · Kees Cook
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

Quoted 5 lines

I'm happy with the Kunit elements here, so unless Andy has other feedback, please feel free to take this via the riscv tree. (Or if riscv maintainers would prefer, I can take it via string.)

Thanks for working on this!

Thank you very much for your review and the previous suggestions for improvement. I truly appreciate your patience and guidance throughout this process!

Signature · 2 lines
With Best Regards,
Feng Jiang
author
#18 lore raw
In reply to Feng Jiang
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

Hi Palmer,

Just a gentle ping on this v7 series.

Kees is happy for this to go through the riscv tree. I've also followed up with Andy regarding the tags for v7 on the mailing list.

Is there anything else needed for this series to be picked up?

Signature · 2 lines
With Best Regards,
Feng Jiang
author
#19 lore raw
In reply to Feng Jiang
Quoted 5 lines · Feng Jiang

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

Hi Paul,

I'm very sorry, I dropped you from the 'To' list by mistake in v7. Adding you back now for visibility.

Signature · 2 lines
With Best Regards,
Feng Jiang
#20 lore raw
In reply to Feng Jiang
This series was applied to riscv/linux.git (for-next) by Paul Walmsley <[email protected]>:

Hello:

This series was applied to riscv/linux.git (for-next) by Paul Walmsley <[email protected]>:

Quoted 16 lines · On Fri, 30 Jan 2026 10:50:10 +0800 you wrote:

This series provides optimized implementations of strnlen(), strchr(), and strrchr() for the RISC-V architecture. The strnlen() implementation is derived from the existing optimized strlen(). For strchr() and strrchr(), the current versions use simple byte-by-byte assembly logic, which will serve as a baseline for future Zbb-based optimizations.

The patch series is organized into three parts:
1. Correctness Testing: The first three patches add KUnit test cases for strlen(), strnlen(), and strrchr() to ensure the baseline and optimized versions are functionally correct.
2. Benchmarking Tool: Patches 4 and 5 extend string_kunit to include performance measurement capabilities, allowing for comparative analysis within the KUnit environment.
3. Architectural Optimizations: The final three patches introduce the RISC-V specific assembly implementations.

Quoted 1 line

[...]

Here is the summary with links:
- [v7,1/8] lib/string_kunit: add correctness test for strlen()

    https://git.kernel.org/riscv/c/abd6819bbf5b
  - [v7,2/8] lib/string_kunit: add correctness test for strnlen()
    https://git.kernel.org/riscv/c/31a361f466a2
  - [v7,3/8] lib/string_kunit: add correctness test for strrchr()
    https://git.kernel.org/riscv/c/68768cdba710
  - [v7,4/8] lib/string_kunit: add performance benchmark for strlen()
    https://git.kernel.org/riscv/c/54a7a0ca4b60
  - [v7,5/8] lib/string_kunit: extend benchmarks to strnlen() and chr searches
    https://git.kernel.org/riscv/c/d52a2222768b
  - [v7,6/8] riscv: lib: add strnlen() implementation
    https://git.kernel.org/riscv/c/018ffd93d25f
  - [v7,7/8] riscv: lib: add strchr() implementation
    https://git.kernel.org/riscv/c/bf74efe28f7c
  - [v7,8/8] riscv: lib: add strrchr() implementation
    https://git.kernel.org/riscv/c/3dcf058583a1

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html