Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Base unit test (KUnit) API.
4 *
5 * Copyright (C) 2019, Google LLC.
6 * Author: Brendan Higgins <brendanhiggins@google.com>
7 */
8
9#include <kunit/resource.h>
10#include <kunit/test.h>
11#include <kunit/test-bug.h>
12#include <kunit/attributes.h>
13#include <linux/kernel.h>
14#include <linux/module.h>
15#include <linux/moduleparam.h>
16#include <linux/panic.h>
17#include <linux/sched/debug.h>
18#include <linux/sched.h>
19
20#include "debugfs.h"
21#include "hooks-impl.h"
22#include "string-stream.h"
23#include "try-catch-impl.h"
24
25/*
26 * Hook to fail the current test and print an error message to the log.
27 */
28void __printf(3, 4) __kunit_fail_current_test_impl(const char *file, int line, const char *fmt, ...)
29{
30 va_list args;
31 int len;
32 char *buffer;
33
34 if (!current->kunit_test)
35 return;
36
37 kunit_set_failure(current->kunit_test);
38
39 /* kunit_err() only accepts literals, so evaluate the args first. */
40 va_start(args, fmt);
41 len = vsnprintf(NULL, 0, fmt, args) + 1;
42 va_end(args);
43
44 buffer = kunit_kmalloc(current->kunit_test, len, GFP_KERNEL);
45 if (!buffer)
46 return;
47
48 va_start(args, fmt);
49 vsnprintf(buffer, len, fmt, args);
50 va_end(args);
51
52 kunit_err(current->kunit_test, "%s:%d: %s", file, line, buffer);
53 kunit_kfree(current->kunit_test, buffer);
54}
55
56/*
57 * Enable KUnit tests to run.
58 */
59#ifdef CONFIG_KUNIT_DEFAULT_ENABLED
60static bool enable_param = true;
61#else
62static bool enable_param;
63#endif
64module_param_named(enable, enable_param, bool, 0);
65MODULE_PARM_DESC(enable, "Enable KUnit tests");
66
67/*
68 * KUnit statistic mode:
69 * 0 - disabled
70 * 1 - only when there is more than one subtest
71 * 2 - enabled
72 */
73static int kunit_stats_enabled = 1;
74module_param_named(stats_enabled, kunit_stats_enabled, int, 0644);
75MODULE_PARM_DESC(stats_enabled,
76 "Print test stats: never (0), only for multiple subtests (1), or always (2)");
77
78struct kunit_result_stats {
79 unsigned long passed;
80 unsigned long skipped;
81 unsigned long failed;
82 unsigned long total;
83};
84
85static bool kunit_should_print_stats(struct kunit_result_stats stats)
86{
87 if (kunit_stats_enabled == 0)
88 return false;
89
90 if (kunit_stats_enabled == 2)
91 return true;
92
93 return (stats.total > 1);
94}
95
96static void kunit_print_test_stats(struct kunit *test,
97 struct kunit_result_stats stats)
98{
99 if (!kunit_should_print_stats(stats))
100 return;
101
102 kunit_log(KERN_INFO, test,
103 KUNIT_SUBTEST_INDENT
104 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
105 test->name,
106 stats.passed,
107 stats.failed,
108 stats.skipped,
109 stats.total);
110}
111
112/* Append formatted message to log. */
113void kunit_log_append(struct string_stream *log, const char *fmt, ...)
114{
115 va_list args;
116
117 if (!log)
118 return;
119
120 va_start(args, fmt);
121 string_stream_vadd(log, fmt, args);
122 va_end(args);
123}
124EXPORT_SYMBOL_GPL(kunit_log_append);
125
126size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
127{
128 struct kunit_case *test_case;
129 size_t len = 0;
130
131 kunit_suite_for_each_test_case(suite, test_case)
132 len++;
133
134 return len;
135}
136EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
137
138/* Currently supported test levels */
139enum {
140 KUNIT_LEVEL_SUITE = 0,
141 KUNIT_LEVEL_CASE,
142 KUNIT_LEVEL_CASE_PARAM,
143};
144
145static void kunit_print_suite_start(struct kunit_suite *suite)
146{
147 /*
148 * We do not log the test suite header as doing so would
149 * mean debugfs display would consist of the test suite
150 * header prior to individual test results.
151 * Hence directly printk the suite status, and we will
152 * separately seq_printf() the suite header for the debugfs
153 * representation.
154 */
155 pr_info(KUNIT_SUBTEST_INDENT "KTAP version 1\n");
156 pr_info(KUNIT_SUBTEST_INDENT "# Subtest: %s\n",
157 suite->name);
158 kunit_print_attr((void *)suite, false, KUNIT_LEVEL_CASE);
159 pr_info(KUNIT_SUBTEST_INDENT "1..%zd\n",
160 kunit_suite_num_test_cases(suite));
161}
162
163static void kunit_print_ok_not_ok(struct kunit *test,
164 unsigned int test_level,
165 enum kunit_status status,
166 size_t test_number,
167 const char *description,
168 const char *directive)
169{
170 const char *directive_header = (status == KUNIT_SKIPPED) ? " # SKIP " : "";
171 const char *directive_body = (status == KUNIT_SKIPPED) ? directive : "";
172
173 /*
174 * When test is NULL assume that results are from the suite
175 * and today suite results are expected at level 0 only.
176 */
177 WARN(!test && test_level, "suite test level can't be %u!\n", test_level);
178
179 /*
180 * We do not log the test suite results as doing so would
181 * mean debugfs display would consist of an incorrect test
182 * number. Hence directly printk the suite result, and we will
183 * separately seq_printf() the suite results for the debugfs
184 * representation.
185 */
186 if (!test)
187 pr_info("%s %zd %s%s%s\n",
188 kunit_status_to_ok_not_ok(status),
189 test_number, description, directive_header,
190 directive_body);
191 else
192 kunit_log(KERN_INFO, test,
193 "%*s%s %zd %s%s%s",
194 KUNIT_INDENT_LEN * test_level, "",
195 kunit_status_to_ok_not_ok(status),
196 test_number, description, directive_header,
197 directive_body);
198}
199
200enum kunit_status kunit_suite_has_succeeded(struct kunit_suite *suite)
201{
202 const struct kunit_case *test_case;
203 enum kunit_status status = KUNIT_SKIPPED;
204
205 if (suite->suite_init_err)
206 return KUNIT_FAILURE;
207
208 kunit_suite_for_each_test_case(suite, test_case) {
209 if (test_case->status == KUNIT_FAILURE)
210 return KUNIT_FAILURE;
211 else if (test_case->status == KUNIT_SUCCESS)
212 status = KUNIT_SUCCESS;
213 }
214
215 return status;
216}
217EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
218
219static size_t kunit_suite_counter = 1;
220
221static void kunit_print_suite_end(struct kunit_suite *suite)
222{
223 kunit_print_ok_not_ok(NULL, KUNIT_LEVEL_SUITE,
224 kunit_suite_has_succeeded(suite),
225 kunit_suite_counter++,
226 suite->name,
227 suite->status_comment);
228}
229
230unsigned int kunit_test_case_num(struct kunit_suite *suite,
231 struct kunit_case *test_case)
232{
233 struct kunit_case *tc;
234 unsigned int i = 1;
235
236 kunit_suite_for_each_test_case(suite, tc) {
237 if (tc == test_case)
238 return i;
239 i++;
240 }
241
242 return 0;
243}
244EXPORT_SYMBOL_GPL(kunit_test_case_num);
245
246static void kunit_print_string_stream(struct kunit *test,
247 struct string_stream *stream)
248{
249 struct string_stream_fragment *fragment;
250 char *buf;
251
252 if (string_stream_is_empty(stream))
253 return;
254
255 buf = string_stream_get_string(stream);
256 if (!buf) {
257 kunit_err(test,
258 "Could not allocate buffer, dumping stream:\n");
259 list_for_each_entry(fragment, &stream->fragments, node) {
260 kunit_err(test, "%s", fragment->fragment);
261 }
262 kunit_err(test, "\n");
263 } else {
264 kunit_err(test, "%s", buf);
265 kfree(buf);
266 }
267}
268
269static void kunit_fail(struct kunit *test, const struct kunit_loc *loc,
270 enum kunit_assert_type type, const struct kunit_assert *assert,
271 assert_format_t assert_format, const struct va_format *message)
272{
273 struct string_stream *stream;
274
275 kunit_set_failure(test);
276
277 stream = kunit_alloc_string_stream(test, GFP_KERNEL);
278 if (IS_ERR(stream)) {
279 WARN(true,
280 "Could not allocate stream to print failed assertion in %s:%d\n",
281 loc->file,
282 loc->line);
283 return;
284 }
285
286 kunit_assert_prologue(loc, type, stream);
287 assert_format(assert, message, stream);
288
289 kunit_print_string_stream(test, stream);
290
291 kunit_free_string_stream(test, stream);
292}
293
294void __noreturn __kunit_abort(struct kunit *test)
295{
296 kunit_try_catch_throw(&test->try_catch); /* Does not return. */
297
298 /*
299 * Throw could not abort from test.
300 *
301 * XXX: we should never reach this line! As kunit_try_catch_throw is
302 * marked __noreturn.
303 */
304 WARN_ONCE(true, "Throw could not abort from test!\n");
305}
306EXPORT_SYMBOL_GPL(__kunit_abort);
307
308void __kunit_do_failed_assertion(struct kunit *test,
309 const struct kunit_loc *loc,
310 enum kunit_assert_type type,
311 const struct kunit_assert *assert,
312 assert_format_t assert_format,
313 const char *fmt, ...)
314{
315 va_list args;
316 struct va_format message;
317 va_start(args, fmt);
318
319 message.fmt = fmt;
320 message.va = &args;
321
322 kunit_fail(test, loc, type, assert, assert_format, &message);
323
324 va_end(args);
325}
326EXPORT_SYMBOL_GPL(__kunit_do_failed_assertion);
327
328void kunit_init_test(struct kunit *test, const char *name, struct string_stream *log)
329{
330 spin_lock_init(&test->lock);
331 INIT_LIST_HEAD(&test->resources);
332 test->name = name;
333 test->log = log;
334 if (test->log)
335 string_stream_clear(log);
336 test->status = KUNIT_SUCCESS;
337 test->status_comment[0] = '\0';
338}
339EXPORT_SYMBOL_GPL(kunit_init_test);
340
341/* Only warn when a test takes more than twice the threshold */
342#define KUNIT_SPEED_WARNING_MULTIPLIER 2
343
344/* Slow tests are defined as taking more than 1s */
345#define KUNIT_SPEED_SLOW_THRESHOLD_S 1
346
347#define KUNIT_SPEED_SLOW_WARNING_THRESHOLD_S \
348 (KUNIT_SPEED_WARNING_MULTIPLIER * KUNIT_SPEED_SLOW_THRESHOLD_S)
349
350#define s_to_timespec64(s) ns_to_timespec64((s) * NSEC_PER_SEC)
351
352static void kunit_run_case_check_speed(struct kunit *test,
353 struct kunit_case *test_case,
354 struct timespec64 duration)
355{
356 struct timespec64 slow_thr =
357 s_to_timespec64(KUNIT_SPEED_SLOW_WARNING_THRESHOLD_S);
358 enum kunit_speed speed = test_case->attr.speed;
359
360 if (timespec64_compare(&duration, &slow_thr) < 0)
361 return;
362
363 if (speed == KUNIT_SPEED_VERY_SLOW || speed == KUNIT_SPEED_SLOW)
364 return;
365
366 kunit_warn(test,
367 "Test should be marked slow (runtime: %lld.%09lds)",
368 duration.tv_sec, duration.tv_nsec);
369}
370
371/*
372 * Initializes and runs test case. Does not clean up or do post validations.
373 */
374static void kunit_run_case_internal(struct kunit *test,
375 struct kunit_suite *suite,
376 struct kunit_case *test_case)
377{
378 struct timespec64 start, end;
379
380 if (suite->init) {
381 int ret;
382
383 ret = suite->init(test);
384 if (ret) {
385 kunit_err(test, "failed to initialize: %d\n", ret);
386 kunit_set_failure(test);
387 return;
388 }
389 }
390
391 ktime_get_ts64(&start);
392
393 test_case->run_case(test);
394
395 ktime_get_ts64(&end);
396
397 kunit_run_case_check_speed(test, test_case, timespec64_sub(end, start));
398}
399
400static void kunit_case_internal_cleanup(struct kunit *test)
401{
402 kunit_cleanup(test);
403}
404
405/*
406 * Performs post validations and cleanup after a test case was run.
407 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
408 */
409static void kunit_run_case_cleanup(struct kunit *test,
410 struct kunit_suite *suite)
411{
412 if (suite->exit)
413 suite->exit(test);
414
415 kunit_case_internal_cleanup(test);
416}
417
418struct kunit_try_catch_context {
419 struct kunit *test;
420 struct kunit_suite *suite;
421 struct kunit_case *test_case;
422};
423
424static void kunit_try_run_case(void *data)
425{
426 struct kunit_try_catch_context *ctx = data;
427 struct kunit *test = ctx->test;
428 struct kunit_suite *suite = ctx->suite;
429 struct kunit_case *test_case = ctx->test_case;
430
431 current->kunit_test = test;
432
433 /*
434 * kunit_run_case_internal may encounter a fatal error; if it does,
435 * abort will be called, this thread will exit, and finally the parent
436 * thread will resume control and handle any necessary clean up.
437 */
438 kunit_run_case_internal(test, suite, test_case);
439}
440
441static void kunit_try_run_case_cleanup(void *data)
442{
443 struct kunit_try_catch_context *ctx = data;
444 struct kunit *test = ctx->test;
445 struct kunit_suite *suite = ctx->suite;
446
447 current->kunit_test = test;
448
449 kunit_run_case_cleanup(test, suite);
450}
451
452static void kunit_catch_run_case_cleanup(void *data)
453{
454 struct kunit_try_catch_context *ctx = data;
455 struct kunit *test = ctx->test;
456 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
457
458 /* It is always a failure if cleanup aborts. */
459 kunit_set_failure(test);
460
461 if (try_exit_code) {
462 /*
463 * Test case could not finish, we have no idea what state it is
464 * in, so don't do clean up.
465 */
466 if (try_exit_code == -ETIMEDOUT) {
467 kunit_err(test, "test case cleanup timed out\n");
468 /*
469 * Unknown internal error occurred preventing test case from
470 * running, so there is nothing to clean up.
471 */
472 } else {
473 kunit_err(test, "internal error occurred during test case cleanup: %d\n",
474 try_exit_code);
475 }
476 return;
477 }
478
479 kunit_err(test, "test aborted during cleanup. continuing without cleaning up\n");
480}
481
482
483static void kunit_catch_run_case(void *data)
484{
485 struct kunit_try_catch_context *ctx = data;
486 struct kunit *test = ctx->test;
487 int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
488
489 if (try_exit_code) {
490 kunit_set_failure(test);
491 /*
492 * Test case could not finish, we have no idea what state it is
493 * in, so don't do clean up.
494 */
495 if (try_exit_code == -ETIMEDOUT) {
496 kunit_err(test, "test case timed out\n");
497 /*
498 * Unknown internal error occurred preventing test case from
499 * running, so there is nothing to clean up.
500 */
501 } else {
502 kunit_err(test, "internal error occurred preventing test case from running: %d\n",
503 try_exit_code);
504 }
505 return;
506 }
507}
508
509/*
510 * Performs all logic to run a test case. It also catches most errors that
511 * occur in a test case and reports them as failures.
512 */
513static void kunit_run_case_catch_errors(struct kunit_suite *suite,
514 struct kunit_case *test_case,
515 struct kunit *test)
516{
517 struct kunit_try_catch_context context;
518 struct kunit_try_catch *try_catch;
519
520 try_catch = &test->try_catch;
521
522 kunit_try_catch_init(try_catch,
523 test,
524 kunit_try_run_case,
525 kunit_catch_run_case);
526 context.test = test;
527 context.suite = suite;
528 context.test_case = test_case;
529 kunit_try_catch_run(try_catch, &context);
530
531 /* Now run the cleanup */
532 kunit_try_catch_init(try_catch,
533 test,
534 kunit_try_run_case_cleanup,
535 kunit_catch_run_case_cleanup);
536 kunit_try_catch_run(try_catch, &context);
537
538 /* Propagate the parameter result to the test case. */
539 if (test->status == KUNIT_FAILURE)
540 test_case->status = KUNIT_FAILURE;
541 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS)
542 test_case->status = KUNIT_SUCCESS;
543}
544
545static void kunit_print_suite_stats(struct kunit_suite *suite,
546 struct kunit_result_stats suite_stats,
547 struct kunit_result_stats param_stats)
548{
549 if (kunit_should_print_stats(suite_stats)) {
550 kunit_log(KERN_INFO, suite,
551 "# %s: pass:%lu fail:%lu skip:%lu total:%lu",
552 suite->name,
553 suite_stats.passed,
554 suite_stats.failed,
555 suite_stats.skipped,
556 suite_stats.total);
557 }
558
559 if (kunit_should_print_stats(param_stats)) {
560 kunit_log(KERN_INFO, suite,
561 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu",
562 param_stats.passed,
563 param_stats.failed,
564 param_stats.skipped,
565 param_stats.total);
566 }
567}
568
569static void kunit_update_stats(struct kunit_result_stats *stats,
570 enum kunit_status status)
571{
572 switch (status) {
573 case KUNIT_SUCCESS:
574 stats->passed++;
575 break;
576 case KUNIT_SKIPPED:
577 stats->skipped++;
578 break;
579 case KUNIT_FAILURE:
580 stats->failed++;
581 break;
582 }
583
584 stats->total++;
585}
586
587static void kunit_accumulate_stats(struct kunit_result_stats *total,
588 struct kunit_result_stats add)
589{
590 total->passed += add.passed;
591 total->skipped += add.skipped;
592 total->failed += add.failed;
593 total->total += add.total;
594}
595
596int kunit_run_tests(struct kunit_suite *suite)
597{
598 char param_desc[KUNIT_PARAM_DESC_SIZE];
599 struct kunit_case *test_case;
600 struct kunit_result_stats suite_stats = { 0 };
601 struct kunit_result_stats total_stats = { 0 };
602
603 /* Taint the kernel so we know we've run tests. */
604 add_taint(TAINT_TEST, LOCKDEP_STILL_OK);
605
606 if (suite->suite_init) {
607 suite->suite_init_err = suite->suite_init(suite);
608 if (suite->suite_init_err) {
609 kunit_err(suite, KUNIT_SUBTEST_INDENT
610 "# failed to initialize (%d)", suite->suite_init_err);
611 goto suite_end;
612 }
613 }
614
615 kunit_print_suite_start(suite);
616
617 kunit_suite_for_each_test_case(suite, test_case) {
618 struct kunit test = { .param_value = NULL, .param_index = 0 };
619 struct kunit_result_stats param_stats = { 0 };
620
621 kunit_init_test(&test, test_case->name, test_case->log);
622 if (test_case->status == KUNIT_SKIPPED) {
623 /* Test marked as skip */
624 test.status = KUNIT_SKIPPED;
625 kunit_update_stats(¶m_stats, test.status);
626 } else if (!test_case->generate_params) {
627 /* Non-parameterised test. */
628 test_case->status = KUNIT_SKIPPED;
629 kunit_run_case_catch_errors(suite, test_case, &test);
630 kunit_update_stats(¶m_stats, test.status);
631 } else {
632 /* Get initial param. */
633 param_desc[0] = '\0';
634 test.param_value = test_case->generate_params(NULL, param_desc);
635 test_case->status = KUNIT_SKIPPED;
636 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
637 "KTAP version 1\n");
638 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT
639 "# Subtest: %s", test_case->name);
640
641 while (test.param_value) {
642 kunit_run_case_catch_errors(suite, test_case, &test);
643
644 if (param_desc[0] == '\0') {
645 snprintf(param_desc, sizeof(param_desc),
646 "param-%d", test.param_index);
647 }
648
649 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE_PARAM,
650 test.status,
651 test.param_index + 1,
652 param_desc,
653 test.status_comment);
654
655 kunit_update_stats(¶m_stats, test.status);
656
657 /* Get next param. */
658 param_desc[0] = '\0';
659 test.param_value = test_case->generate_params(test.param_value, param_desc);
660 test.param_index++;
661 test.status = KUNIT_SUCCESS;
662 test.status_comment[0] = '\0';
663 }
664 }
665
666 kunit_print_attr((void *)test_case, true, KUNIT_LEVEL_CASE);
667
668 kunit_print_test_stats(&test, param_stats);
669
670 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE, test_case->status,
671 kunit_test_case_num(suite, test_case),
672 test_case->name,
673 test.status_comment);
674
675 kunit_update_stats(&suite_stats, test_case->status);
676 kunit_accumulate_stats(&total_stats, param_stats);
677 }
678
679 if (suite->suite_exit)
680 suite->suite_exit(suite);
681
682 kunit_print_suite_stats(suite, suite_stats, total_stats);
683suite_end:
684 kunit_print_suite_end(suite);
685
686 return 0;
687}
688EXPORT_SYMBOL_GPL(kunit_run_tests);
689
690static void kunit_init_suite(struct kunit_suite *suite)
691{
692 kunit_debugfs_create_suite(suite);
693 suite->status_comment[0] = '\0';
694 suite->suite_init_err = 0;
695}
696
697bool kunit_enabled(void)
698{
699 return enable_param;
700}
701
702int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites)
703{
704 unsigned int i;
705
706 if (!kunit_enabled() && num_suites > 0) {
707 pr_info("kunit: disabled\n");
708 return 0;
709 }
710
711 kunit_suite_counter = 1;
712
713 static_branch_inc(&kunit_running);
714
715 for (i = 0; i < num_suites; i++) {
716 kunit_init_suite(suites[i]);
717 kunit_run_tests(suites[i]);
718 }
719
720 static_branch_dec(&kunit_running);
721 return 0;
722}
723EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
724
725static void kunit_exit_suite(struct kunit_suite *suite)
726{
727 kunit_debugfs_destroy_suite(suite);
728}
729
730void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites)
731{
732 unsigned int i;
733
734 if (!kunit_enabled())
735 return;
736
737 for (i = 0; i < num_suites; i++)
738 kunit_exit_suite(suites[i]);
739}
740EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
741
742#ifdef CONFIG_MODULES
743static void kunit_module_init(struct module *mod)
744{
745 struct kunit_suite_set suite_set = {
746 mod->kunit_suites, mod->kunit_suites + mod->num_kunit_suites,
747 };
748 const char *action = kunit_action();
749 int err = 0;
750
751 suite_set = kunit_filter_suites(&suite_set,
752 kunit_filter_glob() ?: "*.*",
753 kunit_filter(), kunit_filter_action(),
754 &err);
755 if (err)
756 pr_err("kunit module: error filtering suites: %d\n", err);
757
758 mod->kunit_suites = (struct kunit_suite **)suite_set.start;
759 mod->num_kunit_suites = suite_set.end - suite_set.start;
760
761 if (!action)
762 kunit_exec_run_tests(&suite_set, false);
763 else if (!strcmp(action, "list"))
764 kunit_exec_list_tests(&suite_set, false);
765 else if (!strcmp(action, "list_attr"))
766 kunit_exec_list_tests(&suite_set, true);
767 else
768 pr_err("kunit: unknown action '%s'\n", action);
769}
770
771static void kunit_module_exit(struct module *mod)
772{
773 struct kunit_suite_set suite_set = {
774 mod->kunit_suites, mod->kunit_suites + mod->num_kunit_suites,
775 };
776 const char *action = kunit_action();
777
778 if (!action)
779 __kunit_test_suites_exit(mod->kunit_suites,
780 mod->num_kunit_suites);
781
782 if (suite_set.start)
783 kunit_free_suite_set(suite_set);
784}
785
786static int kunit_module_notify(struct notifier_block *nb, unsigned long val,
787 void *data)
788{
789 struct module *mod = data;
790
791 switch (val) {
792 case MODULE_STATE_LIVE:
793 break;
794 case MODULE_STATE_GOING:
795 kunit_module_exit(mod);
796 break;
797 case MODULE_STATE_COMING:
798 kunit_module_init(mod);
799 break;
800 case MODULE_STATE_UNFORMED:
801 break;
802 }
803
804 return 0;
805}
806
807static struct notifier_block kunit_mod_nb = {
808 .notifier_call = kunit_module_notify,
809 .priority = 0,
810};
811#endif
812
813void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
814{
815 void *data;
816
817 data = kmalloc_array(n, size, gfp);
818
819 if (!data)
820 return NULL;
821
822 if (kunit_add_action_or_reset(test, (kunit_action_t *)kfree, data) != 0)
823 return NULL;
824
825 return data;
826}
827EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
828
829void kunit_kfree(struct kunit *test, const void *ptr)
830{
831 if (!ptr)
832 return;
833
834 kunit_release_action(test, (kunit_action_t *)kfree, (void *)ptr);
835}
836EXPORT_SYMBOL_GPL(kunit_kfree);
837
838void kunit_cleanup(struct kunit *test)
839{
840 struct kunit_resource *res;
841 unsigned long flags;
842
843 /*
844 * test->resources is a stack - each allocation must be freed in the
845 * reverse order from which it was added since one resource may depend
846 * on another for its entire lifetime.
847 * Also, we cannot use the normal list_for_each constructs, even the
848 * safe ones because *arbitrary* nodes may be deleted when
849 * kunit_resource_free is called; the list_for_each_safe variants only
850 * protect against the current node being deleted, not the next.
851 */
852 while (true) {
853 spin_lock_irqsave(&test->lock, flags);
854 if (list_empty(&test->resources)) {
855 spin_unlock_irqrestore(&test->lock, flags);
856 break;
857 }
858 res = list_last_entry(&test->resources,
859 struct kunit_resource,
860 node);
861 /*
862 * Need to unlock here as a resource may remove another
863 * resource, and this can't happen if the test->lock
864 * is held.
865 */
866 spin_unlock_irqrestore(&test->lock, flags);
867 kunit_remove_resource(test, res);
868 }
869 current->kunit_test = NULL;
870}
871EXPORT_SYMBOL_GPL(kunit_cleanup);
872
873static int __init kunit_init(void)
874{
875 /* Install the KUnit hook functions. */
876 kunit_install_hooks();
877
878 kunit_debugfs_init();
879#ifdef CONFIG_MODULES
880 return register_module_notifier(&kunit_mod_nb);
881#else
882 return 0;
883#endif
884}
885late_initcall(kunit_init);
886
887static void __exit kunit_exit(void)
888{
889 memset(&kunit_hooks, 0, sizeof(kunit_hooks));
890#ifdef CONFIG_MODULES
891 unregister_module_notifier(&kunit_mod_nb);
892#endif
893 kunit_debugfs_cleanup();
894}
895module_exit(kunit_exit);
896
897MODULE_LICENSE("GPL v2");