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