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