xref: /linux/drivers/of/of_kunit_helpers.c (revision 3ba84ac69b53e6ee07c31d54554e00793d7b144f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Test managed DeviceTree APIs
4  */
5 
6 #include <linux/of.h>
7 #include <linux/of_fdt.h>
8 
9 #include <kunit/of.h>
10 #include <kunit/test.h>
11 #include <kunit/resource.h>
12 
13 #if defined(CONFIG_OF_OVERLAY) && defined(CONFIG_OF_EARLY_FLATTREE)
14 
15 static void of_overlay_fdt_apply_kunit_exit(void *ovcs_id)
16 {
17 	of_overlay_remove(ovcs_id);
18 }
19 
20 /**
21  * of_overlay_fdt_apply_kunit() - Test managed of_overlay_fdt_apply()
22  * @test: test context
23  * @overlay_fdt: device tree overlay to apply
24  * @overlay_fdt_size: size in bytes of @overlay_fdt
25  * @ovcs_id: identifier of overlay, used to remove the overlay
26  *
27  * Just like of_overlay_fdt_apply(), except the overlay is managed by the test
28  * case and is automatically removed with of_overlay_remove() after the test
29  * case concludes.
30  *
31  * Return: 0 on success, negative errno on failure
32  */
33 int of_overlay_fdt_apply_kunit(struct kunit *test, void *overlay_fdt,
34 			       u32 overlay_fdt_size, int *ovcs_id)
35 {
36 	int ret;
37 	int *copy_id;
38 
39 	copy_id = kunit_kmalloc(test, sizeof(*copy_id), GFP_KERNEL);
40 	if (!copy_id)
41 		return -ENOMEM;
42 
43 	ret = of_overlay_fdt_apply(overlay_fdt, overlay_fdt_size,
44 				   ovcs_id, NULL);
45 	if (ret)
46 		return ret;
47 
48 	*copy_id = *ovcs_id;
49 
50 	return kunit_add_action_or_reset(test, of_overlay_fdt_apply_kunit_exit,
51 					 copy_id);
52 }
53 EXPORT_SYMBOL_GPL(of_overlay_fdt_apply_kunit);
54 
55 #endif
56 
57 KUNIT_DEFINE_ACTION_WRAPPER(of_node_put_wrapper, of_node_put, struct device_node *);
58 
59 /**
60  * of_node_put_kunit() - Test managed of_node_put()
61  * @test: test context
62  * @node: node to pass to `of_node_put()`
63  *
64  * Just like of_node_put(), except the node is managed by the test case and is
65  * automatically put with of_node_put() after the test case concludes.
66  */
67 void of_node_put_kunit(struct kunit *test, struct device_node *node)
68 {
69 	if (kunit_add_action(test, of_node_put_wrapper, node)) {
70 		KUNIT_FAIL(test,
71 			   "Can't allocate a kunit resource to put of_node\n");
72 	}
73 }
74 EXPORT_SYMBOL_GPL(of_node_put_kunit);
75 
76 MODULE_LICENSE("GPL");
77 MODULE_DESCRIPTION("Test managed DeviceTree APIs");
78