1 // SPDX-License-Identifier: GPL-2.0
3 * KUnit resource API for test managed resources (allocations, etc.).
5 * Copyright (C) 2022, Google LLC.
6 * Author: Daniel Latypov <dlatypov@google.com>
9 #include <kunit/resource.h>
10 #include <kunit/test.h>
11 #include <linux/kref.h>
14 * Used for static resources and when a kunit_resource * has been created by
15 * kunit_alloc_resource(). When an init function is supplied, @data is passed
16 * into the init function; otherwise, we simply set the resource data field to
17 * the data value passed in. Doesn't initialize res->should_kfree.
19 int __kunit_add_resource(struct kunit *test,
20 kunit_resource_init_t init,
21 kunit_resource_free_t free,
22 struct kunit_resource *res,
29 kref_init(&res->refcount);
32 ret = init(res, data);
39 spin_lock_irqsave(&test->lock, flags);
40 list_add_tail(&res->node, &test->resources);
41 /* refcount for list is established by kref_init() */
42 spin_unlock_irqrestore(&test->lock, flags);
46 EXPORT_SYMBOL_GPL(__kunit_add_resource);
48 void kunit_remove_resource(struct kunit *test, struct kunit_resource *res)
53 spin_lock_irqsave(&test->lock, flags);
54 was_linked = !list_empty(&res->node);
55 list_del_init(&res->node);
56 spin_unlock_irqrestore(&test->lock, flags);
59 kunit_put_resource(res);
61 EXPORT_SYMBOL_GPL(kunit_remove_resource);
63 int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
66 struct kunit_resource *res = kunit_find_resource(test, match,
72 kunit_remove_resource(test, res);
74 /* We have a reference also via _find(); drop it. */
75 kunit_put_resource(res);
79 EXPORT_SYMBOL_GPL(kunit_destroy_resource);