Merge tag 'core-rcu-2020-10-12' of git://git.kernel.org/pub/scm/linux/kernel/git...
[sfrench/cifs-2.6.git] / lib / kunit / test.c
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 <linux/kernel.h>
11 #include <linux/kref.h>
12 #include <linux/sched/debug.h>
13 #include <linux/sched.h>
14
15 #include "debugfs.h"
16 #include "string-stream.h"
17 #include "try-catch-impl.h"
18
19 static void kunit_print_tap_version(void)
20 {
21         static bool kunit_has_printed_tap_version;
22
23         if (!kunit_has_printed_tap_version) {
24                 pr_info("TAP version 14\n");
25                 kunit_has_printed_tap_version = true;
26         }
27 }
28
29 /*
30  * Append formatted message to log, size of which is limited to
31  * KUNIT_LOG_SIZE bytes (including null terminating byte).
32  */
33 void kunit_log_append(char *log, const char *fmt, ...)
34 {
35         char line[KUNIT_LOG_SIZE];
36         va_list args;
37         int len_left;
38
39         if (!log)
40                 return;
41
42         len_left = KUNIT_LOG_SIZE - strlen(log) - 1;
43         if (len_left <= 0)
44                 return;
45
46         va_start(args, fmt);
47         vsnprintf(line, sizeof(line), fmt, args);
48         va_end(args);
49
50         strncat(log, line, len_left);
51 }
52 EXPORT_SYMBOL_GPL(kunit_log_append);
53
54 size_t kunit_suite_num_test_cases(struct kunit_suite *suite)
55 {
56         struct kunit_case *test_case;
57         size_t len = 0;
58
59         kunit_suite_for_each_test_case(suite, test_case)
60                 len++;
61
62         return len;
63 }
64 EXPORT_SYMBOL_GPL(kunit_suite_num_test_cases);
65
66 static void kunit_print_subtest_start(struct kunit_suite *suite)
67 {
68         kunit_print_tap_version();
69         kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "# Subtest: %s",
70                   suite->name);
71         kunit_log(KERN_INFO, suite, KUNIT_SUBTEST_INDENT "1..%zd",
72                   kunit_suite_num_test_cases(suite));
73 }
74
75 static void kunit_print_ok_not_ok(void *test_or_suite,
76                                   bool is_test,
77                                   bool is_ok,
78                                   size_t test_number,
79                                   const char *description)
80 {
81         struct kunit_suite *suite = is_test ? NULL : test_or_suite;
82         struct kunit *test = is_test ? test_or_suite : NULL;
83
84         /*
85          * We do not log the test suite results as doing so would
86          * mean debugfs display would consist of the test suite
87          * description and status prior to individual test results.
88          * Hence directly printk the suite status, and we will
89          * separately seq_printf() the suite status for the debugfs
90          * representation.
91          */
92         if (suite)
93                 pr_info("%s %zd - %s\n",
94                         kunit_status_to_string(is_ok),
95                         test_number, description);
96         else
97                 kunit_log(KERN_INFO, test, KUNIT_SUBTEST_INDENT "%s %zd - %s",
98                           kunit_status_to_string(is_ok),
99                           test_number, description);
100 }
101
102 bool kunit_suite_has_succeeded(struct kunit_suite *suite)
103 {
104         const struct kunit_case *test_case;
105
106         kunit_suite_for_each_test_case(suite, test_case) {
107                 if (!test_case->success)
108                         return false;
109         }
110
111         return true;
112 }
113 EXPORT_SYMBOL_GPL(kunit_suite_has_succeeded);
114
115 static void kunit_print_subtest_end(struct kunit_suite *suite)
116 {
117         static size_t kunit_suite_counter = 1;
118
119         kunit_print_ok_not_ok((void *)suite, false,
120                               kunit_suite_has_succeeded(suite),
121                               kunit_suite_counter++,
122                               suite->name);
123 }
124
125 unsigned int kunit_test_case_num(struct kunit_suite *suite,
126                                  struct kunit_case *test_case)
127 {
128         struct kunit_case *tc;
129         unsigned int i = 1;
130
131         kunit_suite_for_each_test_case(suite, tc) {
132                 if (tc == test_case)
133                         return i;
134                 i++;
135         }
136
137         return 0;
138 }
139 EXPORT_SYMBOL_GPL(kunit_test_case_num);
140
141 static void kunit_print_string_stream(struct kunit *test,
142                                       struct string_stream *stream)
143 {
144         struct string_stream_fragment *fragment;
145         char *buf;
146
147         if (string_stream_is_empty(stream))
148                 return;
149
150         buf = string_stream_get_string(stream);
151         if (!buf) {
152                 kunit_err(test,
153                           "Could not allocate buffer, dumping stream:\n");
154                 list_for_each_entry(fragment, &stream->fragments, node) {
155                         kunit_err(test, "%s", fragment->fragment);
156                 }
157                 kunit_err(test, "\n");
158         } else {
159                 kunit_err(test, "%s", buf);
160                 kunit_kfree(test, buf);
161         }
162 }
163
164 static void kunit_fail(struct kunit *test, struct kunit_assert *assert)
165 {
166         struct string_stream *stream;
167
168         kunit_set_failure(test);
169
170         stream = alloc_string_stream(test, GFP_KERNEL);
171         if (!stream) {
172                 WARN(true,
173                      "Could not allocate stream to print failed assertion in %s:%d\n",
174                      assert->file,
175                      assert->line);
176                 return;
177         }
178
179         assert->format(assert, stream);
180
181         kunit_print_string_stream(test, stream);
182
183         WARN_ON(string_stream_destroy(stream));
184 }
185
186 static void __noreturn kunit_abort(struct kunit *test)
187 {
188         kunit_try_catch_throw(&test->try_catch); /* Does not return. */
189
190         /*
191          * Throw could not abort from test.
192          *
193          * XXX: we should never reach this line! As kunit_try_catch_throw is
194          * marked __noreturn.
195          */
196         WARN_ONCE(true, "Throw could not abort from test!\n");
197 }
198
199 void kunit_do_assertion(struct kunit *test,
200                         struct kunit_assert *assert,
201                         bool pass,
202                         const char *fmt, ...)
203 {
204         va_list args;
205
206         if (pass)
207                 return;
208
209         va_start(args, fmt);
210
211         assert->message.fmt = fmt;
212         assert->message.va = &args;
213
214         kunit_fail(test, assert);
215
216         va_end(args);
217
218         if (assert->type == KUNIT_ASSERTION)
219                 kunit_abort(test);
220 }
221 EXPORT_SYMBOL_GPL(kunit_do_assertion);
222
223 void kunit_init_test(struct kunit *test, const char *name, char *log)
224 {
225         spin_lock_init(&test->lock);
226         INIT_LIST_HEAD(&test->resources);
227         test->name = name;
228         test->log = log;
229         if (test->log)
230                 test->log[0] = '\0';
231         test->success = true;
232 }
233 EXPORT_SYMBOL_GPL(kunit_init_test);
234
235 /*
236  * Initializes and runs test case. Does not clean up or do post validations.
237  */
238 static void kunit_run_case_internal(struct kunit *test,
239                                     struct kunit_suite *suite,
240                                     struct kunit_case *test_case)
241 {
242         if (suite->init) {
243                 int ret;
244
245                 ret = suite->init(test);
246                 if (ret) {
247                         kunit_err(test, "failed to initialize: %d\n", ret);
248                         kunit_set_failure(test);
249                         return;
250                 }
251         }
252
253         test_case->run_case(test);
254 }
255
256 static void kunit_case_internal_cleanup(struct kunit *test)
257 {
258         kunit_cleanup(test);
259 }
260
261 /*
262  * Performs post validations and cleanup after a test case was run.
263  * XXX: Should ONLY BE CALLED AFTER kunit_run_case_internal!
264  */
265 static void kunit_run_case_cleanup(struct kunit *test,
266                                    struct kunit_suite *suite)
267 {
268         if (suite->exit)
269                 suite->exit(test);
270
271         kunit_case_internal_cleanup(test);
272 }
273
274 struct kunit_try_catch_context {
275         struct kunit *test;
276         struct kunit_suite *suite;
277         struct kunit_case *test_case;
278 };
279
280 static void kunit_try_run_case(void *data)
281 {
282         struct kunit_try_catch_context *ctx = data;
283         struct kunit *test = ctx->test;
284         struct kunit_suite *suite = ctx->suite;
285         struct kunit_case *test_case = ctx->test_case;
286
287 #if (IS_ENABLED(CONFIG_KASAN) && IS_ENABLED(CONFIG_KUNIT))
288         current->kunit_test = test;
289 #endif /* IS_ENABLED(CONFIG_KASAN) && IS_ENABLED(CONFIG_KUNIT) */
290
291         /*
292          * kunit_run_case_internal may encounter a fatal error; if it does,
293          * abort will be called, this thread will exit, and finally the parent
294          * thread will resume control and handle any necessary clean up.
295          */
296         kunit_run_case_internal(test, suite, test_case);
297         /* This line may never be reached. */
298         kunit_run_case_cleanup(test, suite);
299 }
300
301 static void kunit_catch_run_case(void *data)
302 {
303         struct kunit_try_catch_context *ctx = data;
304         struct kunit *test = ctx->test;
305         struct kunit_suite *suite = ctx->suite;
306         int try_exit_code = kunit_try_catch_get_result(&test->try_catch);
307
308         if (try_exit_code) {
309                 kunit_set_failure(test);
310                 /*
311                  * Test case could not finish, we have no idea what state it is
312                  * in, so don't do clean up.
313                  */
314                 if (try_exit_code == -ETIMEDOUT) {
315                         kunit_err(test, "test case timed out\n");
316                 /*
317                  * Unknown internal error occurred preventing test case from
318                  * running, so there is nothing to clean up.
319                  */
320                 } else {
321                         kunit_err(test, "internal error occurred preventing test case from running: %d\n",
322                                   try_exit_code);
323                 }
324                 return;
325         }
326
327         /*
328          * Test case was run, but aborted. It is the test case's business as to
329          * whether it failed or not, we just need to clean up.
330          */
331         kunit_run_case_cleanup(test, suite);
332 }
333
334 /*
335  * Performs all logic to run a test case. It also catches most errors that
336  * occur in a test case and reports them as failures.
337  */
338 static void kunit_run_case_catch_errors(struct kunit_suite *suite,
339                                         struct kunit_case *test_case)
340 {
341         struct kunit_try_catch_context context;
342         struct kunit_try_catch *try_catch;
343         struct kunit test;
344
345         kunit_init_test(&test, test_case->name, test_case->log);
346         try_catch = &test.try_catch;
347
348         kunit_try_catch_init(try_catch,
349                              &test,
350                              kunit_try_run_case,
351                              kunit_catch_run_case);
352         context.test = &test;
353         context.suite = suite;
354         context.test_case = test_case;
355         kunit_try_catch_run(try_catch, &context);
356
357         test_case->success = test.success;
358
359         kunit_print_ok_not_ok(&test, true, test_case->success,
360                               kunit_test_case_num(suite, test_case),
361                               test_case->name);
362 }
363
364 int kunit_run_tests(struct kunit_suite *suite)
365 {
366         struct kunit_case *test_case;
367
368         kunit_print_subtest_start(suite);
369
370         kunit_suite_for_each_test_case(suite, test_case)
371                 kunit_run_case_catch_errors(suite, test_case);
372
373         kunit_print_subtest_end(suite);
374
375         return 0;
376 }
377 EXPORT_SYMBOL_GPL(kunit_run_tests);
378
379 static void kunit_init_suite(struct kunit_suite *suite)
380 {
381         kunit_debugfs_create_suite(suite);
382 }
383
384 int __kunit_test_suites_init(struct kunit_suite **suites)
385 {
386         unsigned int i;
387
388         for (i = 0; suites[i] != NULL; i++) {
389                 kunit_init_suite(suites[i]);
390                 kunit_run_tests(suites[i]);
391         }
392         return 0;
393 }
394 EXPORT_SYMBOL_GPL(__kunit_test_suites_init);
395
396 static void kunit_exit_suite(struct kunit_suite *suite)
397 {
398         kunit_debugfs_destroy_suite(suite);
399 }
400
401 void __kunit_test_suites_exit(struct kunit_suite **suites)
402 {
403         unsigned int i;
404
405         for (i = 0; suites[i] != NULL; i++)
406                 kunit_exit_suite(suites[i]);
407 }
408 EXPORT_SYMBOL_GPL(__kunit_test_suites_exit);
409
410 /*
411  * Used for static resources and when a kunit_resource * has been created by
412  * kunit_alloc_resource().  When an init function is supplied, @data is passed
413  * into the init function; otherwise, we simply set the resource data field to
414  * the data value passed in.
415  */
416 int kunit_add_resource(struct kunit *test,
417                        kunit_resource_init_t init,
418                        kunit_resource_free_t free,
419                        struct kunit_resource *res,
420                        void *data)
421 {
422         int ret = 0;
423
424         res->free = free;
425         kref_init(&res->refcount);
426
427         if (init) {
428                 ret = init(res, data);
429                 if (ret)
430                         return ret;
431         } else {
432                 res->data = data;
433         }
434
435         spin_lock(&test->lock);
436         list_add_tail(&res->node, &test->resources);
437         /* refcount for list is established by kref_init() */
438         spin_unlock(&test->lock);
439
440         return ret;
441 }
442 EXPORT_SYMBOL_GPL(kunit_add_resource);
443
444 int kunit_add_named_resource(struct kunit *test,
445                              kunit_resource_init_t init,
446                              kunit_resource_free_t free,
447                              struct kunit_resource *res,
448                              const char *name,
449                              void *data)
450 {
451         struct kunit_resource *existing;
452
453         if (!name)
454                 return -EINVAL;
455
456         existing = kunit_find_named_resource(test, name);
457         if (existing) {
458                 kunit_put_resource(existing);
459                 return -EEXIST;
460         }
461
462         res->name = name;
463
464         return kunit_add_resource(test, init, free, res, data);
465 }
466 EXPORT_SYMBOL_GPL(kunit_add_named_resource);
467
468 struct kunit_resource *kunit_alloc_and_get_resource(struct kunit *test,
469                                                     kunit_resource_init_t init,
470                                                     kunit_resource_free_t free,
471                                                     gfp_t internal_gfp,
472                                                     void *data)
473 {
474         struct kunit_resource *res;
475         int ret;
476
477         res = kzalloc(sizeof(*res), internal_gfp);
478         if (!res)
479                 return NULL;
480
481         ret = kunit_add_resource(test, init, free, res, data);
482         if (!ret) {
483                 /*
484                  * bump refcount for get; kunit_resource_put() should be called
485                  * when done.
486                  */
487                 kunit_get_resource(res);
488                 return res;
489         }
490         return NULL;
491 }
492 EXPORT_SYMBOL_GPL(kunit_alloc_and_get_resource);
493
494 void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
495 {
496         spin_lock(&test->lock);
497         list_del(&res->node);
498         spin_unlock(&test->lock);
499         kunit_put_resource(res);
500 }
501 EXPORT_SYMBOL_GPL(kunit_remove_resource);
502
503 int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
504                            void *match_data)
505 {
506         struct kunit_resource *res = kunit_find_resource(test, match,
507                                                          match_data);
508
509         if (!res)
510                 return -ENOENT;
511
512         kunit_remove_resource(test, res);
513
514         /* We have a reference also via _find(); drop it. */
515         kunit_put_resource(res);
516
517         return 0;
518 }
519 EXPORT_SYMBOL_GPL(kunit_destroy_resource);
520
521 struct kunit_kmalloc_params {
522         size_t size;
523         gfp_t gfp;
524 };
525
526 static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
527 {
528         struct kunit_kmalloc_params *params = context;
529
530         res->data = kmalloc(params->size, params->gfp);
531         if (!res->data)
532                 return -ENOMEM;
533
534         return 0;
535 }
536
537 static void kunit_kmalloc_free(struct kunit_resource *res)
538 {
539         kfree(res->data);
540 }
541
542 void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
543 {
544         struct kunit_kmalloc_params params = {
545                 .size = size,
546                 .gfp = gfp
547         };
548
549         return kunit_alloc_resource(test,
550                                     kunit_kmalloc_init,
551                                     kunit_kmalloc_free,
552                                     gfp,
553                                     &params);
554 }
555 EXPORT_SYMBOL_GPL(kunit_kmalloc);
556
557 void kunit_kfree(struct kunit *test, const void *ptr)
558 {
559         struct kunit_resource *res;
560
561         res = kunit_find_resource(test, kunit_resource_instance_match,
562                                   (void *)ptr);
563
564         /*
565          * Removing the resource from the list of resources drops the
566          * reference count to 1; the final put will trigger the free.
567          */
568         kunit_remove_resource(test, res);
569
570         kunit_put_resource(res);
571
572 }
573 EXPORT_SYMBOL_GPL(kunit_kfree);
574
575 void kunit_cleanup(struct kunit *test)
576 {
577         struct kunit_resource *res;
578
579         /*
580          * test->resources is a stack - each allocation must be freed in the
581          * reverse order from which it was added since one resource may depend
582          * on another for its entire lifetime.
583          * Also, we cannot use the normal list_for_each constructs, even the
584          * safe ones because *arbitrary* nodes may be deleted when
585          * kunit_resource_free is called; the list_for_each_safe variants only
586          * protect against the current node being deleted, not the next.
587          */
588         while (true) {
589                 spin_lock(&test->lock);
590                 if (list_empty(&test->resources)) {
591                         spin_unlock(&test->lock);
592                         break;
593                 }
594                 res = list_last_entry(&test->resources,
595                                       struct kunit_resource,
596                                       node);
597                 /*
598                  * Need to unlock here as a resource may remove another
599                  * resource, and this can't happen if the test->lock
600                  * is held.
601                  */
602                 spin_unlock(&test->lock);
603                 kunit_remove_resource(test, res);
604         }
605 #if (IS_ENABLED(CONFIG_KASAN) && IS_ENABLED(CONFIG_KUNIT))
606         current->kunit_test = NULL;
607 #endif /* IS_ENABLED(CONFIG_KASAN) && IS_ENABLED(CONFIG_KUNIT)*/
608 }
609 EXPORT_SYMBOL_GPL(kunit_cleanup);
610
611 static int __init kunit_init(void)
612 {
613         kunit_debugfs_init();
614
615         return 0;
616 }
617 late_initcall(kunit_init);
618
619 static void __exit kunit_exit(void)
620 {
621         kunit_debugfs_cleanup();
622 }
623 module_exit(kunit_exit);
624
625 MODULE_LICENSE("GPL v2");