Commit Graph

81 Commits

Author SHA1 Message Date
Nico Pache 9dd9b5b62a kunit: bail out early in __kunit_test_suites_init() if there are no suites to test
commit 5496b9b77d7420652202b73cf036e69760be5deb
Author: Scott Mayhew <smayhew@redhat.com>
Date:   Thu Mar 21 10:32:00 2024 -0400

    kunit: bail out early in __kunit_test_suites_init() if there are no suites to test

    Commit c72a870926c2 added a mutex to prevent kunit tests from running
    concurrently.  Unfortunately that mutex gets locked during module load
    regardless of whether the module actually has any kunit tests.  This
    causes a problem for kunit tests that might need to load other kernel
    modules (e.g. gss_krb5_test loading the camellia module).

    So check to see if there are actually any tests to run before locking
    the kunit_run_lock mutex.

    Fixes: c72a870926c2 ("kunit: add ability to run tests after boot using debugfs")
    Reported-by: Nico Pache <npache@redhat.com>
    Signed-off-by: Scott Mayhew <smayhew@redhat.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:30 -06:00
Nico Pache 884e06941d kunit: run test suites only after module initialization completes
commit a1af6a2bfa0cb46d70b7df5352993e750da6c79b
Author: Marco Pagani <marpagan@redhat.com>
Date:   Wed Jan 10 16:59:47 2024 +0100

    kunit: run test suites only after module initialization completes

    Commit 2810c1e99867 ("kunit: Fix wild-memory-access bug in
    kunit_free_suite_set()") fixed a wild-memory-access bug that could have
    happened during the loading phase of test suites built and executed as
    loadable modules. However, it also introduced a problematic side effect
    that causes test suites modules to crash when they attempt to register
    fake devices.

    When a module is loaded, it traverses the MODULE_STATE_UNFORMED and
    MODULE_STATE_COMING states before reaching the normal operating state
    MODULE_STATE_LIVE. Finally, when the module is removed, it moves to
    MODULE_STATE_GOING before being released. However, if the loading
    function load_module() fails between complete_formation() and
    do_init_module(), the module goes directly from MODULE_STATE_COMING to
    MODULE_STATE_GOING without passing through MODULE_STATE_LIVE.

    This behavior was causing kunit_module_exit() to be called without
    having first executed kunit_module_init(). Since kunit_module_exit() is
    responsible for freeing the memory allocated by kunit_module_init()
    through kunit_filter_suites(), this behavior was resulting in a
    wild-memory-access bug.

    Commit 2810c1e99867 ("kunit: Fix wild-memory-access bug in
    kunit_free_suite_set()") fixed this issue by running the tests when the
    module is still in MODULE_STATE_COMING. However, modules in that state
    are not fully initialized, lacking sysfs kobjects. Therefore, if a test
    module attempts to register a fake device, it will inevitably crash.

    This patch proposes a different approach to fix the original
    wild-memory-access bug while restoring the normal module execution flow
    by making kunit_module_exit() able to detect if kunit_module_init() has
    previously initialized the tests suite set. In this way, test modules
    can once again register fake devices without crashing.

    This behavior is achieved by checking whether mod->kunit_suites is a
    virtual or direct mapping address. If it is a virtual address, then
    kunit_module_init() has allocated the suite_set in kunit_filter_suites()
    using kmalloc_array(). On the contrary, if mod->kunit_suites is still
    pointing to the original address that was set when looking up the
    .kunit_test_suites section of the module, then the loading phase has
    failed and there's no memory to be freed.

    v4:
    - rebased on 6.8
    - noted that kunit_filter_suites() must return a virtual address
    v3:
    - add a comment to clarify why the start address is checked
    v2:
    - add include <linux/mm.h>

    Fixes: 2810c1e99867 ("kunit: Fix wild-memory-access bug in kunit_free_suite_set()")
    Reviewed-by: David Gow <davidgow@google.com>
    Tested-by: Rae Moar <rmoar@google.com>
    Tested-by: Richard Fitzgerald <rf@opensource.cirrus.com>
    Reviewed-by: Javier Martinez Canillas <javierm@redhat.com>
    Signed-off-by: Marco Pagani <marpagan@redhat.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:28 -06:00
Nico Pache 4b2eb23ca9 kunit: Fix NULL-dereference in kunit_init_suite() if suite->log is NULL
commit a0b84213f947176ddcd0e96e0751a109f28cde21
Author: Richard Fitzgerald <rf@opensource.cirrus.com>
Date:   Mon Dec 18 15:17:29 2023 +0000

    kunit: Fix NULL-dereference in kunit_init_suite() if suite->log is NULL

    suite->log must be checked for NULL before passing it to
    string_stream_clear(). This was done in kunit_init_test() but was missing
    from kunit_init_suite().

    Signed-off-by: Richard Fitzgerald <rf@opensource.cirrus.com>
    Fixes: 6d696c4695c5 ("kunit: add ability to run tests after boot using debugfs")
    Reviewed-by: Rae Moar <rmoar@google.com>
    Acked-by: David Gow <davidgow@google.com>
    Reviewed-by: Muhammad Usama Anjum <usama.anjum@collabora.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:28 -06:00
Nico Pache 6ca6ed4172 kunit: Reset test->priv after each param iteration
commit 342fb9789267ee3908959bfa136b82e88e2ce918
Author: Michal Wajdeczko <michal.wajdeczko@intel.com>
Date:   Fri Dec 15 16:13:27 2023 +0100

    kunit: Reset test->priv after each param iteration

    If we run parameterized test that uses test->priv to prepare some
    custom data, then value of test->priv will leak to the next param
    iteration and may be unexpected.  This could be easily seen if
    we promote example_priv_test to parameterized test as then only
    first test iteration will be successful:

    $ ./tools/testing/kunit/kunit.py run \
            --kunitconfig ./lib/kunit/.kunitconfig *.example_priv*

    [ ] Starting KUnit Kernel (1/1)...
    [ ] ============================================================
    [ ] =================== example (1 subtest) ====================
    [ ] ==================== example_priv_test  ====================
    [ ] [PASSED] example value 3
    [ ] # example_priv_test: initializing
    [ ] # example_priv_test: ASSERTION FAILED at lib/kunit/kunit-example-test.c:230
    [ ] Expected test->priv == ((void *)0), but
    [ ]     test->priv == 0000000060dfe290
    [ ]     ((void *)0) == 0000000000000000
    [ ] # example_priv_test: cleaning up
    [ ] [FAILED] example value 2
    [ ] # example_priv_test: initializing
    [ ] # example_priv_test: ASSERTION FAILED at lib/kunit/kunit-example-test.c:230
    [ ] Expected test->priv == ((void *)0), but
    [ ]     test->priv == 0000000060dfe290
    [ ]     ((void *)0) == 0000000000000000
    [ ] # example_priv_test: cleaning up
    [ ] [FAILED] example value 1
    [ ] # example_priv_test: initializing
    [ ] # example_priv_test: ASSERTION FAILED at lib/kunit/kunit-example-test.c:230
    [ ] Expected test->priv == ((void *)0), but
    [ ]     test->priv == 0000000060dfe290
    [ ]     ((void *)0) == 0000000000000000
    [ ] # example_priv_test: cleaning up
    [ ] [FAILED] example value 0
    [ ] # example_priv_test: initializing
    [ ] # example_priv_test: cleaning up
    [ ] # example_priv_test: pass:1 fail:3 skip:0 total:4
    [ ] ================ [FAILED] example_priv_test ================
    [ ]     # example: initializing suite
    [ ]     # module: kunit_example_test
    [ ]     # example: exiting suite
    [ ] # Totals: pass:1 fail:3 skip:0 total:4
    [ ] ===================== [FAILED] example =====================

    Fix that by resetting test->priv after each param iteration, in
    similar way what we did for the test->status.

    Signed-off-by: Michal Wajdeczko <michal.wajdeczko@intel.com>
    Cc: David Gow <davidgow@google.com>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:28 -06:00
Nico Pache a25c099c74 kunit: add ability to run tests after boot using debugfs
commit c72a870926c2de694942aaac2b49e59ce789bb74
Author: Rae Moar <rmoar@google.com>
Date:   Wed Dec 13 19:44:20 2023 +0000

    kunit: add ability to run tests after boot using debugfs

    Add functionality to run built-in tests after boot by writing to a
    debugfs file.

    Add a new debugfs file labeled "run" for each test suite to use for
    this purpose.

    As an example, write to the file using the following:

    echo "any string" > /sys/kernel/debugfs/kunit/<testsuite>/run

    This will trigger the test suite to run and will print results to the
    kernel log.

    To guard against running tests concurrently with this feature, add a
    mutex lock around running kunit. This supports the current practice of
    not allowing tests to be run concurrently on the same kernel.

    This new functionality could be used to design a parameter
    injection feature in the future.

    Fixed up merge conflict duing rebase to Linux 6.7-rc6
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:28 -06:00
Nico Pache d6b2c538d9 kunit: add KUNIT_INIT_TABLE to init linker section
commit d81f0d7b8b23ec79f80be602ed6129ded27862e8
Author: Rae Moar <rmoar@google.com>
Date:   Wed Dec 13 19:44:17 2023 +0000

    kunit: add KUNIT_INIT_TABLE to init linker section

    Add KUNIT_INIT_TABLE to the INIT_DATA linker section.

    Alter the KUnit macros to create init tests:
    kunit_test_init_section_suites

    Update lib/kunit/executor.c to run both the suites in KUNIT_TABLE and
    KUNIT_INIT_TABLE.

    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:32:28 -06:00
Nico Pache 894142c966 kunit: Reset suite counter right before running tests
commit 2e3c94aed51eabbe9c1c0ee515371ea5441c2fa7
Author: Michal Wajdeczko <michal.wajdeczko@intel.com>
Date:   Wed Oct 4 22:57:00 2023 +0200

    kunit: Reset suite counter right before running tests

    Today we reset the suite counter as part of the suite cleanup,
    called from the module exit callback, but it might not work that
    well as one can try to collect results without unloading a previous
    test (either unintentionally or due to dependencies).

    For easy reproduction try to load the kunit-test.ko and then
    collect and parse results from the kunit-example-test.ko load.
    Parser will complain about mismatch of expected test number:

    [ ] KTAP version 1
    [ ] 1..1
    [ ]     # example: initializing suite
    [ ]     KTAP version 1
    [ ]     # Subtest: example
    ..
    [ ] # example: pass:5 fail:0 skip:4 total:9
    [ ] # Totals: pass:6 fail:0 skip:6 total:12
    [ ] ok 7 example

    [ ] [ERROR] Test: example: Expected test number 1 but found 7
    [ ] ===================== [PASSED] example =====================
    [ ] ============================================================
    [ ] Testing complete. Ran 12 tests: passed: 6, skipped: 6, errors: 1

    Since we are now printing suite test plan on every module load,
    right before running suite tests, we should make sure that suite
    counter will also start from 1. Easiest solution seems to be move
    counter reset to the __kunit_test_suites_init() function.

    Signed-off-by: Michal Wajdeczko <michal.wajdeczko@intel.com>
    Cc: David Gow <davidgow@google.com>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache 2c032ab1ca kunit: Warn if tests are slow
commit f8f2847f739dc899d0e563eac01299dadefa64ff
Author: Maxime Ripard <mripard@kernel.org>
Date:   Thu Oct 26 10:59:31 2023 +0200

    kunit: Warn if tests are slow

    Kunit recently gained support to setup attributes, the first one being
    the speed of a given test, then allowing to filter out slow tests.

    A slow test is defined in the documentation as taking more than one
    second. There's an another speed attribute called "super slow" but whose
    definition is less clear.

    Add support to the test runner to check the test execution time, and
    report tests that should be marked as slow but aren't.

    Signed-off-by: Maxime Ripard <mripard@kernel.org>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache d8db73c041 kunit: Reset test status on each param iteration
commit ee5f8cc2770b2f0f7cfefb5bf7534e2859e39485
Author: Michal Wajdeczko <michal.wajdeczko@intel.com>
Date:   Thu Aug 31 23:48:47 2023 +0200

    kunit: Reset test status on each param iteration

    If we skip one parametrized test case then test status remains
    SKIP for all subsequent test params leading to wrong reports:

    $ ./tools/testing/kunit/kunit.py run \
            --kunitconfig ./lib/kunit/.kunitconfig *.example_params*
            --raw_output \

    [ ] Starting KUnit Kernel (1/1)...
    KTAP version 1
    1..1
        # example: initializing suite
        KTAP version 1
        # Subtest: example
        # module: kunit_example_test
        1..1
            KTAP version 1
            # Subtest: example_params_test
        # example_params_test: initializing
        # example_params_test: cleaning up
            ok 1 example value 3 # SKIP unsupported param value 3
        # example_params_test: initializing
        # example_params_test: cleaning up
            ok 2 example value 2 # SKIP unsupported param value 3
        # example_params_test: initializing
        # example_params_test: cleaning up
            ok 3 example value 1 # SKIP unsupported param value 3
        # example_params_test: initializing
        # example_params_test: cleaning up
            ok 4 example value 0 # SKIP unsupported param value 0
        # example_params_test: pass:0 fail:0 skip:4 total:4
        ok 1 example_params_test # SKIP unsupported param value 0
        # example: exiting suite
    ok 1 example # SKIP

    Reset test status and status comment after each param iteration
    to avoid using stale results.

    Signed-off-by: Michal Wajdeczko <michal.wajdeczko@intel.com>
    Cc: David Gow <davidgow@google.com>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache 5fdee44301 kunit: Use string_stream for test log
commit 05e2006ce493cb6fb5e5b4b8317f82754dfa2b1e
Author: Richard Fitzgerald <rf@opensource.cirrus.com>
Date:   Mon Aug 28 11:41:10 2023 +0100

    kunit: Use string_stream for test log

    Replace the fixed-size log buffer with a string_stream so that the
    log can grow as lines are added.

    The existing kunit log tests have been updated for using a
    string_stream as the log. No new test have been added because there
    are already tests for the underlying string_stream.

    As the log tests now depend on string_stream functions they cannot
    build when kunit-test is a module. They have been surrounded by
    a #if to replace them with skipping version when the test is
    build as a module. Though this isn't pretty, it avoids moving
    code to another file while that code is also being changed.

    Signed-off-by: Richard Fitzgerald <rf@opensource.cirrus.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache 2a517badae kunit: string-stream: Decouple string_stream from kunit
commit a3fdf784780ccb0008d630e8722d1389c49c7499
Author: Richard Fitzgerald <rf@opensource.cirrus.com>
Date:   Mon Aug 28 11:41:08 2023 +0100

    kunit: string-stream: Decouple string_stream from kunit

    Re-work string_stream so that it is not tied to a struct kunit. This is
    to allow using it for the log of struct kunit_suite.

    Instead of resource-managing individual allocations the whole string_stream
    can be resource-managed, if required.

        alloc_string_stream() now allocates a string stream that is
        not resource-managed.

        string_stream_destroy() now works on an unmanaged string_stream
        allocated by alloc_string_stream() and frees the entire
        string_stream (previously it only freed the fragments).

        string_stream_clear() has been made public for callers that
        want to free the fragments without destroying the string_stream.

    For resource-managed allocations use kunit_alloc_string_stream()
    and kunit_free_string_stream().

    In addition to this, string_stream_get_string() now returns an
    unmanaged buffer that the caller must kfree().

    Signed-off-by: Richard Fitzgerald <rf@opensource.cirrus.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache d0c53e56b4 kunit: string-stream: Add kunit_alloc_string_stream()
commit 20631e154c78f4140fffe111f5c79464fae3c38c
Author: Richard Fitzgerald <rf@opensource.cirrus.com>
Date:   Mon Aug 28 11:41:07 2023 +0100

    kunit: string-stream: Add kunit_alloc_string_stream()

    Add function kunit_alloc_string_stream() to do a resource-managed
    allocation of a string stream, and corresponding
    kunit_free_string_stream() to free the resource-managed stream.

    This is preparing for decoupling the string_stream
    implementation from struct kunit, to reduce the amount of code
    churn when that happens. Currently:
     - kunit_alloc_string_stream() only calls alloc_string_stream().
     - kunit_free_string_stream() takes a struct kunit* which
       isn't used yet.

    Callers of the old alloc_string_stream() and
    string_stream_destroy() are all requesting a managed allocation
    so have been changed to use the new functions.

    alloc_string_stream() has been temporarily made static because
    its current behavior has been replaced with
    kunit_alloc_string_stream().

    Signed-off-by: Richard Fitzgerald <rf@opensource.cirrus.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Nico Pache 6211689100 kunit: Fix wild-memory-access bug in kunit_free_suite_set()
commit 2810c1e99867a811e631dd24e63e6c1e3b78a59d
Author: Jinjie Ruan <ruanjinjie@huawei.com>
Date:   Sun Sep 3 15:10:25 2023 +0800

    kunit: Fix wild-memory-access bug in kunit_free_suite_set()

    Inject fault while probing kunit-example-test.ko, if kstrdup()
    fails in mod_sysfs_setup() in load_module(), the mod->state will
    switch from MODULE_STATE_COMING to MODULE_STATE_GOING instead of
    from MODULE_STATE_LIVE to MODULE_STATE_GOING, so only
    kunit_module_exit() will be called without kunit_module_init(), and
    the mod->kunit_suites is no set correctly and the free in
    kunit_free_suite_set() will cause below wild-memory-access bug.

    The mod->state state machine when load_module() succeeds:

    MODULE_STATE_UNFORMED ---> MODULE_STATE_COMING ---> MODULE_STATE_LIVE
             ^                                              |
             |                                              | delete_module
             +---------------- MODULE_STATE_GOING <---------+

    The mod->state state machine when load_module() fails at
    mod_sysfs_setup():

    MODULE_STATE_UNFORMED ---> MODULE_STATE_COMING ---> MODULE_STATE_GOING
            ^                                               |
            |                                               |
            +-----------------------------------------------+

    Call kunit_module_init() at MODULE_STATE_COMING state to fix the issue
    because MODULE_STATE_LIVE is transformed from it.

     Unable to handle kernel paging request at virtual address ffffff341e942a88
     KASAN: maybe wild-memory-access in range [0x0003f9a0f4a15440-0x0003f9a0f4a15447]
     Mem abort info:
       ESR = 0x0000000096000004
       EC = 0x25: DABT (current EL), IL = 32 bits
       SET = 0, FnV = 0
       EA = 0, S1PTW = 0
       FSC = 0x04: level 0 translation fault
     Data abort info:
       ISV = 0, ISS = 0x00000004, ISS2 = 0x00000000
       CM = 0, WnR = 0, TnD = 0, TagAccess = 0
       GCS = 0, Overlay = 0, DirtyBit = 0, Xs = 0
     swapper pgtable: 4k pages, 48-bit VAs, pgdp=00000000441ea000
     [ffffff341e942a88] pgd=0000000000000000, p4d=0000000000000000
     Internal error: Oops: 0000000096000004 [#1] PREEMPT SMP
     Modules linked in: kunit_example_test(-) cfg80211 rfkill 8021q garp mrp stp llc ipv6 [last unloaded: kunit_example_test]
     CPU: 3 PID: 2035 Comm: modprobe Tainted: G        W        N 6.5.0-next-20230828+ #136
     Hardware name: linux,dummy-virt (DT)
     pstate: a0000005 (NzCv daif -PAN -UAO -TCO -DIT -SSBS BTYPE=--)
     pc : kfree+0x2c/0x70
     lr : kunit_free_suite_set+0xcc/0x13c
     sp : ffff8000829b75b0
     x29: ffff8000829b75b0 x28: ffff8000829b7b90 x27: 0000000000000000
     x26: dfff800000000000 x25: ffffcd07c82a7280 x24: ffffcd07a50ab300
     x23: ffffcd07a50ab2e8 x22: 1ffff00010536ec0 x21: dfff800000000000
     x20: ffffcd07a50ab2f0 x19: ffffcd07a50ab2f0 x18: 0000000000000000
     x17: 0000000000000000 x16: 0000000000000000 x15: ffffcd07c24b6764
     x14: ffffcd07c24b63c0 x13: ffffcd07c4cebb94 x12: ffff700010536ec7
     x11: 1ffff00010536ec6 x10: ffff700010536ec6 x9 : dfff800000000000
     x8 : 00008fffefac913a x7 : 0000000041b58ab3 x6 : 0000000000000000
     x5 : 1ffff00010536ec5 x4 : ffff8000829b7628 x3 : dfff800000000000
     x2 : ffffff341e942a80 x1 : ffffcd07a50aa000 x0 : fffffc0000000000
     Call trace:
      kfree+0x2c/0x70
      kunit_free_suite_set+0xcc/0x13c
      kunit_module_notify+0xd8/0x360
      blocking_notifier_call_chain+0xc4/0x128
      load_module+0x382c/0x44a4
      init_module_from_file+0xd4/0x128
      idempotent_init_module+0x2c8/0x524
      __arm64_sys_finit_module+0xac/0x100
      invoke_syscall+0x6c/0x258
      el0_svc_common.constprop.0+0x160/0x22c
      do_el0_svc+0x44/0x5c
      el0_svc+0x38/0x78
      el0t_64_sync_handler+0x13c/0x158
      el0t_64_sync+0x190/0x194
     Code: aa0003e1 b25657e0 d34cfc42 8b021802 (f9400440)
     ---[ end trace 0000000000000000 ]---
     Kernel panic - not syncing: Oops: Fatal exception
     SMP: stopping secondary CPUs
     Kernel Offset: 0x4d0742200000 from 0xffff800080000000
     PHYS_OFFSET: 0xffffee43c0000000
     CPU features: 0x88000203,3c020000,1000421b
     Memory Limit: none
     Rebooting in 1 seconds..

    Fixes: 3d6e44623841 ("kunit: unify module and builtin suite definitions")
    Signed-off-by: Jinjie Ruan <ruanjinjie@huawei.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-39303
Signed-off-by: Nico Pache <npache@redhat.com>
2024-07-31 20:27:47 -06:00
Dave Airlie 5485de0156 kunit: Add a macro to wrap a deferred action function
JIRA: https://issues.redhat.com/browse/RHEL-24101
Upstream Status: v6.8-rc1

The conflict is due to missing string stream logging support, which seems
like a more intricate backport than I'm up for.

Conflicts:
        lib/kunit/kunit-test.c

commit 56778b49c9a2cbc32c6b0fbd3ba1a9d64192d3af
Author:     David Gow <davidgow@google.com>
AuthorDate: Tue Nov 28 15:24:05 2023 +0800
Commit:     Shuah Khan <skhan@linuxfoundation.org>
CommitDate: Mon Dec 18 13:21:14 2023 -0700

    KUnit's deferred action API accepts a void(*)(void *) function pointer
    which is called when the test is exited. However, we very frequently
    want to use existing functions which accept a single pointer, but which
    may not be of type void*. While this is probably dodgy enough to be on
    the wrong side of the C standard, it's been often used for similar
    callbacks, and gcc's -Wcast-function-type seems to ignore cases where
    the only difference is the type of the argument, assuming it's
    compatible (i.e., they're both pointers to data).

    However, clang 16 has introduced -Wcast-function-type-strict, which no
    longer permits any deviation in function pointer type. This seems to be
    because it'd break CFI, which validates the type of function calls.

    This rather ruins our attempts to cast functions to defer them, and
    leaves us with a few options. The one we've chosen is to implement a
    macro which will generate a wrapper function which accepts a void*, and
    casts the argument to the appropriate type.

    For example, if you were trying to wrap:
    void foo_close(struct foo *handle);
    you could use:
    KUNIT_DEFINE_ACTION_WRAPPER(kunit_action_foo_close,
    			    foo_close,
    			    struct foo *);

    This would create a new kunit_action_foo_close() function, of type
    kunit_action_t, which could be passed into kunit_add_action() and
    similar functions.

    In addition to defining this macro, update KUnit and its tests to use
    it.

    Link: https://github.com/ClangBuiltLinux/linux/issues/1750
    Reviewed-by: Nathan Chancellor <nathan@kernel.org>
    Tested-by: Nathan Chancellor <nathan@kernel.org>
    Acked-by: Daniel Vetter <daniel@ffwll.ch>
    Reviewed-by: Maxime Ripard <mripard@kernel.org>
    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Signed-off-by: Dave Airlie <airlied@redhat.com>
2024-04-17 10:46:57 +10:00
Dave Airlie 565a6c89f5 kunit: device: Unregister the kunit_bus on shutdown
JIRA: https://issues.redhat.com/browse/RHEL-24101
Upstream Status: v6.8-rc5

commit 829388b725f8d266ccec32a2f446717d8693eaba
Author:     David Gow <davidgow@google.com>
AuthorDate: Thu Feb  1 14:04:36 2024 +0800
Commit:     Shuah Khan <skhan@linuxfoundation.org>
CommitDate: Tue Feb  6 17:07:37 2024 -0700

    If KUnit is built as a module, and it's unloaded, the kunit_bus is not
    unregistered. This causes an error if it's then re-loaded later, as we
    try to re-register the bus.

    Unregister the bus and root_device on shutdown, if it looks valid.

    In addition, be more specific about the value of kunit_bus_device. It
    is:
    - a valid struct device* if the kunit_bus initialised correctly.
    - an ERR_PTR if it failed to initialise.
    - NULL before initialisation and after shutdown.

    Fixes: d03c720e03bd ("kunit: Add APIs for managing devices")
    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Signed-off-by: Dave Airlie <airlied@redhat.com>
2024-04-17 10:46:57 +10:00
Dave Airlie 81864ed352 kunit: Add APIs for managing devices
JIRA: https://issues.redhat.com/browse/RHEL-24101
Upstream Status: v6.8-rc1

Conflicts:
        lib/kunit/kunit-test.c

commit d03c720e03bd9bf0b784d80b5d3ede7e2daf3b6e
Author:     davidgow@google.com <davidgow@google.com>
AuthorDate: Fri Dec 15 15:39:08 2023 +0800
Commit:     Shuah Khan <skhan@linuxfoundation.org>
CommitDate: Mon Dec 18 13:28:08 2023 -0700

    Tests for drivers often require a struct device to pass to other
    functions. While it's possible to create these with
    root_device_register(), or to use something like a platform device, this
    is both a misuse of those APIs, and can be difficult to clean up after,
    for example, a failed assertion.

    Add some KUnit-specific functions for registering and unregistering a
    struct device:
    - kunit_device_register()
    - kunit_device_register_with_driver()
    - kunit_device_unregister()

    These helpers allocate a on a 'kunit' bus which will either probe the
    driver passed in (kunit_device_register_with_driver), or will create a
    stub driver (kunit_device_register) which is cleaned up on test shutdown.

    Devices are automatically unregistered on test shutdown, but can be
    manually unregistered earlier with kunit_device_unregister() in order
    to, for example, test device release code.

    Reviewed-by: Matti Vaittinen <mazziesaccount@gmail.com>
    Reviewed-by: Maxime Ripard <mripard@kernel.org>
    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Signed-off-by: Dave Airlie <airlied@redhat.com>
2024-04-17 10:46:57 +10:00
Nico Pache ecc7667d28 kunit: Allow kunit test modules to use test filtering
commit b67abaad4d25b5d9364a1d4f6bc18286ebaaa013
Author: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
Date:   Mon Aug 7 12:23:56 2023 +0200

    kunit: Allow kunit test modules to use test filtering

    External tools, e.g., Intel GPU tools (IGT), support execution of
    individual selftests provided by kernel modules.  That could be also
    applicable to kunit test modules if they provided test filtering.  But
    test filtering is now possible only when kunit code is built into the
    kernel.  Moreover, a filter can be specified only at boot time, then
    reboot is required each time a different filter is needed.

    Build the test filtering code also when kunit is configured as a module,
    expose test filtering functions to other kunit source files, and use them
    in kunit module notifier callback functions.  Userspace can then reload
    the kunit module with a value of the filter_glob parameter tuned to a
    specific kunit test module every time it wants to limit the scope of tests
    executed on that module load.  Make the kunit.filter* parameters visible
    in sysfs for user convenience.

    v5: Refresh on tpp of attributes filtering fix
    v4: Refresh on top of newly applied attributes patches and changes
        introdced by new versions of other patches submitted in series with
        this one.
    v3: Fix CONFIG_GLOB, required by filtering functions, not selected when
        building as a module (lkp@intel.com).
    v2: Fix new name of a structure moved to kunit namespace not updated
        across all uses (lkp@intel.com).

    Signed-off-by: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:59 -06:00
Nico Pache 87def7e75f kunit: Make 'list' action available to kunit test modules
commit 18258c60f8a74b9c39b593d118f13f3265d44cd6
Author: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
Date:   Mon Aug 7 12:23:55 2023 +0200

    kunit: Make 'list' action available to kunit test modules

    Results from kunit tests reported via dmesg may be interleaved with other
    kernel messages.  When parsing dmesg for modular kunit results in real
    time, external tools, e.g., Intel GPU tools (IGT), may want to insert
    their own test name markers into dmesg at the start of each test, before
    any kernel message related to that test appears there, so existing upper
    level test result parsers have no doubt which test to blame for a specific
    kernel message.  Unfortunately, kunit reports names of tests only at their
    completion (with the exeption of a not standarized "# Subtest: <name>"
    header above a test plan of each test suite or parametrized test).

    External tools could be able to insert their own "start of the test"
    markers with test names included if they new those names in advance.
    Test names could be learned from a list if provided by a kunit test
    module.

    There exists a feature of listing kunit tests without actually executing
    them, but it is now limited to configurations with the kunit module built
    in and covers only built-in tests, already available at boot time.
    Moreover, switching from list to normal mode requires reboot.  If that
    feature was also available when kunit is built as a module, userspace
    could load the module with action=list parameter, load some kunit test
    modules they are interested in and learn about the list of tests provided
    by those modules, then unload them, reload the kunit module in normal mode
    and execute the tests with their lists already known.

    Extend kunit module notifier initialization callback with a processing
    path for only listing the tests provided by a module if the kunit action
    parameter is set to "list" or "list_attr".  For user convenience, make the
    kunit.action parameter visible in sysfs.

    v2: Don't use a different format, use kunit_exec_list_tests() (Rae),
      - refresh on top of new attributes patches, handle newly introduced
        kunit.action=list_attr case (Rae).

    Signed-off-by: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:59 -06:00
Nico Pache 36120d6d31 kunit: Report the count of test suites in a module
commit c95e7c05c139b1a8a51d368bde57cf20ce931a98
Author: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
Date:   Mon Aug 7 12:23:54 2023 +0200

    kunit: Report the count of test suites in a module

    According to KTAP specification[1], results should always start from a
    header that provides a TAP protocol version, followed by a test plan with
    a count of items to be executed.  That pattern should be followed at each
    nesting level.  In the current implementation of the top-most, i.e., test
    suite level, those rules apply only for test suites built into the kernel,
    executed and reported on boot.  Results submitted to dmesg from kunit test
    modules loaded later are missing those top-level headers.

    As a consequence, if a kunit test module provides more than one test suite
    then, without the top level test plan, external tools that are parsing
    dmesg for kunit test output are not able to tell how many test suites
    should be expected and whether to continue parsing after complete output
    from the first test suite is collected.

    Submit the top-level headers also from the kunit test module notifier
    initialization callback.

    v3: Fix new name of a structure moved to kunit namespace not updated in
        executor_test functions (lkp@intel.com).
    v2: Use kunit_exec_run_tests() (Mauro, Rae), but prevent it from
        emitting the headers when called on load of non-test modules.

    [1] https://docs.kernel.org/dev-tools/ktap.html#

    Signed-off-by: Janusz Krzysztofik <janusz.krzysztofik@linux.intel.com>
    Cc: Mauro Carvalho Chehab <mchehab@kernel.org>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:59 -06:00
Nico Pache f03a70f3c7 kunit: Add ability to filter attributes
commit 529534e8cba3e60f843a682e2a3149612b30d608
Author: Rae Moar <rmoar@google.com>
Date:   Tue Jul 25 21:25:15 2023 +0000

    kunit: Add ability to filter attributes

    Add filtering of test attributes. Users can filter tests using the
    module_param called "filter".

    Filters are imputed in the format: <attribute_name><operation><value>

    Example: kunit.filter="speed>slow"

    Operations include: >, <, >=, <=, !=, and =. These operations will act the
    same for attributes of the same type but may not between types.

    Note multiple filters can be inputted by separating them with a comma.
    Example: kunit.filter="speed=slow, module!=example"

    Since both suites and test cases can have attributes, there may be
    conflicts. The process of filtering follows these rules:
    - Filtering always operates at a per-test level.
    - If a test has an attribute set, then the test's value is filtered on.
    - Otherwise, the value falls back to the suite's value.
    - If neither are set, the attribute has a global "default" value, which
      is used.

    Filtered tests will not be run or show in output. The tests can instead be
    skipped using the configurable option "kunit.filter_action=skip".

    Note the default settings for running tests remains unfiltered.

    Finally, add "filter" methods for the speed and module attributes to parse
    and compare attribute values.

    Note this filtering functionality will be added to kunit.py in the next
    patch.

    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:58 -06:00
Nico Pache 7e697ce65b kunit: Add test attributes API structure
commit 39e92cb1e4a1f6a12097ea2aa9e9ca6f2d2f8a83
Author: Rae Moar <rmoar@google.com>
Date:   Tue Jul 25 21:25:12 2023 +0000

    kunit: Add test attributes API structure

    Add the basic structure of the test attribute API to KUnit, which can be
    used to save and access test associated data.

    Add attributes.c and attributes.h to hold associated structs and functions
    for the API.

    Create a struct that holds a variety of associated helper functions for
    each test attribute. These helper functions will be used to get the
    attribute value, convert the value to a string, and filter based on the
    value. This struct is flexible by design to allow for attributes of
    numerous types and contexts.

    Add a method to print test attributes in the format of "# [<test_name if
    not suite>.]<attribute_name>: <attribute_value>".

    Example for a suite: "# speed: slow"

    Example for a test case: "# test_case.speed: very_slow"

    Use this method to report attributes in the KTAP output (KTAP spec:
    https://docs.kernel.org/dev-tools/ktap.html) and _list_tests output when
    kernel's new kunit.action=list_attr option is used. Note this is derivative
    of the kunit.action=list option.

    In test.h, add fields and associated helper functions to test cases and
    suites to hold user-inputted test attributes.

    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache 1069355e3b kunit: Move kunit_abort() call out of kunit_do_failed_assertion()
commit 260755184cbdb267a046e7ffd397c1d2ba09bb5e
Author: David Gow <davidgow@google.com>
Date:   Wed May 31 13:21:57 2023 +0800

    kunit: Move kunit_abort() call out of kunit_do_failed_assertion()

    KUnit aborts the current thread when an assertion fails. Currently, this
    is done conditionally as part of the kunit_do_failed_assertion()
    function, but this hides the kunit_abort() call from the compiler
    (particularly if it's in another module). This, in turn, can lead to
    both suboptimal code generation (the compiler can't know if
    kunit_do_failed_assertion() will return), and to static analysis tools
    like smatch giving false positives.

    Moving the kunit_abort() call into the macro should give the compiler
    and tools a better chance at understanding what's going on. Doing so
    requires exporting kunit_abort(), though it's recommended to continue to
    use assertions in lieu of aborting directly.

    In addition, kunit_abort() and kunit_do_failed_assertion() are renamed
    to make it clear they they're intended for internal KUnit use, to:
    __kunit_do_failed_assertion() and __kunit_abort()

    Suggested-by: Dan Carpenter <dan.carpenter@linaro.org>
    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Miguel Ojeda <ojeda@kernel.org>
    Reviewed-by: Daniel Latypov <dlatypov@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache 7c58eae20f kunit: Update kunit_print_ok_not_ok function
commit b1eaa8b2a55c9d5d22f5d2929f4d9973d6392241
Author: Michal Wajdeczko <michal.wajdeczko@intel.com>
Date:   Wed May 17 13:18:16 2023 +0200

    kunit: Update kunit_print_ok_not_ok function

    There is no need use opaque test_or_suite pointer and is_test flag
    as we don't use anything from the suite struct. Always expect test
    pointer and use NULL as indication that provided results are from
    the suite so we can treat them differently.

    Since results could be from nested tests, like parameterized tests,
    add explicit level parameter to properly indent output messages and
    thus allow to reuse this function from other places.

    While around, remove small code duplication near skip directive.

    Signed-off-by: Michal Wajdeczko <michal.wajdeczko@intel.com>
    Cc: David Gow <davidgow@google.com>
    Cc: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache c7818a1553 kunit: Fix reporting of the skipped parameterized tests
commit b08f75b9bb0196a626a804e76970733f0a05de94
Author: Michal Wajdeczko <michal.wajdeczko@intel.com>
Date:   Wed May 17 13:18:15 2023 +0200

    kunit: Fix reporting of the skipped parameterized tests

    Logs from the parameterized tests that were skipped don't include
    SKIP directive thus they are displayed as PASSED. Fix that.

    Signed-off-by: Michal Wajdeczko <michal.wajdeczko@intel.com>
    Cc: David Gow <davidgow@google.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache 890d0eab7f kunit: kmalloc_array: Use kunit_add_action()
commit 57e3cded99e9c840bc5310878d0a7f4e7768a296
Author: David Gow <davidgow@google.com>
Date:   Thu May 25 12:21:30 2023 +0800

    kunit: kmalloc_array: Use kunit_add_action()

    The kunit_add_action() function is much simpler and cleaner to use that
    the full KUnit resource API for simple things like the
    kunit_kmalloc_array() functionality.

    Replacing it allows us to get rid of a number of helper functions, and
    leaves us with no uses of kunit_alloc_resource(), which has some
    usability problems and is going to have its behaviour modified in an
    upcoming patch.

    Note that we need to use kunit_defer_trigger_all() to implement
    kunit_kfree().

    Reviewed-by: Benjamin Berg <benjamin.berg@intel.com>
    Reviewed-by: Maxime Ripard <maxime@cerno.tech>
    Tested-by: Maxime Ripard <maxime@cerno.tech>
    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache 0d49919c68 kunit: Always run cleanup from a test kthread
commit 55e8c1b49ac5a7f5567430cc83f2d270d8b7ce46
Author: David Gow <davidgow@google.com>
Date:   Wed May 10 13:38:29 2023 +0800

    kunit: Always run cleanup from a test kthread

    KUnit tests run in a kthread, with the current->kunit_test pointer set
    to the test's context. This allows the kunit_get_current_test() and
    kunit_fail_current_test() macros to work. Normally, this pointer is
    still valid during test shutdown (i.e., the suite->exit function, and
    any resource cleanup). However, if the test has exited early (e.g., due
    to a failed assertion), the cleanup is done in the parent KUnit thread,
    which does not have an active context.

    Instead, in the event test terminates early, run the test exit and
    cleanup from a new 'cleanup' kthread, which sets current->kunit_test,
    and better isolates the rest of KUnit from issues which arise in test
    cleanup.

    If a test cleanup function itself aborts (e.g., due to an assertion
    failing), there will be no further attempts to clean up: an error will
    be logged and the test failed. For example:
             # example_simple_test: test aborted during cleanup. continuing without cleaning up

    This should also make it easier to get access to the KUnit context,
    particularly from within resource cleanup functions, which may, for
    example, need access to data in test->priv.

    Reviewed-by: Benjamin Berg <benjamin.berg@intel.com>
    Reviewed-by: Maxime Ripard <maxime@cerno.tech>
    Tested-by: Maxime Ripard <maxime@cerno.tech>
    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:57 -06:00
Nico Pache be954e91b6 kunit: fix bug of extra newline characters in debugfs logs
commit 2c6a96dad5797e57b4cf04101d6c8d5c7a571603
Author: Rae Moar <rmoar@google.com>
Date:   Wed Mar 8 20:39:52 2023 +0000

    kunit: fix bug of extra newline characters in debugfs logs

    Fix bug of the extra newline characters in debugfs logs. When a
    line is added to debugfs with a newline character at the end,
    an extra line appears in the debugfs log.

    This is due to a discrepancy between how the lines are printed and how they
    are added to the logs. Remove this discrepancy by checking if a newline
    character is present before adding a newline character. This should closely
    match the printk behavior.

    Add kunit_log_newline_test to provide test coverage for this issue.  (Also,
    move kunit_log_test above suite definition to remove the unnecessary
    declaration prior to the suite definition)

    As an example, say we add these two lines to the log:

    kunit_log(..., "KTAP version 1\n");
    kunit_log(..., "1..1");

    The debugfs log before this fix:

     KTAP version 1

     1..1

    The debugfs log after this fix:

     KTAP version 1
     1..1

    Signed-off-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:56 -06:00
Nico Pache 669b9d92f6 kunit: fix bug in the order of lines in debugfs logs
commit f9a301c3317daa921375da0aec82462ddf019928
Author: Rae Moar <rmoar@google.com>
Date:   Wed Mar 8 20:39:51 2023 +0000

    kunit: fix bug in the order of lines in debugfs logs

    Fix bug in debugfs logs that causes an incorrect order of lines in the
    debugfs log.

    Currently, the test counts lines that show the number of tests passed,
    failed, and skipped, as well as any suite diagnostic lines,
    appear prior to the individual results, which is a bug.

    Ensure the order of printing for the debugfs log is correct. Additionally,
    add a KTAP header to so the debugfs logs can be valid KTAP.

    This is an example of a log prior to these fixes:

         KTAP version 1

         # Subtest: kunit_status
         1..2
     # kunit_status: pass:2 fail:0 skip:0 total:2
     # Totals: pass:2 fail:0 skip:0 total:2
         ok 1 kunit_status_set_failure_test
         ok 2 kunit_status_mark_skipped_test
     ok 1 kunit_status

    Note the two lines with stats are out of order. This is the same debugfs
    log after the fixes (in combination with the third patch to remove the
    extra line):

     KTAP version 1
     1..1
         KTAP version 1
         # Subtest: kunit_status
         1..2
         ok 1 kunit_status_set_failure_test
         ok 2 kunit_status_mark_skipped_test
     # kunit_status: pass:2 fail:0 skip:0 total:2
     # Totals: pass:2 fail:0 skip:0 total:2
     ok 1 kunit_status

    Signed-off-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:56 -06:00
Nico Pache b42b41d7f8 kunit: fix bug in debugfs logs of parameterized tests
commit 887d85a0736ff346cbfe5efaf51cf20c7ca195a3
Author: Rae Moar <rmoar@google.com>
Date:   Wed Mar 8 20:39:50 2023 +0000

    kunit: fix bug in debugfs logs of parameterized tests

    Fix bug in debugfs logs that causes individual parameterized results to not
    appear because the log is reinitialized (cleared) when each parameter is
    run.

    Ensure these results appear in the debugfs logs, increase log size to
    allow for the size of parameterized results. As a result, append lines to
    the log directly rather than using an intermediate variable that can cause
    stack size warnings due to the increased log size.

    Here is the debugfs log of ext4_inode_test which uses parameterized tests
    before the fix:

         KTAP version 1

         # Subtest: ext4_inode_test
         1..1
     # Totals: pass:16 fail:0 skip:0 total:16
     ok 1 ext4_inode_test

    As you can see, this log does not include any of the individual
    parametrized results.

    After (in combination with the next two fixes to remove extra empty line
    and ensure KTAP valid format):

     KTAP version 1
     1..1
         KTAP version 1
         # Subtest: ext4_inode_test
         1..1
            KTAP version 1
             # Subtest: inode_test_xtimestamp_decoding
             ok 1 1901-12-13 Lower bound of 32bit < 0 timestamp, no extra bits
             ... (the rest of the individual parameterized tests)
             ok 16 2446-05-10 Upper bound of 32bit >=0 timestamp. All extra
         # inode_test_xtimestamp_decoding: pass:16 fail:0 skip:0 total:16
         ok 1 inode_test_xtimestamp_decoding
     # Totals: pass:16 fail:0 skip:0 total:16
     ok 1 ext4_inode_test

    Signed-off-by: Rae Moar <rmoar@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:56 -06:00
Nico Pache cd47084fae kunit: Add printf attribute to fail_current_test_impl
commit 82649c7c0da431d147a75c6ae768ee42c1053f53
Author: David Gow <davidgow@google.com>
Date:   Sat Feb 4 12:04:53 2023 +0800

    kunit: Add printf attribute to fail_current_test_impl

    Add the gnu_printf (__printf()) attribute to the
    kunit_fail_current_test() implementation in
    __kunit_fail_current_test_impl(). While it's not actually useful here,
    as this function is never called directly, it nevertheless was
    triggering -Wsuggest-attribute=format warnings, so we should add it to
    reduce the noise.

    Fixes: cc3ed2fe5c93 ("kunit: Add "hooks" to call into KUnit when it's built as a module")
    Reported-by: kernel test robot <lkp@intel.com>
    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:56 -06:00
Nico Pache ca38ec1553 kunit: Add "hooks" to call into KUnit when it's built as a module
commit 7170b7ed6acbde523c5d362c8978c60df4c30f30
Author: David Gow <davidgow@google.com>
Date:   Sat Jan 28 15:10:07 2023 +0800

    kunit: Add "hooks" to call into KUnit when it's built as a module

    KUnit has several macros and functions intended for use from non-test
    code. These hooks, currently the kunit_get_current_test() and
    kunit_fail_current_test() macros, didn't work when CONFIG_KUNIT=m.

    In order to support this case, the required functions and static data
    need to be available unconditionally, even when KUnit itself is not
    built-in. The new 'hooks.c' file is therefore always included, and has
    both the static key required for kunit_get_current_test(), and a table
    of function pointers in struct kunit_hooks_table. This is filled in with
    the real implementations by kunit_install_hooks(), which is kept in
    hooks-impl.h and called when the kunit module is loaded.

    This can  be extended for future features which require similar
    "hook" behaviour, such as static stubs, by simply adding new entries to
    the struct, and the appropriate code to set them.

    Fixed white-space errors during commit:
    Shuah Khan <skhan@linuxfoundation.org>

    Resolved merge conflicts with:
    db105c37a4d6 ("kunit: Export kunit_running()")
    This patch supersedes the above.
    Shuah Khan <skhan@linuxfoundation.org>

    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Rae Moar <rmoar@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:55 -06:00
Nico Pache 51fe2aacec kunit: Export kunit_running()
commit db105c37a4d69d684c1edf2915557463d0ba172c
Author: Arnd Bergmann <arnd@arndb.de>
Date:   Tue Jan 17 17:50:26 2023 +0100

    kunit: Export kunit_running()

    Using kunit_fail_current_test() in a loadable module causes a link
    error like:

    ERROR: modpost: "kunit_running" [drivers/gpu/drm/vc4/vc4.ko] undefined!

    Export the symbol to allow using it from modules.

    Fixes: da43ff045c3f ("drm/vc4: tests: Fail the current test if we access a register")
    Signed-off-by: Arnd Bergmann <arnd@arndb.de>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:55 -06:00
Nico Pache 1902b81e9d kunit: improve KTAP compliance of KUnit test output
commit 6c738b52316c58ae8a87abf0907f87a7b5e7a109
Author: Rae Moar <rmoar@google.com>
Date:   Wed Nov 23 18:25:58 2022 +0000

    kunit: improve KTAP compliance of KUnit test output

    Change KUnit test output to better comply with KTAP v1 specifications
    found here: https://kernel.org/doc/html/latest/dev-tools/ktap.html.
    1) Use "KTAP version 1" instead of "TAP version 14" as test output header
    2) Remove '-' between test number and test name on test result lines
    2) Add KTAP version lines to each subtest header as well

    Note that the new KUnit output still includes the “# Subtest” line now
    located after the KTAP version line. This does not completely match the
    KTAP v1 spec but since it is classified as a diagnostic line, it is not
    expected to be disruptive or break any existing parsers. This
    “# Subtest” line comes from the TAP 14 spec
    (https://testanything.org/tap-version-14-specification.html) and it is
    used to define the test name before the results.

    Original output:

     TAP version 14
     1..1
       # Subtest: kunit-test-suite
       1..3
       ok 1 - kunit_test_1
       ok 2 - kunit_test_2
       ok 3 - kunit_test_3
     # kunit-test-suite: pass:3 fail:0 skip:0 total:3
     # Totals: pass:3 fail:0 skip:0 total:3
     ok 1 - kunit-test-suite

    New output:

     KTAP version 1
     1..1
       KTAP version 1
       # Subtest: kunit-test-suite
       1..3
       ok 1 kunit_test_1
       ok 2 kunit_test_2
       ok 3 kunit_test_3
     # kunit-test-suite: pass:3 fail:0 skip:0 total:3
     # Totals: pass:3 fail:0 skip:0 total:3
     ok 1 kunit-test-suite

    Signed-off-by: Rae Moar <rmoar@google.com>
    Reviewed-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Tested-by: Anders Roxell <anders.roxell@linaro.org>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:55 -06:00
Nico Pache ca727b76ac kunit: Provide a static key to check if KUnit is actively running tests
commit 908d0c177bbc7c34ab9129c6f2bcd87487115632
Author: David Gow <davidgow@google.com>
Date:   Fri Nov 25 16:43:04 2022 +0800

    kunit: Provide a static key to check if KUnit is actively running tests

    KUnit does a few expensive things when enabled. This hasn't been a
    problem because KUnit was only enabled on test kernels, but with a few
    people enabling (but not _using_) KUnit on production systems, we need a
    runtime way of handling this.

    Provide a 'kunit_running' static key (defaulting to false), which allows
    us to hide any KUnit code behind a static branch. This should reduce the
    performance impact (on other code) of having KUnit enabled to a single
    NOP when no tests are running.

    Note that, while it looks unintuitive, tests always run entirely within
    __kunit_test_suites_init(), so it's safe to decrement the static key at
    the end of this function, rather than in __kunit_test_suites_exit(),
    which is only there to clean up results in debugfs.

    Signed-off-by: David Gow <davidgow@google.com>
    Reviewed-by: Daniel Latypov <dlatypov@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:55 -06:00
Nico Pache 354e6cb46a kunit: make kunit_kfree(NULL) a no-op to match kfree()
commit 185d57797c5ea82e941befc2489dba0cf162b9c4
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Jul 22 17:15:34 2022 +0000

    kunit: make kunit_kfree(NULL) a no-op to match kfree()

    The real kfree() function will silently return when given a NULL.
    So a user might reasonably think they can write the following code:
      char *buffer = NULL;
      if (param->use_buffer) buffer = kunit_kzalloc(test, 10, GFP_KERNEL);
      ...
      kunit_kfree(test, buffer);

    As-is, kunit_kfree() will mark the test as FAILED when buffer is NULL.
    (And in earlier times, it would segfault).

    Let's match the semantics of kfree().

    Suggested-by: David Gow <davidgow@google.com>
    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:54 -06:00
Nico Pache 30a253a41e kunit: make kunit_kfree() not segfault on invalid inputs
commit e562e309d1d4ac05457c1454b6007071f13b5684
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Jul 22 17:15:33 2022 +0000

    kunit: make kunit_kfree() not segfault on invalid inputs

    kunit_kfree() can only work on data ("resources") allocated by KUnit.

    Currently for code like this,
    > void *ptr = kmalloc(4, GFP_KERNEL);
    > kunit_kfree(test, ptr);
    kunit_kfree() will segfault.

    It'll try and look up the kunit_resource associated with `ptr` and get a
    NULL back, but it won't check for this. This means we also segfault if
    you double-free.

    Change kunit_kfree() so it'll notice these invalid pointers and respond
    by failing the test.

    Implementation: kunit_destroy_resource() does what kunit_kfree() does,
    but is more generic and returns -ENOENT when it can't find the resource.
    Sadly, unlike just letting it crash, this means we don't get a stack
    trace. But kunit_kfree() is so infrequently used it shouldn't be hard to
    track down the bad callsite anyways.

    After this change, the above code gives:
    > # example_simple_test: EXPECTATION FAILED at lib/kunit/test.c:702
    > kunit_kfree: 00000000626ec200 already freed or not allocated by kunit

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:54 -06:00
Nico Pache 3ba64ece2e kunit: make kunit_kfree() only work on pointers from kunit_malloc() and friends
commit 047a8a0a2da716fecfd325d21ccf509c431992d9
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Jul 22 17:15:32 2022 +0000

    kunit: make kunit_kfree() only work on pointers from kunit_malloc() and friends

    kunit_kfree() exists to clean up allocations from kunit_kmalloc() and
    friends early instead of waiting for this to happen automatically at the
    end of the test.

    But it can be used on *anything* registered with the kunit resource API.

    E.g. the last 2 statements are equivalent:
      struct kunit_resource *res = something();
      kfree(res->data);
      kunit_put_resource(res);

    The problem is that there could be multiple resources that point to the
    same `data`.

    E.g. you can have a named resource acting as a pseudo-global variable in
    a test. If you point it to data allocated with kunit_kmalloc(), then
    calling `kunit_kfree(ptr)` has the chance to delete either the named
    resource or to kfree `ptr`.
    Which one it does depends on the order the resources are registered as
    kunit_kfree() will delete resources in LIFO order.

    So this patch restricts kunit_kfree() to only working on resources
    created by kunit_kmalloc(). Calling it is therefore guaranteed to free
    the memory, not do anything else.

    Note: kunit_resource_instance_match() wasn't used outside of KUnit, so
    it should be safe to remove from the public interface. It's also
    generally dangerous, as shown above, and shouldn't be used.

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:54 -06:00
Nico Pache 5c9ca317d9 kunit: update NULL vs IS_ERR() tests
commit 618887768bb71f0a475334fa5a4fba7dc98d7ab5
Author: Dan Carpenter <dan.carpenter@oracle.com>
Date:   Fri Oct 14 12:37:25 2022 +0300

    kunit: update NULL vs IS_ERR() tests

    The alloc_string_stream() functions were changed from returning NULL on
    error to returning error pointers so these caller needs to be updated
    as well.

    Fixes: 78b1c6584fce ("kunit: string-stream: Simplify resource use")
    Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
    Reviewed-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:54 -06:00
Nico Pache dba9a6413b kunit: string-stream: Simplify resource use
commit 78b1c6584fcedcf2d9687a4455c461859094cf04
Author: David Gow <davidgow@google.com>
Date:   Fri Jul 22 17:15:30 2022 +0000

    kunit: string-stream: Simplify resource use

    Currently, KUnit's string streams are themselves "KUnit resources".
    This is redundant since the stream itself is already allocated with
    kunit_kzalloc() and will thus be freed automatically at the end of the
    test.

    string-stream is only used internally within KUnit, and isn't using the
    extra features that resources provide like reference counting, being
    able to locate them dynamically as "test-local variables", etc.

    Indeed, the resource's refcount is never incremented when the
    pointer is returned. The fact that it's always manually destroyed is
    more evidence that the reference counting is unused.

    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:53 -06:00
Nico Pache d659ce544c kunit: add kunit.enable to enable/disable KUnit test
commit d20a6ba5e3be5f8d9002c6c5a5d4dfecc5dc48f9
Author: Joe Fradley <joefradley@google.com>
Date:   Tue Aug 23 07:24:54 2022 -0700

    kunit: add kunit.enable to enable/disable KUnit test

    This patch adds the kunit.enable module parameter that will need to be
    set to true in addition to KUNIT being enabled for KUnit tests to run.
    The default value is true giving backwards compatibility. However, for
    the production+testing use case the new config option
    KUNIT_DEFAULT_ENABLED can be set to N requiring the tester to opt-in
    by passing kunit.enable=1 to the kernel.

    Signed-off-by: Joe Fradley <joefradley@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

JIRA: https://issues.redhat.com/browse/RHEL-5618
Signed-off-by: Nico Pache <npache@redhat.com>
2023-11-02 15:26:53 -06:00
Nico Pache 63a96edc7c kunit: remove format func from struct kunit_assert, get it to 0 bytes
commit a8495ad8e973cb6aabbe855d3dfb66ec4c9b281a
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Sep 30 17:26:35 2022 -0700

    kunit: remove format func from struct kunit_assert, get it to 0 bytes

    Each calll to a KUNIT_EXPECT_*() macro creates a local variable which
    contains a struct kunit_assert.

    Normally, we'd hope the compiler would be able to optimize this away,
    but we've seen cases where it hasn't, see
    https://groups.google.com/g/kunit-dev/c/i3fZXgvBrfA/m/GbrMNej2BAAJ.

    In changes like commit 21957f90b28f ("kunit: split out part of
    kunit_assert into a static const"), we've moved more and more parts out
    of struct kunit_assert and its children types (kunit_binary_assert).

    This patch removes the final field and gets us to:
      sizeof(struct kunit_assert) == 0
      sizeof(struct kunit_binary_assert) == 24 (on UML x86_64).

    This also reduces the amount of macro plumbing going on at the cost of
    passing in one more arg to the base KUNIT_ASSERTION macro and
    kunit_do_failed_assertion().

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:38 -06:00
Nico Pache 4b0fc605a2 kunit: flatten kunit_suite*** to kunit_suite** in .kunit_test_suites
commit e5857d396f35e59e6fe96cf1178b0357cc3a1ea4
Author: Daniel Latypov <dlatypov@google.com>
Date:   Sat Jul 9 11:19:58 2022 +0800

    kunit: flatten kunit_suite*** to kunit_suite** in .kunit_test_suites

    We currently store kunit suites in the .kunit_test_suites ELF section as
    a `struct kunit_suite***` (modulo some `const`s).
    For every test file, we store a struct kunit_suite** NULL-terminated array.

    This adds quite a bit of complexity to the test filtering code in the
    executor.

    Instead, let's just make the .kunit_test_suites section contain a single
    giant array of struct kunit_suite pointers, which can then be directly
    manipulated. This array is not NULL-terminated, and so none of the test
    filtering code needs to NULL-terminate anything.

    Tested-by: Maíra Canal <maira.canal@usp.br>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Co-developed-by: David Gow <davidgow@google.com>
    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:37 -06:00
Nico Pache 6a735e5db9 kunit: unify module and builtin suite definitions
commit 3d6e44623841c8b82c2157f2f749019803fb238a
Author: Jeremy Kerr <jk@codeconstruct.com.au>
Date:   Sat Jul 9 11:19:57 2022 +0800

    kunit: unify module and builtin suite definitions

    Currently, KUnit runs built-in tests and tests loaded from modules
    differently. For built-in tests, the kunit_test_suite{,s}() macro adds a
    list of suites in the .kunit_test_suites linker section. However, for
    kernel modules, a module_init() function is used to run the test suites.

    This causes problems if tests are included in a module which already
    defines module_init/exit_module functions, as they'll conflict with the
    kunit-provided ones.

    This change removes the kunit-defined module inits, and instead parses
    the kunit tests from their own section in the module. After module init,
    we call __kunit_test_suites_init() on the contents of that section,
    which prepares and runs the suite.

    This essentially unifies the module- and non-module kunit init formats.

    Tested-by: Maíra Canal <maira.canal@usp.br>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Jeremy Kerr <jk@codeconstruct.com.au>
    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Signed-off-by: David Gow <davidgow@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:37 -06:00
Nico Pache fd5f3203eb kunit: Taint the kernel when KUnit tests are run
commit c272612cb4a2f7cde550d35f46cde159a2af0bab
Author: David Gow <davidgow@google.com>
Date:   Fri Jul 1 16:47:43 2022 +0800

    kunit: Taint the kernel when KUnit tests are run

    Make KUnit trigger the new TAINT_TEST taint when any KUnit test is run.
    Due to KUnit tests not being intended to run on production systems, and
    potentially causing problems (or security issues like leaking kernel
    addresses), the kernel's state should not be considered safe for
    production use after KUnit tests are run.

    This both marks KUnit modules as test modules using MODULE_INFO() and
    manually taints the kernel when tests are run (which catches builtin
    tests).

    Acked-by: Luis Chamberlain <mcgrof@kernel.org>
    Tested-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: David Gow <davidgow@google.com>
    Tested-by: Maíra Canal <mairacanal@riseup.net>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:36 -06:00
Nico Pache 7e5fa39c3a kunit: take `kunit_assert` as `const`
commit 7466886b400b1904ce30fa311904849e314a2cf4
Author: Miguel Ojeda <ojeda@kernel.org>
Date:   Mon May 2 11:36:25 2022 +0200

    kunit: take `kunit_assert` as `const`

    The `kunit_do_failed_assertion` function passes its
    `struct kunit_assert` argument to `kunit_fail`. This one,
    in turn, calls its `format` field passing the assert again
    as a `const` pointer.

    Therefore, the whole chain may be made `const`.

    Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
    Reviewed-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: Kees Cook <keescook@chromium.org>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:35 -06:00
Nico Pache 699445ef3b kunit: add ability to specify suite-level init and exit functions
commit 1cdba21db2ca31514c60b9732fc3963ae24c59e0
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Apr 29 11:12:57 2022 -0700

    kunit: add ability to specify suite-level init and exit functions

    KUnit has support for setup/cleanup logic for each test case in a suite.
    But it lacks the ability to specify setup/cleanup for the entire suite
    itself.

    This can be used to do setup that is too expensive or cumbersome to do
    for each test.
    Or it can be used to do simpler things like log debug information after
    the suite completes.
    It's a fairly common feature, so the lack of it is noticeable.

    Some examples in other frameworks and languages:
    * https://docs.python.org/3/library/unittest.html#setupclass-and-teardownclass
    * https://google.github.io/googletest/reference/testing.html#Test::SetUpTestSuite

    Meta:
    This is very similar to this patch here: https://lore.kernel.org/linux-kselftest/20210805043503.20252-3-bvanassche@acm.org/
    The changes from that patch:
    * pass in `struct kunit *` so users can do stuff like
      `kunit_info(suite, "debug message")`
    * makes sure the init failure is bubbled up as a failure
    * updates kunit-example-test.c to use a suite init
    * Updates kunit/usage.rst to mention the new support
    * some minor cosmetic things
      * use `suite_{init,exit}` instead of `{init/exit}_suite`
      * make suite init error message more consistent w/ test init
      * etc.

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:35 -06:00
Nico Pache 4fd2016d57 kunit: rename print_subtest_{start,end} for clarity (s/subtest/suite)
commit cae56e1740f559703c94b7f4d772d873b8a01395
Author: Daniel Latypov <dlatypov@google.com>
Date:   Fri Apr 29 11:12:56 2022 -0700

    kunit: rename print_subtest_{start,end} for clarity (s/subtest/suite)

    These names sound more general than they are.

    The _end() function increments a `static int kunit_suite_counter`, so it
    can only safely be called on suites, aka top-level subtests.
    It would need to have a separate counter for each level of subtest to be
    generic enough.

    So rename it to make it clear it's only appropriate for suites.

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:35 -06:00
Nico Pache 4db05af562 kunit: split resource API impl from test.c into new resource.c
commit cdebea6968faafa955b3cc9196003e7f17f78955
Author: Daniel Latypov <dlatypov@google.com>
Date:   Mon Mar 28 10:41:43 2022 -0700

    kunit: split resource API impl from test.c into new resource.c

    We've split out the declarations from include/kunit/test.h into
    resource.h.
    This patch splits out the definitions as well for consistency.

    A side effect of this is git blame won't properly track history by
    default, users need to run
    $ git blame -L ,1 -C13 lib/kunit/resource.c

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:47:34 -06:00
Nico Pache 019707eacb kunit: remove va_format from kunit_assert
commit 6419abb80e82c603bbec6d7f5af6c2f79fa5c4ae
Author: Daniel Latypov <dlatypov@google.com>
Date:   Tue Jan 25 13:00:09 2022 -0800

    kunit: remove va_format from kunit_assert

    The concern is that having a lot of redundant fields in kunit_assert can
    blow up stack usage if the compiler doesn't optimize them away [1].

    The comment on this field implies that it was meant to be initialized
    when the expect/assert was declared, but this only happens when we run
    kunit_do_failed_assertion().

    We don't need to access it outside of that function, so move it out of
    the struct and make it a local variable there.

    This change also takes the chance to reduce the number of macros by
    inlining the now simplified KUNIT_INIT_ASSERT_STRUCT() macro.

    [1] https://groups.google.com/g/kunit-dev/c/i3fZXgvBrfA/m/VULQg1z6BAAJ

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:20:43 -06:00
Nico Pache 02ddab24e7 kunit: split out part of kunit_assert into a static const
commit 21957f90b28f6bc118c055e3e564d45f6e4df45d
Author: Daniel Latypov <dlatypov@google.com>
Date:   Thu Jan 13 08:59:30 2022 -0800

    kunit: split out part of kunit_assert into a static const

    This is per Linus's suggestion in [1].

    The issue there is that every KUNIT_EXPECT/KUNIT_ASSERT puts a
    kunit_assert object onto the stack. Normally we rely on compilers to
    elide this, but when that doesn't work out, this blows up the stack
    usage of kunit test functions.

    We can move some data off the stack by making it static.
    This change introduces a new `struct kunit_loc` to hold the file and
    line number and then just passing assert_type (EXPECT or ASSERT) as an
    argument.

    In [1], it was suggested to also move out the format string as well, but
    users could theoretically craft a format string at runtime, so we can't.

    This change leaves a copy of `assert_type` in kunit_assert for now
    because cleaning up all the macros to not pass it around is a bit more
    involved.

    Here's an example of the expanded code for KUNIT_FAIL():
    if (__builtin_expect(!!(!(false)), 0)) {
      static const struct kunit_loc loc = { .file = ... };
      struct kunit_fail_assert __assertion = { .assert = { .type ...  };
      kunit_do_failed_assertion(test, &loc, KUNIT_EXPECTATION, &__assertion.assert, ...);
    };

    [1] https://groups.google.com/g/kunit-dev/c/i3fZXgvBrfA/m/VULQg1z6BAAJ

    Signed-off-by: Daniel Latypov <dlatypov@google.com>
    Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
    Reviewed-by: David Gow <davidgow@google.com>
    Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
    Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2168378
Signed-off-by: Nico Pache <npache@redhat.com>
2023-04-17 11:20:43 -06:00