xref: /linux/kernel/bpf/preload/bpf_preload_kern.c (revision 906fd46a65383cd639e5eec72a047efc33045d86)
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 #include <linux/init.h>
4 #include <linux/module.h>
5 #include "bpf_preload.h"
6 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
7 #include "iterators/iterators.lskel-little-endian.h"
8 #else
9 #include "iterators/iterators.lskel-big-endian.h"
10 #endif
11 
12 static struct bpf_link *maps_link, *progs_link;
13 static struct iterators_bpf *skel;
14 
15 static void free_links_and_skel(void)
16 {
17 	if (!IS_ERR_OR_NULL(maps_link))
18 		bpf_link_put(maps_link);
19 	if (!IS_ERR_OR_NULL(progs_link))
20 		bpf_link_put(progs_link);
21 	iterators_bpf__destroy(skel);
22 }
23 
24 static int preload(struct bpf_preload_info *obj)
25 {
26 	strscpy(obj[0].link_name, "maps.debug", sizeof(obj[0].link_name));
27 	obj[0].link = maps_link;
28 	strscpy(obj[1].link_name, "progs.debug", sizeof(obj[1].link_name));
29 	obj[1].link = progs_link;
30 	return 0;
31 }
32 
33 static struct bpf_preload_ops ops = {
34 	.preload = preload,
35 	.owner = THIS_MODULE,
36 };
37 
38 static int load_skel(void)
39 {
40 	int err;
41 
42 	skel = iterators_bpf__open();
43 	if (!skel)
44 		return -ENOMEM;
45 	err = iterators_bpf__load(skel);
46 	if (err)
47 		goto out;
48 	err = iterators_bpf__attach(skel);
49 	if (err)
50 		goto out;
51 	maps_link = bpf_link_get_from_fd(skel->links.dump_bpf_map_fd);
52 	if (IS_ERR(maps_link)) {
53 		err = PTR_ERR(maps_link);
54 		goto out;
55 	}
56 	progs_link = bpf_link_get_from_fd(skel->links.dump_bpf_prog_fd);
57 	if (IS_ERR(progs_link)) {
58 		err = PTR_ERR(progs_link);
59 		goto out;
60 	}
61 	/* Avoid taking over stdin/stdout/stderr of init process. Zeroing out
62 	 * makes skel_closenz() a no-op later in iterators_bpf__destroy().
63 	 */
64 	close_fd(skel->links.dump_bpf_map_fd);
65 	skel->links.dump_bpf_map_fd = 0;
66 	close_fd(skel->links.dump_bpf_prog_fd);
67 	skel->links.dump_bpf_prog_fd = 0;
68 	return 0;
69 out:
70 	free_links_and_skel();
71 	return err;
72 }
73 
74 static int __init load(void)
75 {
76 	int err;
77 
78 	err = load_skel();
79 	if (err)
80 		return err;
81 	bpf_preload_ops = &ops;
82 	return err;
83 }
84 
85 static void __exit fini(void)
86 {
87 	bpf_preload_ops = NULL;
88 	free_links_and_skel();
89 }
90 late_initcall(load);
91 module_exit(fini);
92 MODULE_LICENSE("GPL");
93