[PATCH] lib/sbitmap: test that free() clears alloc_hint and ws

From: Wang Yibo

Date: Thu Dec 03 2026 - 03:36:14 EST


Bart Van Assche's commit ddca9a368588 ("sbitmap: Clear alloc_hint and
ws pointers after freeing") made sbitmap_free() and sbitmap_queue_free()
clear the pointers they free, so that repeated teardown is safe. Andrew
Morton asked for the sbitmap KUnit suite to be updated to cover this.

Extend the suite to check that sbitmap_free() clears alloc_hint and that
sbitmap_queue_free() clears ws, including a second free of each object
to pin down the idempotency that the scsi error-cleanup path relies on.

Link: https://lore.kernel.org/r/20261202112938.a596225d374bdf002bd1ad81@xxxxxxxxxxxxxxxxxxxx
Signed-off-by: Wang Yibo <wangyibo@xxxxxxxxxx>
---
lib/tests/sbitmap_kunit.c | 41 +++++++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)

diff --git a/lib/tests/sbitmap_kunit.c b/lib/tests/sbitmap_kunit.c
index 284dcb5..935d143 100644
--- a/lib/tests/sbitmap_kunit.c
+++ b/lib/tests/sbitmap_kunit.c
@@ -45,6 +45,7 @@ static void sbitmap_test_init(struct kunit *test)
KUNIT_EXPECT_FALSE(test, sbitmap_any_bit_set(&sb));
KUNIT_EXPECT_EQ(test, sbitmap_weight(&sb), 0U);
sbitmap_free(&sb);
+ KUNIT_EXPECT_FALSE(test, sb.alloc_hint);

/* An explicitly requested shift is honoured. */
ret = sbitmap_init_node(&sb, depth, 3, GFP_KERNEL, NUMA_NO_NODE,
@@ -285,6 +286,44 @@ static void sbitmap_test_iterate_set(struct kunit *test)
sbitmap_free(&sb);
}

+static void sbitmap_test_free_clears_alloc_hint(struct kunit *test)
+{
+ struct sbitmap sb;
+
+ KUNIT_ASSERT_EQ(test, sbitmap_init_node(&sb, BITS_PER_LONG, -1,
+ GFP_KERNEL, NUMA_NO_NODE,
+ false, true), 0);
+ KUNIT_EXPECT_TRUE(test, sb.alloc_hint);
+
+ sbitmap_free(&sb);
+
+ /*
+ * alloc_hint is a __percpu pointer, so test it as a boolean, as in
+ * sbitmap_test_init(). Clearing it makes repeated teardown safe,
+ * which is what the scsi error-cleanup path relies on.
+ */
+ KUNIT_EXPECT_FALSE(test, sb.alloc_hint);
+ sbitmap_free(&sb);
+ KUNIT_EXPECT_FALSE(test, sb.alloc_hint);
+}
+
+static void sbitmap_test_queue_free_clears_ws(struct kunit *test)
+{
+ struct sbitmap_queue sbq;
+
+ KUNIT_ASSERT_EQ(test, sbitmap_queue_init_node(&sbq, BITS_PER_LONG, -1,
+ false, GFP_KERNEL,
+ NUMA_NO_NODE), 0);
+ KUNIT_EXPECT_TRUE(test, sbq.ws);
+
+ sbitmap_queue_free(&sbq);
+
+ KUNIT_EXPECT_NULL(test, sbq.ws);
+ /* Repeated teardown must not pass a stale ws to kfree(). */
+ sbitmap_queue_free(&sbq);
+ KUNIT_EXPECT_NULL(test, sbq.ws);
+}
+
static struct kunit_case sbitmap_test_cases[] = {
KUNIT_CASE(sbitmap_test_init),
KUNIT_CASE(sbitmap_test_calculate_shift),
@@ -294,6 +333,8 @@ static struct kunit_case sbitmap_test_cases[] = {
KUNIT_CASE(sbitmap_test_resize),
KUNIT_CASE(sbitmap_test_set_clear_bit),
KUNIT_CASE(sbitmap_test_iterate_set),
+ KUNIT_CASE(sbitmap_test_free_clears_alloc_hint),
+ KUNIT_CASE(sbitmap_test_queue_free_clears_ws),
{}
};

--
2.25.1