map: process dns patterns in the order in which they were defined
[project/qosify.git] / loader.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright (C) 2021 Felix Fietkau <nbd@nbd.name>
4 */
5 #include <sys/resource.h>
6 #include <sys/stat.h>
7 #include <arpa/inet.h>
8 #include <glob.h>
9 #include <unistd.h>
10
11 #include "qosify.h"
12
13 static int qosify_bpf_pr(enum libbpf_print_level level, const char *format,
14 va_list args)
15 {
16 return vfprintf(stderr, format, args);
17 }
18
19 static void qosify_init_env(void)
20 {
21 struct rlimit limit = {
22 .rlim_cur = RLIM_INFINITY,
23 .rlim_max = RLIM_INFINITY,
24 };
25
26 setrlimit(RLIMIT_MEMLOCK, &limit);
27 }
28
29 static void qosify_fill_rodata(struct bpf_object *obj, uint32_t flags)
30 {
31 struct bpf_map *map = NULL;
32
33 while ((map = bpf_map__next(map, obj)) != NULL) {
34 if (!strstr(bpf_map__name(map), ".rodata"))
35 continue;
36
37 bpf_map__set_initial_value(map, &flags, sizeof(flags));
38 }
39 }
40
41 static int
42 qosify_create_program(const char *suffix, uint32_t flags)
43 {
44 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
45 .pin_root_path = CLASSIFY_DATA_PATH,
46 );
47 struct bpf_program *prog;
48 struct bpf_object *obj;
49 char path[256];
50 int err;
51
52 snprintf(path, sizeof(path), CLASSIFY_PIN_PATH "_" "%s", suffix);
53
54 obj = bpf_object__open_file(CLASSIFY_PROG_PATH, &opts);
55 err = libbpf_get_error(obj);
56 if (err) {
57 perror("bpf_object__open_file");
58 return -1;
59 }
60
61 prog = bpf_object__find_program_by_title(obj, "classifier");
62 if (!prog) {
63 fprintf(stderr, "Can't find classifier prog\n");
64 return -1;
65 }
66
67 bpf_program__set_type(prog, BPF_PROG_TYPE_SCHED_CLS);
68
69 qosify_fill_rodata(obj, flags);
70
71 err = bpf_object__load(obj);
72 if (err) {
73 perror("bpf_object__load");
74 return -1;
75 }
76
77 libbpf_set_print(NULL);
78
79 unlink(path);
80 err = bpf_program__pin(prog, path);
81 if (err) {
82 fprintf(stderr, "Failed to pin program to %s: %s\n",
83 path, strerror(-err));
84 }
85
86 bpf_object__close(obj);
87
88 return 0;
89 }
90
91 int qosify_loader_init(void)
92 {
93 static const struct {
94 const char *suffix;
95 uint32_t flags;
96 } progs[] = {
97 { "egress_eth", 0 },
98 { "egress_ip", QOSIFY_IP_ONLY },
99 { "ingress_eth", QOSIFY_INGRESS },
100 { "ingress_ip", QOSIFY_INGRESS | QOSIFY_IP_ONLY },
101 };
102 glob_t g;
103 int i;
104
105 if (glob(CLASSIFY_DATA_PATH "/*", 0, NULL, &g) == 0) {
106 for (i = 0; i < g.gl_pathc; i++)
107 unlink(g.gl_pathv[i]);
108 }
109
110
111 libbpf_set_print(qosify_bpf_pr);
112
113 qosify_init_env();
114
115 for (i = 0; i < ARRAY_SIZE(progs); i++) {
116 if (qosify_create_program(progs[i].suffix, progs[i].flags))
117 return -1;
118 }
119
120 return 0;
121 }