Linux Audio

Check our new training course

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