test.c 27 KB

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