1 From 0f354629c10f457751c20a230b13b1b7ac2f1fbc Mon Sep 17 00:00:00 2001
2 From: David Gow <davidgow@google.com>
3 Date: Fri, 25 Nov 2022 16:43:04 +0800
4 Subject: [PATCH] kunit: Provide a static key to check if KUnit is
7 KUnit does a few expensive things when enabled. This hasn't been a
8 problem because KUnit was only enabled on test kernels, but with a few
9 people enabling (but not _using_) KUnit on production systems, we need a
10 runtime way of handling this.
12 Provide a 'kunit_running' static key (defaulting to false), which allows
13 us to hide any KUnit code behind a static branch. This should reduce the
14 performance impact (on other code) of having KUnit enabled to a single
15 NOP when no tests are running.
17 Note that, while it looks unintuitive, tests always run entirely within
18 __kunit_test_suites_init(), so it's safe to decrement the static key at
19 the end of this function, rather than in __kunit_test_suites_exit(),
20 which is only there to clean up results in debugfs.
22 Signed-off-by: David Gow <davidgow@google.com>
23 Reviewed-by: Daniel Latypov <dlatypov@google.com>
24 Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>
26 include/kunit/test.h | 4 ++++
27 lib/kunit/test.c | 6 ++++++
28 2 files changed, 10 insertions(+)
30 --- a/include/kunit/test.h
31 +++ b/include/kunit/test.h
33 #include <linux/container_of.h>
34 #include <linux/err.h>
35 #include <linux/init.h>
36 +#include <linux/jump_label.h>
37 #include <linux/kconfig.h>
38 #include <linux/kref.h>
39 #include <linux/list.h>
42 #include <asm/rwonce.h>
44 +/* Static key: true if any KUnit tests are currently running */
45 +DECLARE_STATIC_KEY_FALSE(kunit_running);
49 /* Size of log associated with test. */
50 --- a/lib/kunit/test.c
51 +++ b/lib/kunit/test.c
53 #include "string-stream.h"
54 #include "try-catch-impl.h"
56 +DEFINE_STATIC_KEY_FALSE(kunit_running);
58 #if IS_BUILTIN(CONFIG_KUNIT)
60 * Fail the current test and print an error message to the log.
61 @@ -622,10 +624,14 @@ int __kunit_test_suites_init(struct kuni
65 + static_branch_inc(&kunit_running);
67 for (i = 0; i < num_suites; i++) {
68 kunit_init_suite(suites[i]);
69 kunit_run_tests(suites[i]);
72 + static_branch_dec(&kunit_running);
75 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);