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