Skip to contentSkip to conversation

platform/chrome: Add Kunit tests for protocol device drivers

RFC PATCH In review Tzung-Bi Shih 2 participants 12 messages May 20, 2025 – Jul 1, 2025

Subsystems (7)
Kbuild Kselftest Tracing ftrace +3 more subsystems
lore
Share & tools
lore

Tzung-Bi Shih

author maintainer
#0 lore raw

cover platform/chrome: Add Kunit tests for protocol device drivers

The protocol device drivers under drivers/platform/chrome/ are responsible to communicate to the ChromeOS EC (Embedded Controller). They need to pack the data in a pre-defined format and check if the EC responds accordingly.

The series adds some fundamental unit tests for the protocol. It calls the .cmd_xfer() and .pkt_xfer() callbacks (which are the most crucial parts for the protocol), mocks the rest of the system, and checks if the interactions are all correct.

The series isn't ready for landing. It's more like a PoC for the binary-level function redirection and its use cases.

The 1st patch adds ftrace stub which is originally from [1][2]. There is no follow-up discussion about the ftrace stub. As a result, the patch is still on the mailing list.

The 2nd patch adds Kunit tests for cros_ec_i2c. It relies on the ftrace stub for redirecting cros_ec_{un,}register().

The 3rd patch uses static stub instead (if ftrace stub isn't really an option). However, I'm not a big fan to change the production code (i.e. adding the prologue in cros_ec_{un,}register()) for testing.

The 4th patch adds Kunit tests for cros_ec_spi. It relies on the ftrace stub for redirecting cros_ec_{un,}register() again.

The 5th patch calls .probe() directly instead of forcing the driver probe needs to be synchronous. In comparison with the 4th patch, I don't think this is simpler. I'd prefer to the way in the 4th patch.

After talked to Masami about the work, he suggested to use Kprobes for function redirection. The 6th patch adds kprobes stub.

The 7th patch uses kprobes stub instead for cros_ec_spi.

Questions:
- Are we going to support ftrace stub so that tests can use it?

- If ftrace stub isn't on the plate (e.g. due to too many dependencies), how about the kprobes stub? Is it something we could pursue?

- (minor) I'm unsure if people would prefer 'kprobes stub' vs. 'kprobe stub'.

[1]: https://kunit.dev/mocking.html#binary-level-ftrace-et-al
[2]: https://lore.kernel.org/linux-kselftest/[email protected]/

Daniel Latypov (1):
kunit: expose ftrace-based API for stubbing out functions during tests

Tzung-Bi Shih (6):
platform/chrome: kunit: cros_ec_i2c: Add tests with ftrace stub platform/chrome: kunit: cros_ec_i2c: Use static stub instead platform/chrome: kunit: cros_ec_spi: Add tests with ftrace stub platform/chrome: kunit: cros_ec_spi: Call .probe() directly
kunit: Expose 'kprobes stub' API to redirect functions platform/chrome: kunit: cros_ec_spi: Use kprobes stub instead

 drivers/platform/chrome/Kconfig            |  17 +
 drivers/platform/chrome/Makefile           |   2 +
 drivers/platform/chrome/cros_ec.c          |   6 +
 drivers/platform/chrome/cros_ec_i2c_test.c | 479 +++++++++++++++++++++
 drivers/platform/chrome/cros_ec_spi_test.c | 355 +++++++++++++++
 include/kunit/ftrace_stub.h                |  84 ++++
 include/kunit/kprobes_stub.h               |  19 +
 kernel/trace/ftrace.c                      |   3 +
 lib/kunit/Kconfig                          |  18 +
 lib/kunit/Makefile                         |   8 +
 lib/kunit/ftrace_stub.c                    | 139 ++++++
 lib/kunit/kprobes_stub.c                   | 113 +++++
 lib/kunit/kunit-example-test.c             |  27 +-
 lib/kunit/stubs_example.kunitconfig        |  11 +
 14 files changed, 1280 insertions(+), 1 deletion(-)
 create mode 100644 drivers/platform/chrome/cros_ec_i2c_test.c
 create mode 100644 drivers/platform/chrome/cros_ec_spi_test.c
 create mode 100644 include/kunit/ftrace_stub.h
 create mode 100644 include/kunit/kprobes_stub.h
 create mode 100644 lib/kunit/ftrace_stub.c
 create mode 100644 lib/kunit/kprobes_stub.c
 create mode 100644 lib/kunit/stubs_example.kunitconfig
Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#1 lore raw

RFC PATCH 1/7 kunit: expose ftrace-based API for stubbing out functions during tests

From: Daniel Latypov <[email protected]>

Allow function redirection using ftrace and kernel livepatch. This is basically equivalent to the static_stub support in the previous patch, but does not require the function being replaced to be modified (save for the addition of KUNIT_STUBBABLE/noinline).

This is hidden behind the CONFIG_KUNIT_FTRACE_STUBS option, and has a number of dependencies, including ftrace, livepatch and CONFIG_KALLSYMS_ALL. As a result, it only works on architectures where these are available.

You can run the KUnit example tests with the following:

$ ./tools/testing/kunit/kunit.py run --kunitconfig lib/kunit/stubs_example.kunitconfig --arch=x86_64

To the end user, replacing a function is very simple, e.g.
KUNIT_STUBBABLE void real_func(int n);
void replacement_func(int n);

  /* in tests */
  kunit_activate_ftrace_stub(test, real_func, replacement_func);

The implementation is inspired by Steven's snippet here [1].

Some more details:
* stubbing is automatically undone at the end of tests
* it can also be manually undone with kunit_deactive_ftrace_stub()
* stubbing only applies when current->kunit_test == test
* note: currently can't have more than one test running at a time
* KUNIT_STUBBABLE marks tests as noinline when CONFIG_KUNIT_STUBS is set
* this ensures we can actually stub all calls
* KUNIT_STUBBABLE_TRAMPOLINE is a version that evaluates to __always_inline when stubbing is not enabled
* This may need to be used with a wrapper function.
* See the doc comment for more details.

Sharp-edges:
* kernel livepatch only works on some arches (not UML)
* if you don't use noinline/KUNIT_STUBBABLE, functions might be inlined and thus none of this works:
* if it's always inlined, at least the attempt to stub will fail
* if it's sometimes inlined, then the stub silently won't work

[1] https://lore.kernel.org/lkml/[email protected]
[2] https://lore.kernel.org/linux-kselftest/CAGS_qxqtMpjKX+CMF6eBUWfsc-TKR9-Bk+hYM=PHa0_wUtQQuA@mail.gmail.com/

[tzungbi:
* Resolve contextual conflicts for rebasing.
* klp_arch_set_pc() -> ftrace_regs_set_instruction_pointer().
* Fix type check in kunit_activate_ftrace_stub() just like what has been done in kunit_activate_static_stub().
* Include <kunit/ftrace_stub.h> in lib/kunit/ftrace_stub.c.
* Fix typo in include/kunit/ftrace_stub.h as pointed out in [2].
* eavlautes -> evaluates.
* active -> activate.
* Fix typo in kunit-example-test.c and ftrace_stub.c.
* static -> ftrace.
* EXPORT_SYMBOL_IF_KUNIT() for ftrace_location() as lib/kunit/ftrace_stub.c uses it. If CONFIG_KUNIT=m, it can't find the symbol ftrace_location().
* KUNIT_ASSERT_FAILURE() -> KUNIT_FAIL_AND_ABORT() due to

    7d4087b01389.

]

---
 include/kunit/ftrace_stub.h         |  84 +++++++++++++++++
 kernel/trace/ftrace.c               |   3 +
 lib/kunit/Kconfig                   |  11 +++
 lib/kunit/Makefile                  |   4 +
 lib/kunit/ftrace_stub.c             | 139 ++++++++++++++++++++++++++++
 lib/kunit/kunit-example-test.c      |  27 +++++-
 lib/kunit/stubs_example.kunitconfig |  11 +++
 7 files changed, 278 insertions(+), 1 deletion(-)
 create mode 100644 include/kunit/ftrace_stub.h
 create mode 100644 lib/kunit/ftrace_stub.c
 create mode 100644 lib/kunit/stubs_example.kunitconfig
include/kunit/ftrace_stub.h new file +84 -0
new file mode 100644
index 000000000000..79c496b51ac5
@@ -0,0 +1,84 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _KUNIT_FTRACE_STUB_H
+#define _KUNIT_FTRACE_STUB_H
+
+/** KUNIT_STUBBABLE - marks a function as stubbable when stubbing support is
+ * enabled.
+ *
+ * Stubbing uses ftrace internally, so we can only stub out functions when they
+ * are not inlined. This macro evaluates to noinline when stubbing support is
+ * enabled to thus make it safe.
+ *
+ * If you cannot add this annotation to the function, you can instead use
+ * KUNIT_STUBBABLE_TRAMPOLINE, which is the same, but evaluates to
+ * __always_inline when stubbing is not enabled.
+ *
+ * Consider copy_to_user, which is marked as __always_inline:
+ *
+ * .. code-block:: c
+ *	static KUNIT_STUBBABLE_TRAMPOLINE unsigned long
+ *	copy_to_user_trampoline(void __user *to, const void *from, unsigned long n)
+ *	{
+ *		return copy_to_user(to, from, n);
+ *	}
+ *
+ * Then we simply need to update our code to go through this function instead
+ * (in the places where we want to stub it out).
+ */
+#if IS_ENABLED(CONFIG_KUNIT_FTRACE_STUBS)
+#define KUNIT_STUBBABLE noinline
+#define KUNIT_STUBBABLE_TRAMPOLINE noinline
+#else
+#define KUNIT_STUBBABLE
+#define KUNIT_STUBBABLE_TRAMPOLINE __always_inline
+#endif
+
+struct kunit;
+
+/**
+ * kunit_activate_ftrace_stub() - makes all calls to @func go to @replacement during @test.
+ * @test: The test context object.
+ * @func: The function to stub out, must be annotated with KUNIT_STUBBABLE.
+ * @replacement: The function to replace @func with.
+ *
+ * All calls to @func will instead call @replacement for the duration of the
+ * current test. If called from outside the test's thread, the function will
+ * not be redirected.
+ *
+ * The redirection can be disabled again with kunit_deactivate_ftrace_stub().
+ *
+ * Example:
+ *
+ * .. code-block:: c
+ *	KUNIT_STUBBABLE int real_func(int n)
+ *	{
+ *		pr_info("real_func() called with %d", n);
+ *		return 0;
+ *	}
+ *
+ *	void replacement_func(int n)
+ *	{
+ *		pr_info("replacement_func() called with %d", n);
+ *		return 42;
+ *	}
+ *
+ *	void example_test(struct kunit *test)
+ *	{
+ *		kunit_activate_ftrace_stub(test, real_func, replacement_func);
+ *		KUNIT_EXPECT_EQ(test, real_func(1), 42);
+ *	}
+ *
+ */
+#define kunit_activate_ftrace_stub(test, func, replacement) do { \
+	typecheck_fn(typeof(&func), replacement); \
+	__kunit_activate_ftrace_stub(test, #func, func, replacement); \
+} while (0)
+
+void __kunit_activate_ftrace_stub(struct kunit *test,
+				  const char *name,
+				  void *real_fn_addr,
+				  void *replacement_addr);
+
+
+void kunit_deactivate_ftrace_stub(struct kunit *test, void *real_fn_addr);
+#endif  /* _KUNIT_STUB_H */
kernel/trace/ftrace.c +3 -0
index 1a48aedb5255..7e86bc57d462 100644
@@ -36,6 +36,8 @@
 #include <linux/rcupdate.h>
 #include <linux/kprobes.h>
 
+#include <kunit/visibility.h>
+
 #include <trace/events/sched.h>
 
 #include <asm/sections.h>
@@ -1663,6 +1665,7 @@ unsigned long ftrace_location(unsigned long ip)
 	}
 	return loc;
 }
+EXPORT_SYMBOL_IF_KUNIT(ftrace_location);
 
 /**
  * ftrace_text_reserved - return true if range contains an ftrace location
lib/kunit/Kconfig +11 -0
index a97897edd964..933fda1df5c3 100644
@@ -93,4 +93,15 @@ config KUNIT_AUTORUN_ENABLED
 	  In most cases this should be left as Y. Only if additional opt-in
 	  behavior is needed should this be set to N.
 
+config KUNIT_FTRACE_STUBS
+	bool "Support for stubbing out functions in KUnit tests with ftrace and kernel livepatch"
+	depends on FTRACE=y && FUNCTION_TRACER=y && MODULES=y && DEBUG_KERNEL=y && KALLSYMS_ALL=y && LIVEPATCH=y
+	help
+	  Builds support for stubbing out functions for the duration of KUnit
+	  test cases or suites using ftrace and kernel livepatch.
+	  See KUNIT_EXAMPLE_TEST for an example.
+
+	  NOTE: this does not work on all architectures (like UML, arm64) and
+	  relies on a lot of magic (see the dependencies list).
+
 endif # KUNIT
lib/kunit/Makefile +4 -0
index 5aa51978e456..0ecb255576e2 100644
@@ -29,3 +29,7 @@ obj-$(CONFIG_KUNIT_TEST) +=		assert_test.o
 endif
 
 obj-$(CONFIG_KUNIT_EXAMPLE_TEST) +=	kunit-example-test.o
+
+ifeq ($(CONFIG_KUNIT_FTRACE_STUBS),y)
+kunit-objs +=				ftrace_stub.o
+endif
lib/kunit/ftrace_stub.c new file +139 -0

139 lines not on this page · raw message

lib/kunit/kunit-example-test.c +26 -1
index 3056d6bc705d..1974e8d24a50 100644
@@ -8,6 +8,7 @@
 
 #include <kunit/test.h>
 #include <kunit/static_stub.h>
+#include <kunit/ftrace_stub.h>
 
 /*
  * This is the most fundamental element of KUnit, the test case. A test case
@@ -152,7 +153,7 @@ static void example_all_expect_macros_test(struct kunit *test)
 }
 
 /* This is a function we'll replace with static stubs. */
-static int add_one(int i)
+static KUNIT_STUBBABLE int add_one(int i)
 {
 	/* This will trigger the stub if active. */
 	KUNIT_STATIC_STUB_REDIRECT(add_one, i);
@@ -277,6 +278,29 @@ static void example_slow_test(struct kunit *test)
 	KUNIT_EXPECT_EQ(test, 1 + 1, 2);
 }
 
+/*
+ * This test shows the use of ftrace stubs.
+ */
+static void example_ftrace_stub_test(struct kunit *test)
+{
+#if !IS_ENABLED(CONFIG_KUNIT_FTRACE_STUBS)
+	kunit_skip(test, "KUNIT_FTRACE_STUBS not enabled");
+#else
+	/* By default, function is not stubbed. */
+	KUNIT_EXPECT_EQ(test, add_one(1), 2);
+
+	/* Replace add_one() with subtract_one(). */
+	kunit_activate_ftrace_stub(test, add_one, subtract_one);
+
+	/* add_one() is now replaced. */
+	KUNIT_EXPECT_EQ(test, add_one(1), 0);
+
+	/* Return add_one() to normal. */
+	kunit_deactivate_ftrace_stub(test, add_one);
+	KUNIT_EXPECT_EQ(test, add_one(1), 2);
+#endif
+}
+
 /*
  * Here we make a list of all the test cases we want to add to the test suite
  * below.
@@ -297,6 +321,7 @@ static struct kunit_case example_test_cases[] = {
 	KUNIT_CASE(example_priv_test),
 	KUNIT_CASE_PARAM(example_params_test, example_gen_params),
 	KUNIT_CASE_SLOW(example_slow_test),
+	KUNIT_CASE(example_ftrace_stub_test),
 	{}
 };
 
lib/kunit/stubs_example.kunitconfig new file +11 -0
new file mode 100644
index 000000000000..a47369199fb9
@@ -0,0 +1,11 @@
+CONFIG_KUNIT=y
+CONFIG_KUNIT_FTRACE_STUBS=y
+CONFIG_KUNIT_EXAMPLE_TEST=y
+
+# Depedencies
+CONFIG_FTRACE=y
+CONFIG_FUNCTION_TRACER=y
+CONFIG_MODULES=y
+CONFIG_DEBUG_KERNEL=y
+CONFIG_KALLSYMS_ALL=y
+CONFIG_LIVEPATCH=y
Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#2 lore raw

RFC PATCH 2/7 platform/chrome: kunit: cros_ec_i2c: Add tests with ftrace stub

In reply to Tzung-Bi Shih

For running the tests:

$ ./tools/testing/kunit/kunit.py run \
	--arch=x86_64 \
	--kconfig_add CONFIG_CHROME_PLATFORMS=y \
	--kconfig_add CONFIG_CROS_EC=y \
	--kconfig_add CONFIG_FTRACE=y \
	--kconfig_add CONFIG_FUNCTION_TRACER=y \
	--kconfig_add CONFIG_MODULES=y \
	--kconfig_add CONFIG_DEBUG_KERNEL=y \
	--kconfig_add CONFIG_KALLSYMS_ALL=y \
	--kconfig_add CONFIG_LIVEPATCH=y \
	--kconfig_add CONFIG_KUNIT_FTRACE_STUBS=y \
	--kconfig_add CONFIG_I2C=y \
	--kconfig_add CONFIG_CROS_EC_I2C=y \
	--kconfig_add CONFIG_CROS_KUNIT_EC_I2C_TEST=y \
	cros_ec_i2c*
---
 drivers/platform/chrome/Kconfig            |   9 +
 drivers/platform/chrome/Makefile           |   1 +
 drivers/platform/chrome/cros_ec_i2c_test.c | 479 +++++++++++++++++++++
 3 files changed, 489 insertions(+)
 create mode 100644 drivers/platform/chrome/cros_ec_i2c_test.c
drivers/platform/chrome/Kconfig +9 -0
index 10941ac37305..5e0b44fb7ca7 100644
@@ -327,4 +327,13 @@ config CROS_KUNIT_EC_PROTO_TEST
 	help
 	  Kunit tests for ChromeOS EC protocol.
 
+config CROS_KUNIT_EC_I2C_TEST
+	tristate "Kunit tests for ChromeOS EC over I2C" if !KUNIT_ALL_TESTS
+	depends on KUNIT && CROS_EC
+	default KUNIT_ALL_TESTS
+	depends on KUNIT_FTRACE_STUBS
+	depends on CROS_EC_I2C
+	help
+	  Kunit tests for ChromeOS EC over I2C.
+
 endif # CHROMEOS_PLATFORMS
drivers/platform/chrome/Makefile +1 -0
index b981a1bb5bd8..9808f25aea38 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_WILCO_EC)			+= wilco_ec/
 # Kunit test cases
 obj-$(CONFIG_CROS_KUNIT_EC_PROTO_TEST)	+= cros_kunit_proto_test.o
 cros_kunit_proto_test-objs		:= cros_ec_proto_test_util.o cros_ec_proto_test.o
+obj-$(CONFIG_CROS_KUNIT_EC_I2C_TEST)	+= cros_ec_i2c_test.o
drivers/platform/chrome/cros_ec_i2c_test.c new file +479 -0

479 lines not on this page · raw message

Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#3 lore raw

RFC PATCH 3/7 platform/chrome: kunit: cros_ec_i2c: Use static stub instead

In reply to Tzung-Bi Shih

For running the tests:

$ ./tools/testing/kunit/kunit.py run \
        --arch=x86_64 \
        --kconfig_add CONFIG_CHROME_PLATFORMS=y \
        --kconfig_add CONFIG_CROS_EC=y \
        --kconfig_add CONFIG_I2C=y \
        --kconfig_add CONFIG_CROS_EC_I2C=y \
        --kconfig_add CONFIG_CROS_KUNIT_EC_I2C_TEST=y \
        cros_ec_i2c*
---
 drivers/platform/chrome/Kconfig            |  1 -
 drivers/platform/chrome/cros_ec.c          |  6 ++++++
 drivers/platform/chrome/cros_ec_i2c_test.c | 10 +++++-----
 3 files changed, 11 insertions(+), 6 deletions(-)
drivers/platform/chrome/Kconfig +0 -1
index 5e0b44fb7ca7..bf10c0625be8 100644
@@ -331,7 +331,6 @@ config CROS_KUNIT_EC_I2C_TEST
 	tristate "Kunit tests for ChromeOS EC over I2C" if !KUNIT_ALL_TESTS
 	depends on KUNIT && CROS_EC
 	default KUNIT_ALL_TESTS
-	depends on KUNIT_FTRACE_STUBS
 	depends on CROS_EC_I2C
 	help
 	  Kunit tests for ChromeOS EC over I2C.
drivers/platform/chrome/cros_ec.c +6 -0
index 110771a8645e..62327fa0ff34 100644
@@ -18,6 +18,8 @@
 #include <linux/slab.h>
 #include <linux/suspend.h>
 
+#include <kunit/static_stub.h>
+
 #include "cros_ec.h"
 
 static struct cros_ec_platform ec_p = {
@@ -179,6 +181,8 @@ static int cros_ec_ready_event(struct notifier_block *nb,
  */
 int cros_ec_register(struct cros_ec_device *ec_dev)
 {
+	KUNIT_STATIC_STUB_REDIRECT(cros_ec_register, ec_dev);
+
 	struct device *dev = ec_dev->dev;
 	int err = 0;
 
@@ -318,6 +322,8 @@ EXPORT_SYMBOL(cros_ec_register);
  */
 void cros_ec_unregister(struct cros_ec_device *ec_dev)
 {
+	KUNIT_STATIC_STUB_REDIRECT(cros_ec_unregister, ec_dev);
+
 	platform_device_unregister(ec_dev->pd);
 	platform_device_unregister(ec_dev->ec);
 	mutex_destroy(&ec_dev->lock);
drivers/platform/chrome/cros_ec_i2c_test.c +5 -5
index 3a7f1a17d82d..5d41cdeec4b7 100644
@@ -3,7 +3,7 @@
  * Kunit tests for ChromeOS Embedded Controller I2C interface.
  */
 #include <kunit/test.h>
-#include <kunit/ftrace_stub.h>
+#include <kunit/static_stub.h>
 
 #include <linux/i2c.h>
 #include <linux/platform_data/cros_ec_proto.h>
@@ -106,8 +106,8 @@ static int cros_ec_i2c_test_init(struct kunit *test)
 		I2C_BOARD_INFO("cros-ec-i2c", I2C_ADDR),
 	};
 
-	kunit_activate_ftrace_stub(test, cros_ec_register, fake_cros_ec_register);
-	kunit_activate_ftrace_stub(test, cros_ec_unregister, fake_cros_ec_unregister);
+	kunit_activate_static_stub(test, cros_ec_register, fake_cros_ec_register);
+	kunit_activate_static_stub(test, cros_ec_unregister, fake_cros_ec_unregister);
 
 	priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL);
 	KUNIT_ASSERT_NOT_NULL(test, priv);
@@ -142,8 +142,8 @@ static void cros_ec_i2c_test_exit(struct kunit *test)
 
 	i2c_del_adapter(priv->fake_adap);
 
-	kunit_deactivate_ftrace_stub(test, cros_ec_register);
-	kunit_deactivate_ftrace_stub(test, cros_ec_unregister);
+	kunit_deactivate_static_stub(test, cros_ec_register);
+	kunit_deactivate_static_stub(test, cros_ec_unregister);
 }
 
 static int cros_ec_i2c_test_cmd_xfer_init(struct kunit *test)
Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#4 lore raw

RFC PATCH 4/7 platform/chrome: kunit: cros_ec_spi: Add tests with ftrace stub

In reply to Tzung-Bi Shih

For running the tests:

$ ./tools/testing/kunit/kunit.py run \
	--arch=x86_64 \
	--kconfig_add CONFIG_FTRACE=y \
	--kconfig_add CONFIG_FUNCTION_TRACER=y \
	--kconfig_add CONFIG_MODULES=y \
	--kconfig_add CONFIG_DEBUG_KERNEL=y \
	--kconfig_add CONFIG_KALLSYMS_ALL=y \
	--kconfig_add CONFIG_LIVEPATCH=y \
	--kconfig_add CONFIG_KUNIT_FTRACE_STUBS=y \
	--kconfig_add CONFIG_CHROME_PLATFORMS=y \
	--kconfig_add CONFIG_CROS_EC=y \
	--kconfig_add CONFIG_SPI=y \
	--kconfig_add CONFIG_CROS_EC_SPI=y \
	--kconfig_add CONFIG_CROS_KUNIT_EC_SPI_TEST=y \
	cros_ec_spi*
---
 drivers/platform/chrome/Kconfig            |   9 +
 drivers/platform/chrome/Makefile           |   1 +
 drivers/platform/chrome/cros_ec_spi_test.c | 361 +++++++++++++++++++++
 3 files changed, 371 insertions(+)
 create mode 100644 drivers/platform/chrome/cros_ec_spi_test.c
drivers/platform/chrome/Kconfig +9 -0
index bf10c0625be8..aa13e871a31f 100644
@@ -335,4 +335,13 @@ config CROS_KUNIT_EC_I2C_TEST
 	help
 	  Kunit tests for ChromeOS EC over I2C.
 
+config CROS_KUNIT_EC_SPI_TEST
+	tristate "Kunit tests for ChromeOS EC over SPI" if !KUNIT_ALL_TESTS
+	depends on KUNIT && CROS_EC
+	default KUNIT_ALL_TESTS
+	depends on KUNIT_FTRACE_STUBS
+	depends on CROS_EC_SPI
+	help
+	  Kunit tests for ChromeOS EC over SPI.
+
 endif # CHROMEOS_PLATFORMS
drivers/platform/chrome/Makefile +1 -0
index 9808f25aea38..74649b8f21b3 100644
@@ -45,3 +45,4 @@ obj-$(CONFIG_WILCO_EC)			+= wilco_ec/
 obj-$(CONFIG_CROS_KUNIT_EC_PROTO_TEST)	+= cros_kunit_proto_test.o
 cros_kunit_proto_test-objs		:= cros_ec_proto_test_util.o cros_ec_proto_test.o
 obj-$(CONFIG_CROS_KUNIT_EC_I2C_TEST)	+= cros_ec_i2c_test.o
+obj-$(CONFIG_CROS_KUNIT_EC_SPI_TEST)	+= cros_ec_spi_test.o
drivers/platform/chrome/cros_ec_spi_test.c new file +361 -0

361 lines not on this page · raw message

Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#5 lore raw

RFC PATCH 5/7 platform/chrome: kunit: cros_ec_spi: Call .probe() directly

In reply to Tzung-Bi Shih

Get the spi_driver and call .probe() directly.

For running the tests:

$ ./tools/testing/kunit/kunit.py run \
	--arch=x86_64 \
	--kconfig_add CONFIG_FTRACE=y \
	--kconfig_add CONFIG_FUNCTION_TRACER=y \
	--kconfig_add CONFIG_MODULES=y \
	--kconfig_add CONFIG_DEBUG_KERNEL=y \
	--kconfig_add CONFIG_KALLSYMS_ALL=y \
	--kconfig_add CONFIG_LIVEPATCH=y \
	--kconfig_add CONFIG_KUNIT_FTRACE_STUBS=y \
	--kconfig_add CONFIG_CHROME_PLATFORMS=y \
	--kconfig_add CONFIG_CROS_EC=y \
	--kconfig_add CONFIG_SPI=y \
	--kconfig_add CONFIG_CROS_EC_SPI=y \
	--kconfig_add CONFIG_CROS_KUNIT_EC_SPI_TEST=y \
	cros_ec_spi*
---
 drivers/platform/chrome/cros_ec_spi_test.c | 22 ++++++++--------------
 1 file changed, 8 insertions(+), 14 deletions(-)
drivers/platform/chrome/cros_ec_spi_test.c +8 -14
index 2a021569a726..52dea75ecabf 100644
@@ -27,6 +27,7 @@ struct cros_ec_spi_test_priv {
 	struct device dev;
 	struct spi_controller *fake_ctlr;
 	struct spi_device *fake_spi_device;
+	struct spi_driver *spi_drv;
 
 	int fake_cros_ec_register_called;
 	struct cros_ec_device *ec_dev;
@@ -117,16 +118,12 @@ static int find_target_driver(struct device_driver *drv, void *data)
 static int cros_ec_spi_test_init(struct kunit *test)
 {
 	struct cros_ec_spi_test_priv *priv;
-	struct spi_board_info board_info = {};
 	int ret;
 	struct device_driver *drv;
-	enum probe_type orig;
 
 	kunit_activate_ftrace_stub(test, cros_ec_register, fake_cros_ec_register);
 	kunit_activate_ftrace_stub(test, cros_ec_unregister, fake_cros_ec_unregister);
 
-	sized_strscpy(board_info.modalias, "cros-ec-spi", SPI_NAME_SIZE);
-
 	priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL);
 	KUNIT_ASSERT_NOT_NULL(test, priv);
 	test->priv = priv;
@@ -151,21 +148,17 @@ static int cros_ec_spi_test_init(struct kunit *test)
 	ret = spi_register_controller(priv->fake_ctlr);
 	KUNIT_ASSERT_EQ(test, ret, 0);
 
-	/*
-	 * Force to use synchronous probe so that the upcoming SPI device gets
-	 * probed correctly and synchronously.
-	 */
 	ret = bus_for_each_drv(&spi_bus_type, NULL, &drv, find_target_driver);
 	KUNIT_ASSERT_EQ(test, ret, 0);
 	KUNIT_ASSERT_NOT_NULL(test, drv);
-	orig = drv->probe_type;
-	drv->probe_type = PROBE_FORCE_SYNCHRONOUS;
 
-	priv->fake_spi_device = spi_new_device(priv->fake_ctlr, &board_info);
-	/* Restore to original probe type. */
-	drv->probe_type = orig;
+	priv->fake_spi_device = spi_alloc_device(priv->fake_ctlr);
 	KUNIT_ASSERT_NOT_NULL(test, priv->fake_spi_device);
 
+	priv->spi_drv = container_of(drv, struct spi_driver, driver);
+	ret = priv->spi_drv->probe(priv->fake_spi_device);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
 	KUNIT_EXPECT_EQ(test, priv->fake_cros_ec_register_called, 1);
 	KUNIT_ASSERT_NOT_NULL(test, priv->ec_dev);
 	KUNIT_EXPECT_EQ(test, priv->fake_cros_ec_unregister_called, 0);
@@ -180,9 +173,10 @@ static void cros_ec_spi_test_exit(struct kunit *test)
 {
 	struct cros_ec_spi_test_priv *priv = test->priv;
 
-	spi_unregister_device(priv->fake_spi_device);
+	priv->spi_drv->remove(priv->fake_spi_device);
 	KUNIT_EXPECT_EQ(test, priv->fake_cros_ec_unregister_called, 1);
 
+	spi_dev_put(priv->fake_spi_device);
 	spi_unregister_controller(priv->fake_ctlr);
 	device_del(&priv->dev);
 	class_destroy(priv->fake_class);
Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#6 lore raw

RFC PATCH 6/7 kunit: Expose 'kprobes stub' API to redirect functions

In reply to Tzung-Bi Shih

Add function redirection API based on Kprobes.

---
 include/kunit/kprobes_stub.h |  19 ++++++
 lib/kunit/Kconfig            |   7 +++
 lib/kunit/Makefile           |   4 ++
 lib/kunit/kprobes_stub.c     | 113 +++++++++++++++++++++++++++++++++++
 4 files changed, 143 insertions(+)
 create mode 100644 include/kunit/kprobes_stub.h
 create mode 100644 lib/kunit/kprobes_stub.c
include/kunit/kprobes_stub.h new file +19 -0
new file mode 100644
index 000000000000..af77c86fe48e
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _KUNIT_KPROBES_STUB_H
+#define _KUNIT_KPROBES_STUB_H
+
+struct kunit;
+
+#define kunit_activate_kprobes_stub(test, func, replacement) do { \
+	typecheck_fn(typeof(&func), replacement); \
+	__kunit_activate_kprobes_stub(test, #func, func, replacement); \
+} while (0)
+
+void __kunit_activate_kprobes_stub(struct kunit *test,
+				  const char *name,
+				  void *real_fn_addr,
+				  void *replacement_addr);
+
+void kunit_deactivate_kprobes_stub(struct kunit *test, void *real_fn_addr);
+
+#endif  /* _KUNIT_KPROBES_STUB_H */
lib/kunit/Kconfig +7 -0
index 933fda1df5c3..13fdd3471060 100644
@@ -104,4 +104,11 @@ config KUNIT_FTRACE_STUBS
 	  NOTE: this does not work on all architectures (like UML, arm64) and
 	  relies on a lot of magic (see the dependencies list).
 
+config KUNIT_KPROBES_STUBS
+	bool "Support for stubbing out functions in KUnit tests with kprobes"
+	depends on KPROBES
+	help
+	  Builds support for stubbing out functions for the duration of KUnit
+	  test cases or suites using kprobes.
+
 endif # KUNIT
lib/kunit/Makefile +4 -0
index 0ecb255576e2..727ce86eb61f 100644
@@ -33,3 +33,7 @@ obj-$(CONFIG_KUNIT_EXAMPLE_TEST) +=	kunit-example-test.o
 ifeq ($(CONFIG_KUNIT_FTRACE_STUBS),y)
 kunit-objs +=				ftrace_stub.o
 endif
+
+ifeq ($(CONFIG_KUNIT_KPROBES_STUBS),y)
+kunit-objs +=				kprobes_stub.o
+endif
lib/kunit/kprobes_stub.c new file +113 -0

113 lines not on this page · raw message

Signature · 1 line
2.49.0.1101.gccaa498523-goog
author maintainer
#7 lore raw

RFC PATCH 7/7 platform/chrome: kunit: cros_ec_spi: Use kprobes stub instead

In reply to Tzung-Bi Shih

For running the tests:

$ ./tools/testing/kunit/kunit.py run \
	--arch=x86_64 \
	--kconfig_add CONFIG_KPROBES=y \
	--kconfig_add CONFIG_KUNIT_KPROBES_STUBS=y \
	--kconfig_add CONFIG_CHROME_PLATFORMS=y \
	--kconfig_add CONFIG_CROS_EC=y \
	--kconfig_add CONFIG_SPI=y \
	--kconfig_add CONFIG_CROS_EC_SPI=y \
	--kconfig_add CONFIG_CROS_KUNIT_EC_SPI_TEST=y \
	cros_ec_spi*
---
 drivers/platform/chrome/Kconfig            |  2 +-
 drivers/platform/chrome/cros_ec_spi_test.c | 10 +++++-----
 2 files changed, 6 insertions(+), 6 deletions(-)
drivers/platform/chrome/Kconfig +1 -1
index aa13e871a31f..aacce3323384 100644
@@ -339,7 +339,7 @@ config CROS_KUNIT_EC_SPI_TEST
 	tristate "Kunit tests for ChromeOS EC over SPI" if !KUNIT_ALL_TESTS
 	depends on KUNIT && CROS_EC
 	default KUNIT_ALL_TESTS
-	depends on KUNIT_FTRACE_STUBS
+	depends on KUNIT_KPROBES_STUBS
 	depends on CROS_EC_SPI
 	help
 	  Kunit tests for ChromeOS EC over SPI.
drivers/platform/chrome/cros_ec_spi_test.c +5 -5
index 52dea75ecabf..74fcbd37b87b 100644
@@ -3,7 +3,7 @@
  * Kunit tests for ChromeOS Embedded Controller SPI interface.
  */
 #include <kunit/test.h>
-#include <kunit/ftrace_stub.h>
+#include <kunit/kprobes_stub.h>
 
 #include <linux/platform_data/cros_ec_commands.h>
 #include <linux/platform_data/cros_ec_proto.h>
@@ -121,8 +121,8 @@ static int cros_ec_spi_test_init(struct kunit *test)
 	int ret;
 	struct device_driver *drv;
 
-	kunit_activate_ftrace_stub(test, cros_ec_register, fake_cros_ec_register);
-	kunit_activate_ftrace_stub(test, cros_ec_unregister, fake_cros_ec_unregister);
+	kunit_activate_kprobes_stub(test, cros_ec_register, fake_cros_ec_register);
+	kunit_activate_kprobes_stub(test, cros_ec_unregister, fake_cros_ec_unregister);
 
 	priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL);
 	KUNIT_ASSERT_NOT_NULL(test, priv);
@@ -181,8 +181,8 @@ static void cros_ec_spi_test_exit(struct kunit *test)
 	device_del(&priv->dev);
 	class_destroy(priv->fake_class);
 
-	kunit_deactivate_ftrace_stub(test, cros_ec_register);
-	kunit_deactivate_ftrace_stub(test, cros_ec_unregister);
+	kunit_deactivate_kprobes_stub(test, cros_ec_register);
+	kunit_deactivate_kprobes_stub(test, cros_ec_unregister);
 }
 
 static int cros_ec_spi_test_cmd_xfer_init(struct kunit *test)
Signature · 1 line
2.49.0.1101.gccaa498523-goog
#8 lore raw
In reply to Tzung-Bi Shih
Quoted 34 lines · Tzung-Bi Shih' via KUnit Development

The protocol device drivers under drivers/platform/chrome/ are responsible to communicate to the ChromeOS EC (Embedded Controller). They need to pack the data in a pre-defined format and check if the EC responds accordingly.

The series adds some fundamental unit tests for the protocol. It calls the .cmd_xfer() and .pkt_xfer() callbacks (which are the most crucial parts for the protocol), mocks the rest of the system, and checks if the interactions are all correct.

The series isn't ready for landing. It's more like a PoC for the binary-level function redirection and its use cases.

The 1st patch adds ftrace stub which is originally from [1][2]. There is no follow-up discussion about the ftrace stub. As a result, the patch is still on the mailing list.

The 2nd patch adds Kunit tests for cros_ec_i2c. It relies on the ftrace stub for redirecting cros_ec_{un,}register().

The 3rd patch uses static stub instead (if ftrace stub isn't really an option). However, I'm not a big fan to change the production code (i.e. adding the prologue in cros_ec_{un,}register()) for testing.

The 4th patch adds Kunit tests for cros_ec_spi. It relies on the ftrace stub for redirecting cros_ec_{un,}register() again.

The 5th patch calls .probe() directly instead of forcing the driver probe needs to be synchronous. In comparison with the 4th patch, I don't think this is simpler. I'd prefer to the way in the 4th patch.

After talked to Masami about the work, he suggested to use Kprobes for function redirection. The 6th patch adds kprobes stub.

Quoted 7 lines

The 7th patch uses kprobes stub instead for cros_ec_spi.

Questions:
- Are we going to support ftrace stub so that tests can use it?

- If ftrace stub isn't on the plate (e.g. due to too many dependencies), how about the kprobes stub? Is it something we could pursue?

Quick comment,
If I recall, the thought process was that we could consider it in the future if there was enough demand for it.

We have these drawbacks with the current ftrace stubs:
* doesn't compile on all arches
* silently doesn't work on inlined functions <== scariest one to me
* is more complicated and has more dependencies

So it felt like the better move to go with static stubs which has none of those drawbacks (works on all arches, all functions, and is dead simple) as opposed to simultaneously introducing two ways to do the same thing.

You mention you don't like how static stubs requires modifying the code-under-test.
Since it gets eliminated by the preprocessor unless you're compiling for KUnit, is the concern more so about how it conceptually feels wrong to do so?
For the Android GKI kernel, they have (or had) KUnit enabled so there is potentially concern about real runtime cost there, not sure if you have something similar in mind.

But stepping back, ftrace_stubs technically require modifying the code to make sure funcs are marked as noinline, which this patch series does not do.
I've not looked at cros_ec_{un,}register() to check if they're at risk of inlining, but wanted to call that out, that ftrace stubs technically don't handle your usage pattern 100% properly.

Quoted 3 lines

- (minor) I'm unsure if people would prefer 'kprobes stub' vs. 'kprobe stub'.

I'd personally vote for kprobe_stub.

Daniel

author maintainer
#9 lore raw
Quoted 6 lines · Daniel Latypov
Quoted 4 lines · Tzung-Bi Shih' via KUnit Development

[...]
Questions:
- Are we going to support ftrace stub so that tests can use it?

Quoted 6 lines
Quoted 2 lines

- If ftrace stub isn't on the plate (e.g. due to too many dependencies), how about the kprobes stub? Is it something we could pursue?

Quick comment,
If I recall, the thought process was that we could consider it in the future if there was enough demand for it.

Sorry for the late reply. I was doing some more experiments and stuck by some else.

Quoted 3 lines

We have these drawbacks with the current ftrace stubs:
* doesn't compile on all arches
* silently doesn't work on inlined functions <== scariest one to me

I see. I did some experiments and realized that kprobe stubs also share the same concern. Thus I'm wondering if there is a way that kprobe stub detects the redirection may fail, at least it can skip the test case (e.g. register_kprobe() returns -ENOENT when it can't find the symbol via kprobe_lookup_name()). But it seems no way if the target function is partially inlined.

Quoted 8 lines

You mention you don't like how static stubs requires modifying the code-under-test.
Since it gets eliminated by the preprocessor unless you're compiling for KUnit, is the concern more so about how it conceptually feels wrong to do so?
For the Android GKI kernel, they have (or had) KUnit enabled so there is potentially concern about real runtime cost there, not sure if you have something similar in mind.

Not exactly. Ideally, I think we shouldn't modify the CUT. I'm wondering if there is a way to not change the CUT but also break the external dependencies.

Quoted 6 lines

But stepping back, ftrace_stubs technically require modifying the code to make sure funcs are marked as noinline, which this patch series does not do.
I've not looked at cros_ec_{un,}register() to check if they're at risk of inlining, but wanted to call that out, that ftrace stubs technically don't handle your usage pattern 100% properly.

True. They could be partially inlined even though they are exported symbols.

#10 lore raw
Quoted 2 lines · Tzung-Bi Shih

On Tue, May 20, 2025 at 09:04:53AM -0700, Daniel Latypov wrote:

(snip)

Quoted 11 lines
Quoted 4 lines

We have these drawbacks with the current ftrace stubs:
* doesn't compile on all arches
* silently doesn't work on inlined functions <== scariest one to me

I see. I did some experiments and realized that kprobe stubs also share the same concern. Thus I'm wondering if there is a way that kprobe stub detects the redirection may fail, at least it can skip the test case (e.g. register_kprobe() returns -ENOENT when it can't find the symbol via kprobe_lookup_name()). But it seems no way if the target function is partially inlined.

Yeah, any such approach will need to be cautious of inlining, so they'd have to always be "for power users only: only use this if you understand the risk"
Skipping when we can detect the user is obviously doing the wrong thing makes that a *bit* more palatable.

It's not like static stubs can detect at runtime if you've failed to add the necessary corresponding KUNIT_STATIC_STUB_REDIRECT() either, for example.

But I still personally lean slightly against adding either kprobe or ftrace stubs, see below.

Quoted 17 lines
Quoted 9 lines

You mention you don't like how static stubs requires modifying the code-under-test.
Since it gets eliminated by the preprocessor unless you're compiling for KUnit, is the concern more so about how it conceptually feels wrong to do so?
For the Android GKI kernel, they have (or had) KUnit enabled so there is potentially concern about real runtime cost there, not sure if you have something similar in mind.

Not exactly. Ideally, I think we shouldn't modify the CUT. I'm wondering if there is a way to not change the CUT but also break the external dependencies.

Quoted 3 lines

But stepping back, ftrace_stubs technically require modifying the code to make sure funcs are marked as noinline, which this patch series does not do.

...

Quoted 1 line

They could be partially inlined even though they are exported symbols.

So to summarize, right now we're stuck with having to modify the code. (Unless someone can come up with something really clever, but not too clever)

To make it concrete, the current approach would look like:

int func(char* arg1, int arg2) {
KUNIT_STATIC_STUB_REDIRECT(func, arg1, arg2);
... // unchanged
}

vs an ftrace/kprobe approach that needs a conditional noinline

KUNIT_STUBBABLE int func(char* arg1, int arg2) {
... // unchanged
}

The latter is definitely simpler and less burdensome. But I don't know if it's simpler enough to warrant a second implementation existing for me personally.

E.g. we already have some people who justifiably say it's too hard to figure out KUnit, so this is another decision point where a user might get stuck with "how should I know which one I should use?" and give up.

Compatibility tangent:
A smaller annoyance is KUNIT_STATIC_STUB_REDIRECT and KUNIT_STUBBABLE are incompatible (and always will be?)

E.g. imagine a func has KUNIT_STUBBABLE on it, but a person authoring a new test wants needs to run without kprobe support, so they must add KUNIT_STATIC_STUB_REDIRECT.
I can imagine an author deciding to make the func have *both* macros on it... That feels like a worst case outcome from the perspective of "we shouldn't modify the CUT just for the sake of tests" :\

To be clear, the right approach in this scenario is to 1) swap to KUNIT_STATIC_STUB_REDIRECT and update the previous tests to use static stubs, 2) then add your new tests.
But I can imagine that won't always happen, esp. if it crosses maintainer boundaries.

author maintainer
#11 lore raw
Quoted 33 lines · Daniel Latypov
Quoted 17 lines · Tzung-Bi Shih
Quoted 8 lines · Daniel Latypov

You mention you don't like how static stubs requires modifying the code-under-test.
Since it gets eliminated by the preprocessor unless you're compiling for KUnit, is the concern more so about how it conceptually feels wrong to do so?
For the Android GKI kernel, they have (or had) KUnit enabled so there is potentially concern about real runtime cost there, not sure if you have something similar in mind.

Not exactly. Ideally, I think we shouldn't modify the CUT. I'm wondering if there is a way to not change the CUT but also break the external dependencies.

Quoted 3 lines

But stepping back, ftrace_stubs technically require modifying the code to make sure funcs are marked as noinline, which this patch series does not do.

...

Quoted 1 line

They could be partially inlined even though they are exported symbols.

So to summarize, right now we're stuck with having to modify the code. (Unless someone can come up with something really clever, but not too clever)

To make it concrete, the current approach would look like:

int func(char* arg1, int arg2) {
KUNIT_STATIC_STUB_REDIRECT(func, arg1, arg2);
... // unchanged
}

vs an ftrace/kprobe approach that needs a conditional noinline

Quoted 7 lines

KUNIT_STUBBABLE int func(char* arg1, int arg2) {
... // unchanged
}

The latter is definitely simpler and less burdensome. But I don't know if it's simpler enough to warrant a second implementation existing for me personally.

Instead of KUNIT_STUBBABLE macros, I was thinking of:

Makefile +4 -0
index 35e6e5240c61..40319083f58b 100644
@@ -979,6 +979,10 @@ ifdef CONFIG_DEBUG_SECTION_MISMATCH
 KBUILD_CFLAGS += -fno-inline-functions-called-once
 endif
 
+ifdef CONFIG_KUNIT_KPROBE_STUBS
+KBUILD_CFLAGS += -fno-inline
+endif
+
 # `rustc`'s `-Zfunction-sections` applies to data too (as of 1.59.0).
 ifdef CONFIG_LD_DEAD_CODE_DATA_ELIMINATION
 KBUILD_CFLAGS_KERNEL += -ffunction-sections -fdata-sections

I don't know what are most people's usages. I always run KUnit tests in qemu or at least in some real devices that I less care about the performance. Thus, turning inline off globally in such environments is totally acceptable.