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 28 static DEFINE_MUTEX(kunit_run_lock); 29 30 /* 31 * Hook to fail the current test and print an error message to the log. 32 */ 33 void __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 65 static bool enable_param = true; 66 #else 67 static bool enable_param; 68 #endif 69 module_param_named(enable, enable_param, bool, 0); 70 MODULE_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 */ 78 static int kunit_stats_enabled = 1; 79 module_param_named(stats_enabled, kunit_stats_enabled, int, 0644); 80 MODULE_PARM_DESC(stats_enabled, 81 "Print test stats: never (0), only for multiple subtests (1), or always (2)"); 82 83 struct kunit_result_stats { 84 unsigned long passed; 85 unsigned long skipped; 86 unsigned long failed; 87 unsigned long total; 88 }; 89 90 static 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 101 static 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. */ 118 void 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 } 129 EXPORT_SYMBOL_GPL(kunit_log_append); 130 131 size_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 } 141 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases); 142 143 /* Currently supported test levels */ 144 enum { 145 KUNIT_LEVEL_SUITE = 0, 146 KUNIT_LEVEL_CASE, 147 KUNIT_LEVEL_CASE_PARAM, 148 }; 149 150 static 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 168 static 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 205 enum 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 } 222 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded); 223 224 static size_t kunit_suite_counter = 1; 225 226 static 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 235 unsigned 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 } 249 EXPORT_SYMBOL_GPL(kunit_test_case_num); 250 251 static 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 274 static 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 299 void __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 } 311 EXPORT_SYMBOL_GPL(__kunit_abort); 312 313 void __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 } 331 EXPORT_SYMBOL_GPL(__kunit_do_failed_assertion); 332 333 void 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 } 344 EXPORT_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 357 static 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 /* Returns timeout multiplier based on speed. 377 * DEFAULT: 1 378 * KUNIT_SPEED_SLOW: 3 379 * KUNIT_SPEED_VERY_SLOW: 12 380 */ 381 static int kunit_timeout_mult(enum kunit_speed speed) 382 { 383 switch (speed) { 384 case KUNIT_SPEED_SLOW: 385 return 3; 386 case KUNIT_SPEED_VERY_SLOW: 387 return 12; 388 default: 389 return 1; 390 } 391 } 392 393 static unsigned long kunit_test_timeout(struct kunit_suite *suite, struct kunit_case *test_case) 394 { 395 int mult = 1; 396 /* 397 * TODO: Make the default (base) timeout configurable, so that users with 398 * particularly slow or fast machines can successfully run tests, while 399 * still taking advantage of the relative speed. 400 */ 401 unsigned long default_timeout = 300; 402 403 /* 404 * The default test timeout is 300 seconds and will be adjusted by mult 405 * based on the test speed. The test speed will be overridden by the 406 * innermost test component. 407 */ 408 if (suite->attr.speed != KUNIT_SPEED_UNSET) 409 mult = kunit_timeout_mult(suite->attr.speed); 410 if (test_case->attr.speed != KUNIT_SPEED_UNSET) 411 mult = kunit_timeout_mult(test_case->attr.speed); 412 return mult * default_timeout * msecs_to_jiffies(MSEC_PER_SEC); 413 } 414 415 416 /* 417 * Initializes and runs test case. Does not clean up or do post validations. 418 */ 419 static void kunit_run_case_internal(struct kunit *test, 420 struct kunit_suite *suite, 421 struct kunit_case *test_case) 422 { 423 struct timespec64 start, end; 424 425 if (suite->init) { 426 int ret; 427 428 ret = suite->init(test); 429 if (ret) { 430 kunit_err(test, "failed to initialize: %d\n", ret); 431 kunit_set_failure(test); 432 return; 433 } 434 } 435 436 ktime_get_ts64(&start); 437 438 test_case->run_case(test); 439 440 ktime_get_ts64(&end); 441 442 kunit_run_case_check_speed(test, test_case, timespec64_sub(end, start)); 443 } 444 445 static void kunit_case_internal_cleanup(struct kunit *test) 446 { 447 kunit_cleanup(test); 448 } 449 450 /* 451 * Performs post validations and cleanup after a test case was run. 452 * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal! 453 */ 454 static void kunit_run_case_cleanup(struct kunit *test, 455 struct kunit_suite *suite) 456 { 457 if (suite->exit) 458 suite->exit(test); 459 460 kunit_case_internal_cleanup(test); 461 } 462 463 struct kunit_try_catch_context { 464 struct kunit *test; 465 struct kunit_suite *suite; 466 struct kunit_case *test_case; 467 }; 468 469 static void kunit_try_run_case(void *data) 470 { 471 struct kunit_try_catch_context *ctx = data; 472 struct kunit *test = ctx->test; 473 struct kunit_suite *suite = ctx->suite; 474 struct kunit_case *test_case = ctx->test_case; 475 476 current->kunit_test = test; 477 478 /* 479 * kunit_run_case_internal may encounter a fatal error; if it does, 480 * abort will be called, this thread will exit, and finally the parent 481 * thread will resume control and handle any necessary clean up. 482 */ 483 kunit_run_case_internal(test, suite, test_case); 484 } 485 486 static void kunit_try_run_case_cleanup(void *data) 487 { 488 struct kunit_try_catch_context *ctx = data; 489 struct kunit *test = ctx->test; 490 struct kunit_suite *suite = ctx->suite; 491 492 current->kunit_test = test; 493 494 kunit_run_case_cleanup(test, suite); 495 } 496 497 static void kunit_catch_run_case_cleanup(void *data) 498 { 499 struct kunit_try_catch_context *ctx = data; 500 struct kunit *test = ctx->test; 501 int try_exit_code = kunit_try_catch_get_result(&test->try_catch); 502 503 /* It is always a failure if cleanup aborts. */ 504 kunit_set_failure(test); 505 506 if (try_exit_code) { 507 /* 508 * Test case could not finish, we have no idea what state it is 509 * in, so don't do clean up. 510 */ 511 if (try_exit_code == -ETIMEDOUT) { 512 kunit_err(test, "test case cleanup timed out\n"); 513 /* 514 * Unknown internal error occurred preventing test case from 515 * running, so there is nothing to clean up. 516 */ 517 } else { 518 kunit_err(test, "internal error occurred during test case cleanup: %d\n", 519 try_exit_code); 520 } 521 return; 522 } 523 524 kunit_err(test, "test aborted during cleanup. continuing without cleaning up\n"); 525 } 526 527 528 static void kunit_catch_run_case(void *data) 529 { 530 struct kunit_try_catch_context *ctx = data; 531 struct kunit *test = ctx->test; 532 int try_exit_code = kunit_try_catch_get_result(&test->try_catch); 533 534 if (try_exit_code) { 535 kunit_set_failure(test); 536 /* 537 * Test case could not finish, we have no idea what state it is 538 * in, so don't do clean up. 539 */ 540 if (try_exit_code == -ETIMEDOUT) { 541 kunit_err(test, "test case timed out\n"); 542 /* 543 * Unknown internal error occurred preventing test case from 544 * running, so there is nothing to clean up. 545 */ 546 } else { 547 kunit_err(test, "internal error occurred preventing test case from running: %d\n", 548 try_exit_code); 549 } 550 return; 551 } 552 } 553 554 /* 555 * Performs all logic to run a test case. It also catches most errors that 556 * occur in a test case and reports them as failures. 557 */ 558 static void kunit_run_case_catch_errors(struct kunit_suite *suite, 559 struct kunit_case *test_case, 560 struct kunit *test) 561 { 562 struct kunit_try_catch_context context; 563 struct kunit_try_catch *try_catch; 564 565 try_catch = &test->try_catch; 566 567 kunit_try_catch_init(try_catch, 568 test, 569 kunit_try_run_case, 570 kunit_catch_run_case, 571 kunit_test_timeout(suite, test_case)); 572 context.test = test; 573 context.suite = suite; 574 context.test_case = test_case; 575 kunit_try_catch_run(try_catch, &context); 576 577 /* Now run the cleanup */ 578 kunit_try_catch_init(try_catch, 579 test, 580 kunit_try_run_case_cleanup, 581 kunit_catch_run_case_cleanup, 582 kunit_test_timeout(suite, test_case)); 583 kunit_try_catch_run(try_catch, &context); 584 585 /* Propagate the parameter result to the test case. */ 586 if (test->status == KUNIT_FAILURE) 587 test_case->status = KUNIT_FAILURE; 588 else if (test_case->status != KUNIT_FAILURE && test->status == KUNIT_SUCCESS) 589 test_case->status = KUNIT_SUCCESS; 590 } 591 592 static void kunit_print_suite_stats(struct kunit_suite *suite, 593 struct kunit_result_stats suite_stats, 594 struct kunit_result_stats param_stats) 595 { 596 if (kunit_should_print_stats(suite_stats)) { 597 kunit_log(KERN_INFO, suite, 598 "# %s: pass:%lu fail:%lu skip:%lu total:%lu", 599 suite->name, 600 suite_stats.passed, 601 suite_stats.failed, 602 suite_stats.skipped, 603 suite_stats.total); 604 } 605 606 if (kunit_should_print_stats(param_stats)) { 607 kunit_log(KERN_INFO, suite, 608 "# Totals: pass:%lu fail:%lu skip:%lu total:%lu", 609 param_stats.passed, 610 param_stats.failed, 611 param_stats.skipped, 612 param_stats.total); 613 } 614 } 615 616 static void kunit_update_stats(struct kunit_result_stats *stats, 617 enum kunit_status status) 618 { 619 switch (status) { 620 case KUNIT_SUCCESS: 621 stats->passed++; 622 break; 623 case KUNIT_SKIPPED: 624 stats->skipped++; 625 break; 626 case KUNIT_FAILURE: 627 stats->failed++; 628 break; 629 } 630 631 stats->total++; 632 } 633 634 static void kunit_accumulate_stats(struct kunit_result_stats *total, 635 struct kunit_result_stats add) 636 { 637 total->passed += add.passed; 638 total->skipped += add.skipped; 639 total->failed += add.failed; 640 total->total += add.total; 641 } 642 643 int kunit_run_tests(struct kunit_suite *suite) 644 { 645 char param_desc[KUNIT_PARAM_DESC_SIZE]; 646 struct kunit_case *test_case; 647 struct kunit_result_stats suite_stats = { 0 }; 648 struct kunit_result_stats total_stats = { 0 }; 649 650 /* Taint the kernel so we know we've run tests. */ 651 add_taint(TAINT_TEST, LOCKDEP_STILL_OK); 652 653 if (suite->suite_init) { 654 suite->suite_init_err = suite->suite_init(suite); 655 if (suite->suite_init_err) { 656 kunit_err(suite, KUNIT_SUBTEST_INDENT 657 "# failed to initialize (%d)", suite->suite_init_err); 658 goto suite_end; 659 } 660 } 661 662 kunit_print_suite_start(suite); 663 664 kunit_suite_for_each_test_case(suite, test_case) { 665 struct kunit test = { .param_value = NULL, .param_index = 0 }; 666 struct kunit_result_stats param_stats = { 0 }; 667 668 kunit_init_test(&test, test_case->name, test_case->log); 669 if (test_case->status == KUNIT_SKIPPED) { 670 /* Test marked as skip */ 671 test.status = KUNIT_SKIPPED; 672 kunit_update_stats(¶m_stats, test.status); 673 } else if (!test_case->generate_params) { 674 /* Non-parameterised test. */ 675 test_case->status = KUNIT_SKIPPED; 676 kunit_run_case_catch_errors(suite, test_case, &test); 677 kunit_update_stats(¶m_stats, test.status); 678 } else { 679 /* Get initial param. */ 680 param_desc[0] = '\0'; 681 test.param_value = test_case->generate_params(NULL, param_desc); 682 test_case->status = KUNIT_SKIPPED; 683 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT 684 "KTAP version 1\n"); 685 kunit_log(KERN_INFO, &test, KUNIT_SUBTEST_INDENT KUNIT_SUBTEST_INDENT 686 "# Subtest: %s", test_case->name); 687 688 while (test.param_value) { 689 kunit_run_case_catch_errors(suite, test_case, &test); 690 691 if (param_desc[0] == '\0') { 692 snprintf(param_desc, sizeof(param_desc), 693 "param-%d", test.param_index); 694 } 695 696 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE_PARAM, 697 test.status, 698 test.param_index + 1, 699 param_desc, 700 test.status_comment); 701 702 kunit_update_stats(¶m_stats, test.status); 703 704 /* Get next param. */ 705 param_desc[0] = '\0'; 706 test.param_value = test_case->generate_params(test.param_value, param_desc); 707 test.param_index++; 708 test.status = KUNIT_SUCCESS; 709 test.status_comment[0] = '\0'; 710 test.priv = NULL; 711 } 712 } 713 714 kunit_print_attr((void *)test_case, true, KUNIT_LEVEL_CASE); 715 716 kunit_print_test_stats(&test, param_stats); 717 718 kunit_print_ok_not_ok(&test, KUNIT_LEVEL_CASE, test_case->status, 719 kunit_test_case_num(suite, test_case), 720 test_case->name, 721 test.status_comment); 722 723 kunit_update_stats(&suite_stats, test_case->status); 724 kunit_accumulate_stats(&total_stats, param_stats); 725 } 726 727 if (suite->suite_exit) 728 suite->suite_exit(suite); 729 730 kunit_print_suite_stats(suite, suite_stats, total_stats); 731 suite_end: 732 kunit_print_suite_end(suite); 733 734 return 0; 735 } 736 EXPORT_SYMBOL_GPL(kunit_run_tests); 737 738 static void kunit_init_suite(struct kunit_suite *suite) 739 { 740 kunit_debugfs_create_suite(suite); 741 suite->status_comment[0] = '\0'; 742 suite->suite_init_err = 0; 743 744 if (suite->log) 745 string_stream_clear(suite->log); 746 } 747 748 bool kunit_enabled(void) 749 { 750 return enable_param; 751 } 752 753 int __kunit_test_suites_init(struct kunit_suite * const * const suites, int num_suites, 754 bool run_tests) 755 { 756 unsigned int i; 757 758 if (num_suites == 0) 759 return 0; 760 761 if (!kunit_enabled() && num_suites > 0) { 762 pr_info("kunit: disabled\n"); 763 return 0; 764 } 765 766 kunit_suite_counter = 1; 767 768 /* Use mutex lock to guard against running tests concurrently. */ 769 if (mutex_lock_interruptible(&kunit_run_lock)) { 770 pr_err("kunit: test interrupted\n"); 771 return -EINTR; 772 } 773 static_branch_inc(&kunit_running); 774 775 for (i = 0; i < num_suites; i++) { 776 kunit_init_suite(suites[i]); 777 if (run_tests) 778 kunit_run_tests(suites[i]); 779 } 780 781 static_branch_dec(&kunit_running); 782 mutex_unlock(&kunit_run_lock); 783 return 0; 784 } 785 EXPORT_SYMBOL_GPL(__kunit_test_suites_init); 786 787 static void kunit_exit_suite(struct kunit_suite *suite) 788 { 789 kunit_debugfs_destroy_suite(suite); 790 } 791 792 void __kunit_test_suites_exit(struct kunit_suite **suites, int num_suites) 793 { 794 unsigned int i; 795 796 if (!kunit_enabled()) 797 return; 798 799 for (i = 0; i < num_suites; i++) 800 kunit_exit_suite(suites[i]); 801 } 802 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit); 803 804 #ifdef CONFIG_MODULES 805 static void kunit_module_init(struct module *mod) 806 { 807 struct kunit_suite_set suite_set, filtered_set; 808 struct kunit_suite_set normal_suite_set = { 809 mod->kunit_suites, mod->kunit_suites + mod->num_kunit_suites, 810 }; 811 struct kunit_suite_set init_suite_set = { 812 mod->kunit_init_suites, mod->kunit_init_suites + mod->num_kunit_init_suites, 813 }; 814 const char *action = kunit_action(); 815 int err = 0; 816 817 if (mod->num_kunit_init_suites > 0) 818 suite_set = kunit_merge_suite_sets(init_suite_set, normal_suite_set); 819 else 820 suite_set = normal_suite_set; 821 822 filtered_set = kunit_filter_suites(&suite_set, 823 kunit_filter_glob() ?: "*.*", 824 kunit_filter(), kunit_filter_action(), 825 &err); 826 if (err) 827 pr_err("kunit module: error filtering suites: %d\n", err); 828 829 mod->kunit_suites = (struct kunit_suite **)filtered_set.start; 830 mod->num_kunit_suites = filtered_set.end - filtered_set.start; 831 832 if (mod->num_kunit_init_suites > 0) 833 kfree(suite_set.start); 834 835 if (!action) 836 kunit_exec_run_tests(&filtered_set, false); 837 else if (!strcmp(action, "list")) 838 kunit_exec_list_tests(&filtered_set, false); 839 else if (!strcmp(action, "list_attr")) 840 kunit_exec_list_tests(&filtered_set, true); 841 else 842 pr_err("kunit: unknown action '%s'\n", action); 843 } 844 845 static void kunit_module_exit(struct module *mod) 846 { 847 struct kunit_suite_set suite_set = { 848 mod->kunit_suites, mod->kunit_suites + mod->num_kunit_suites, 849 }; 850 const char *action = kunit_action(); 851 852 /* 853 * Check if the start address is a valid virtual address to detect 854 * if the module load sequence has failed and the suite set has not 855 * been initialized and filtered. 856 */ 857 if (!suite_set.start || !virt_addr_valid(suite_set.start)) 858 return; 859 860 if (!action) 861 __kunit_test_suites_exit(mod->kunit_suites, 862 mod->num_kunit_suites); 863 864 kunit_free_suite_set(suite_set); 865 } 866 867 static int kunit_module_notify(struct notifier_block *nb, unsigned long val, 868 void *data) 869 { 870 struct module *mod = data; 871 872 switch (val) { 873 case MODULE_STATE_LIVE: 874 kunit_module_init(mod); 875 break; 876 case MODULE_STATE_GOING: 877 kunit_module_exit(mod); 878 break; 879 case MODULE_STATE_COMING: 880 break; 881 case MODULE_STATE_UNFORMED: 882 break; 883 } 884 885 return 0; 886 } 887 888 static struct notifier_block kunit_mod_nb = { 889 .notifier_call = kunit_module_notify, 890 .priority = 0, 891 }; 892 #endif 893 894 KUNIT_DEFINE_ACTION_WRAPPER(kfree_action_wrapper, kfree, const void *) 895 896 void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp) 897 { 898 void *data; 899 900 data = kmalloc_array(n, size, gfp); 901 902 if (!data) 903 return NULL; 904 905 if (kunit_add_action_or_reset(test, kfree_action_wrapper, data) != 0) 906 return NULL; 907 908 return data; 909 } 910 EXPORT_SYMBOL_GPL(kunit_kmalloc_array); 911 912 void kunit_kfree(struct kunit *test, const void *ptr) 913 { 914 if (!ptr) 915 return; 916 917 kunit_release_action(test, kfree_action_wrapper, (void *)ptr); 918 } 919 EXPORT_SYMBOL_GPL(kunit_kfree); 920 921 void kunit_kfree_const(struct kunit *test, const void *x) 922 { 923 #if !IS_MODULE(CONFIG_KUNIT) 924 if (!is_kernel_rodata((unsigned long)x)) 925 #endif 926 kunit_kfree(test, x); 927 } 928 EXPORT_SYMBOL_GPL(kunit_kfree_const); 929 930 const char *kunit_kstrdup_const(struct kunit *test, const char *str, gfp_t gfp) 931 { 932 #if !IS_MODULE(CONFIG_KUNIT) 933 if (is_kernel_rodata((unsigned long)str)) 934 return str; 935 #endif 936 return kunit_kstrdup(test, str, gfp); 937 } 938 EXPORT_SYMBOL_GPL(kunit_kstrdup_const); 939 940 void kunit_cleanup(struct kunit *test) 941 { 942 struct kunit_resource *res; 943 unsigned long flags; 944 945 /* 946 * test->resources is a stack - each allocation must be freed in the 947 * reverse order from which it was added since one resource may depend 948 * on another for its entire lifetime. 949 * Also, we cannot use the normal list_for_each constructs, even the 950 * safe ones because *arbitrary* nodes may be deleted when 951 * kunit_resource_free is called; the list_for_each_safe variants only 952 * protect against the current node being deleted, not the next. 953 */ 954 while (true) { 955 spin_lock_irqsave(&test->lock, flags); 956 if (list_empty(&test->resources)) { 957 spin_unlock_irqrestore(&test->lock, flags); 958 break; 959 } 960 res = list_last_entry(&test->resources, 961 struct kunit_resource, 962 node); 963 /* 964 * Need to unlock here as a resource may remove another 965 * resource, and this can't happen if the test->lock 966 * is held. 967 */ 968 spin_unlock_irqrestore(&test->lock, flags); 969 kunit_remove_resource(test, res); 970 } 971 current->kunit_test = NULL; 972 } 973 EXPORT_SYMBOL_GPL(kunit_cleanup); 974 975 static int __init kunit_init(void) 976 { 977 /* Install the KUnit hook functions. */ 978 kunit_install_hooks(); 979 980 kunit_debugfs_init(); 981 982 kunit_bus_init(); 983 #ifdef CONFIG_MODULES 984 return register_module_notifier(&kunit_mod_nb); 985 #else 986 return 0; 987 #endif 988 } 989 late_initcall(kunit_init); 990 991 static void __exit kunit_exit(void) 992 { 993 memset(&kunit_hooks, 0, sizeof(kunit_hooks)); 994 #ifdef CONFIG_MODULES 995 unregister_module_notifier(&kunit_mod_nb); 996 #endif 997 998 kunit_bus_shutdown(); 999 1000 kunit_debugfs_cleanup(); 1001 } 1002 module_exit(kunit_exit); 1003 1004 MODULE_DESCRIPTION("Base unit test (KUnit) API"); 1005 MODULE_LICENSE("GPL v2"); 1006