Re: [PATCH V1 2/2] lib/tests/slub_kunit: add a test case for {kmalloc,kfree}_nolock

Harry Yoo (Oracle)
2026-03-31T03:04:47Z

On Mon, Mar 30, 2026 at 09:05:16PM +0900, Harry Yoo (Oracle) wrote:
> Testing invocation of {kmalloc,kfree}_nolock() during kmalloc() or
> kfree() is tricky, and it is even harder to ensure that slowpaths are
> properly tested. Lack of such testing has led to late discovery of
> the bug fixed by commit a1e244a9f177 ("mm/slab: use prandom if
> !allow_spin").
>
> Add a slub_kunit test that allocates and frees objects in a tight loop
> while a perf event triggers NMIs on the same task, invoking
> {kmalloc,kfree}_nolock() from the NMI handler.
>
> Signed-off-by: Harry Yoo (Oracle) <harry@kernel.org>
> ---
> lib/tests/slub_kunit.c | 88 ++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 88 insertions(+)
>
> diff --git a/lib/tests/slub_kunit.c b/lib/tests/slub_kunit.c
> index 848b682a2d70..2ed5f90a748a 100644
> --- a/lib/tests/slub_kunit.c
> +++ b/lib/tests/slub_kunit.c
> +static void test_kmalloc_kfree_nolock(struct kunit *test)
> +{
> + int i, j;
> + struct nmi_context ctx = { .test = test };
> + struct perf_event *event;
> + bool alloc_fail = false;
> +
> + event = perf_event_create_kernel_counter(&nmi_hw_attr, -1, current,
> + kmalloc_kfree_nolock_in_nmi,
> + &ctx);
> + if (IS_ERR(event))
> + kunit_skip(test, "Failed to create perf event");
> + ctx.event = event;
> + perf_event_enable(ctx.event);
> + for (i = 0; i < REPEAT_TIMES; i++) {
> + for (j = 0; j < LOOP_SIZE; j++) {
> + gfp_t gfp = (i % 2) ? 0 : __GFP_ACCOUNT;

One thing sashiko pointed out [1]: '0' as gfp for kmalloc() is
unnecessarily restrictive. (it's not kmalloc_nolock()!), it should be:

`gfp_t gfp = (i % 2) ? GFP_KERNEL : GFP_KERNEL_ACCOUNT;`

[1] https://sashiko.dev/#/patchset/20260330120517.104743-1-harry%40kernel.org

--
Cheers,
Harry / Hyeonggon