Branch data Line data Source code
1 : : /* SPDX-License-Identifier: GPL-2.0-only */
2 : : /*
3 : : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : : */
5 : :
6 : : #include "cgen/codegen.h"
7 : :
8 : : #include <linux/bpf.h>
9 : : #include <linux/bpf_common.h>
10 : : #include <linux/if_ether.h>
11 : : #include <linux/in.h> // NOLINT
12 : : #include <linux/limits.h>
13 : :
14 : : #include <endian.h>
15 : : #include <errno.h>
16 : : #include <fcntl.h>
17 : : #include <limits.h>
18 : : #include <stdbool.h>
19 : : #include <stddef.h>
20 : : #include <stdint.h>
21 : : #include <stdio.h>
22 : : #include <stdlib.h>
23 : : #include <string.h>
24 : : #include <unistd.h>
25 : :
26 : : #include <bpfilter/bpf.h>
27 : : #include <bpfilter/btf.h>
28 : : #include <bpfilter/chain.h>
29 : : #include <bpfilter/core/hashset.h>
30 : : #include <bpfilter/core/list.h>
31 : : #include <bpfilter/counter.h>
32 : : #include <bpfilter/ctx.h>
33 : : #include <bpfilter/dump.h>
34 : : #include <bpfilter/flavor.h>
35 : : #include <bpfilter/helper.h>
36 : : #include <bpfilter/hook.h>
37 : : #include <bpfilter/io.h>
38 : : #include <bpfilter/logger.h>
39 : : #include <bpfilter/matcher.h>
40 : : #include <bpfilter/pack.h>
41 : : #include <bpfilter/rule.h>
42 : : #include <bpfilter/set.h>
43 : : #include <bpfilter/verdict.h>
44 : :
45 : : #include "cgen/cgroup_skb.h"
46 : : #include "cgen/cgroup_sock_addr.h"
47 : : #include "cgen/dump.h"
48 : : #include "cgen/fixup.h"
49 : : #include "cgen/handle.h"
50 : : #include "cgen/jmp.h"
51 : : #include "cgen/nf.h"
52 : : #include "cgen/printer.h"
53 : : #include "cgen/prog/link.h"
54 : : #include "cgen/prog/map.h"
55 : : #include "cgen/stub.h"
56 : : #include "cgen/tc.h"
57 : : #include "cgen/xdp.h"
58 : : #include "filter.h"
59 : :
60 : : #define _BF_LOG_BUF_SIZE \
61 : : (UINT32_MAX >> 8U) /* verifier maximum in kernels <= 5.1 */
62 : : #define _BF_LOG_MAP_N_ENTRIES 1000
63 : : #define _BF_LOG_MAP_SIZE \
64 : : _bf_round_next_power_of_2(sizeof(struct bf_log) * _BF_LOG_MAP_N_ENTRIES)
65 : : #define _BF_SET_MAP_PREFIX "bf_set_"
66 : : #define _BF_COUNTER_MAP_NAME "bf_cmap"
67 : : #define _BF_PRINTER_MAP_NAME "bf_pmap"
68 : : #define _BF_LOG_MAP_NAME "bf_lmap"
69 : : #define _BF_STATE_MAP_NAME "bf_smap"
70 : :
71 : : static inline size_t _bf_round_next_power_of_2(size_t value)
72 : : {
73 : : if (value == 0)
74 : : return 1;
75 : :
76 : : value--;
77 : : value |= value >> 1U;
78 : : value |= value >> 2U;
79 : : value |= value >> 4U;
80 : : value |= value >> 8U;
81 : : value |= value >> 16U;
82 : : #if SIZE_MAX > 0xFFFFFFFFU
83 : : value |= value >> 32U;
84 : : #endif
85 : :
86 : : return ++value;
87 : : }
88 : :
89 : : /**
90 : : * @brief Sets sharing the same key format, collapsed to a single BPF map.
91 : : *
92 : : * For hash-keyed sets, one `bf_set_group` exists for every unique key
93 : : * format among a chain's non-empty sets. The sets list preserves insertion
94 : : * order; a set's position is its bit index within the group's bitmask
95 : : * value.
96 : : *
97 : : * LPM trie sets are never grouped together: each non-empty trie set gets
98 : : * its own group of size 1. See `_bf_codegen_build_set_groups()` for the
99 : : * rationale.
100 : : */
101 : : struct bf_set_group
102 : : {
103 : : /** Non-empty sets that map to the same BPF map. For hash-keyed groups,
104 : : * all sets share the same key format; LPM trie groups always hold a
105 : : * single set. Non-owning pointers into the chain's `bf_set` list.
106 : : * Never empty. */
107 : : bf_list sets;
108 : :
109 : : /** Backing BPF map. Populated during `bf_codegen_load()`; the map is
110 : : * owned by `bf_codegen->handle->sets`. */
111 : : struct bf_map *map;
112 : : };
113 : :
114 : : #define _free_bf_set_group_ __attribute__((__cleanup__(_bf_set_group_free)))
115 : :
116 : 1142 : static void _bf_set_group_free(struct bf_set_group **group)
117 : : {
118 : : assert(group);
119 : :
120 [ + + ]: 1142 : if (!*group)
121 : : return;
122 : :
123 : 364 : bf_list_clean(&(*group)->sets);
124 : 364 : BF_FREEP(group);
125 : : }
126 : :
127 : 364 : static int _bf_set_group_new(struct bf_set_group **group)
128 : : {
129 : 364 : _free_bf_set_group_ struct bf_set_group *_group = NULL;
130 : :
131 : : assert(group);
132 : :
133 : 364 : _group = calloc(1, sizeof(*_group));
134 [ + - ]: 364 : if (!_group)
135 : : return -ENOMEM;
136 : :
137 : : /* The list holds non-owning const struct bf_set * pointers; no free
138 : : * callback. Groups are temporary (not serialized), so no pack callback
139 : : * either. */
140 : 364 : _group->sets = bf_list_default(NULL, NULL);
141 : :
142 : 364 : *group = TAKE_PTR(_group);
143 : :
144 : 364 : return 0;
145 : : }
146 : :
147 : : static struct bf_set_group *
148 : 341 : _bf_codegen_find_set_group(const struct bf_codegen *program,
149 : : const struct bf_set *set)
150 : : {
151 : : assert(program);
152 : :
153 [ + - ]: 341 : if (!set)
154 : : return NULL;
155 : :
156 [ + - + - : 884 : bf_list_foreach (&program->set_groups, group_node) {
+ - ]
157 : : struct bf_set_group *group = bf_list_node_get_data(group_node);
158 [ + - + + : 1204 : bf_list_foreach (&group->sets, set_node) {
+ + ]
159 [ + + ]: 501 : if (bf_list_node_get_data(set_node) == set)
160 : : return group;
161 : : }
162 : : }
163 : :
164 : : return NULL;
165 : : }
166 : :
167 : 414 : static int _bf_codegen_add_set_to_group(struct bf_codegen *program,
168 : : const struct bf_set *set)
169 : : {
170 : 414 : _free_bf_set_group_ struct bf_set_group *group = NULL;
171 : : int r;
172 : :
173 : : assert(program);
174 : : assert(set);
175 : :
176 [ + + ]: 414 : if (bf_hashset_is_empty(&set->elems))
177 : : return 0;
178 : :
179 : : /* If a group with a matching key already exists, reuse it. For LPM trie,
180 : : * sets can't be grouped (as we can't define which rule matches on which
181 : : * prefix), so they always are the sole member of their group. */
182 [ + + ]: 392 : if (!set->use_trie) {
183 [ + + + + : 856 : bf_list_foreach (&program->set_groups, group_node) {
+ + ]
184 : : struct bf_set_group *group = bf_list_node_get_data(group_node);
185 : : const struct bf_set *head =
186 : : bf_list_node_get_data(bf_list_get_head(&group->sets));
187 : :
188 [ + + ]: 129 : if (bf_set_same_key(set, head)) {
189 : 28 : r = bf_list_add_tail(&group->sets, (void *)set);
190 [ - + ]: 28 : if (r)
191 [ # # ]: 0 : return bf_err_r(r, "failed to add set to existing group");
192 : :
193 : : return 0;
194 : : }
195 : : }
196 : : }
197 : :
198 : 364 : r = _bf_set_group_new(&group);
199 [ - + ]: 364 : if (r)
200 [ # # ]: 0 : return bf_err_r(r, "failed to allocate set group");
201 : :
202 : 364 : r = bf_list_add_tail(&group->sets, (void *)set);
203 [ - + ]: 364 : if (r)
204 [ # # ]: 0 : return bf_err_r(r, "failed to seed set group");
205 : :
206 : 364 : r = bf_list_push(&program->set_groups, (void **)&group);
207 [ - + ]: 364 : if (r)
208 [ # # ]: 0 : return bf_err_r(r, "failed to register set group");
209 : :
210 : : return 0;
211 : : }
212 : :
213 : 1475 : static int _bf_codegen_build_set_groups(struct bf_codegen *program)
214 : : {
215 : : assert(program);
216 : :
217 : 1475 : bf_list_clean(&program->set_groups);
218 : 1475 : program->set_groups = bf_list_default(_bf_set_group_free, NULL);
219 : :
220 [ + + + + : 3118 : bf_hashset_foreach (&program->runtime.chain->sets, set_node) {
+ + ]
221 : 84 : int r = _bf_codegen_add_set_to_group(program, set_node->data);
222 [ + - ]: 84 : if (r)
223 : : return r;
224 : : }
225 : :
226 [ + + + + : 6452 : bf_list_foreach (&program->runtime.chain->rules, rule_node) {
+ + ]
227 : : const struct bf_rule *rule = bf_list_node_get_data(rule_node);
228 : :
229 [ + - + + : 9476 : bf_list_foreach (&rule->matchers, matcher_node) {
+ + ]
230 : : const struct bf_matcher *matcher =
231 : : bf_list_node_get_data(matcher_node);
232 : : const struct bf_set *set;
233 : : int r;
234 : :
235 [ + + ]: 2987 : if (bf_matcher_get_type(matcher) != BF_MATCHER_SET)
236 : 2583 : continue;
237 : :
238 : 404 : memcpy(&set, bf_matcher_payload(matcher), sizeof(struct bf_set *));
239 [ + + ]: 404 : if (!bf_set_is_anonymous(set))
240 : 74 : continue;
241 : :
242 : 330 : r = _bf_codegen_add_set_to_group(program, set);
243 [ + - ]: 330 : if (r)
244 : : return r;
245 : : }
246 : : }
247 : :
248 : : return 0;
249 : : }
250 : :
251 : 341 : int bf_codegen_set_bit_index(const struct bf_codegen *program,
252 : : const struct bf_set *set, size_t *bit_index)
253 : : {
254 : : assert(program);
255 : : assert(set);
256 : : assert(bit_index);
257 : :
258 [ + - + - : 884 : bf_list_foreach (&program->set_groups, group_node) {
+ - ]
259 : : struct bf_set_group *group = bf_list_node_get_data(group_node);
260 : : size_t i = 0;
261 : :
262 [ + - + + ]: 1103 : bf_list_foreach (&group->sets, set_node) {
263 [ + + ]: 501 : if (bf_list_node_get_data(set_node) == set) {
264 : 341 : *bit_index = i;
265 : 341 : return 0;
266 : : }
267 [ + + ]: 160 : ++i;
268 : : }
269 : : }
270 : :
271 : : return -ENOENT;
272 : : }
273 : :
274 : : static const struct bf_flavor_ops *bf_flavor_ops_get(enum bf_flavor flavor)
275 : : {
276 : : static const struct bf_flavor_ops *flavor_ops[] = {
277 : : [BF_FLAVOR_TC] = &bf_flavor_ops_tc,
278 : : [BF_FLAVOR_NF] = &bf_flavor_ops_nf,
279 : : [BF_FLAVOR_XDP] = &bf_flavor_ops_xdp,
280 : : [BF_FLAVOR_CGROUP_SKB] = &bf_flavor_ops_cgroup_skb,
281 : : [BF_FLAVOR_CGROUP_SOCK_ADDR] = &bf_flavor_ops_cgroup_sock_addr,
282 : : };
283 : :
284 : : static_assert_enum_mapping(flavor_ops, _BF_FLAVOR_MAX);
285 : :
286 : 1475 : return flavor_ops[flavor];
287 : : }
288 : :
289 : 1477 : int bf_codegen_new(struct bf_codegen **program, struct bf_chain *chain,
290 : : struct bf_handle *handle)
291 : : {
292 : 1477 : _free_bf_codegen_ struct bf_codegen *_program = NULL;
293 : : int r;
294 : :
295 : : assert(program);
296 : : assert(chain);
297 : : assert(handle);
298 : :
299 : : // The chain's derived state can be stale: update it in the caller's chain.
300 : 1477 : r = bf_chain_validate_rules(chain);
301 [ + + ]: 1477 : if (r)
302 : : return r;
303 : :
304 : 1475 : _program = calloc(1, sizeof(*_program));
305 [ + - ]: 1475 : if (!_program)
306 : : return -ENOMEM;
307 : :
308 : 1475 : _program->flavor = bf_hook_to_flavor(chain->hook);
309 : 1475 : _program->runtime.ops = bf_flavor_ops_get(_program->flavor);
310 : 1475 : _program->runtime.chain = chain;
311 : 1475 : _program->img = bf_vector_default(sizeof(struct bpf_insn));
312 : 1475 : _program->fixups = bf_list_default(bf_fixup_free, NULL);
313 : 1475 : _program->set_groups = bf_list_default(_bf_set_group_free, NULL);
314 : 1475 : _program->handle = handle;
315 : :
316 : 1475 : r = bf_vector_reserve(&_program->img, 512);
317 [ + - ]: 1475 : if (r)
318 : : return r;
319 : :
320 : 1475 : r = bf_printer_new(&_program->printer);
321 [ + - ]: 1475 : if (r)
322 : : return r;
323 : :
324 : 1475 : *program = TAKE_PTR(_program);
325 : :
326 : 1475 : return 0;
327 : : }
328 : :
329 : 2954 : void bf_codegen_free(struct bf_codegen **program)
330 : : {
331 : : assert(program);
332 : :
333 [ + + ]: 2954 : if (!*program)
334 : : return;
335 : :
336 : 1475 : bf_list_clean(&(*program)->fixups);
337 : 1475 : bf_list_clean(&(*program)->set_groups);
338 : 1475 : bf_vector_clean(&(*program)->img);
339 : :
340 : 1475 : bf_printer_free(&(*program)->printer);
341 : :
342 : 1475 : free(*program);
343 : 1475 : *program = NULL;
344 : : }
345 : :
346 : 0 : void bf_codegen_dump(const struct bf_codegen *program, prefix_t *prefix)
347 : : {
348 : : assert(program);
349 : : assert(prefix);
350 : :
351 [ # # ]: 0 : DUMP(prefix, "struct bf_codegen at %p", program);
352 : :
353 : 0 : bf_dump_prefix_push(prefix);
354 : :
355 [ # # ]: 0 : DUMP(prefix, "handle: struct bf_handle *");
356 : 0 : bf_dump_prefix_push(prefix);
357 : 0 : bf_handle_dump(program->handle, bf_dump_prefix_last(prefix));
358 : 0 : bf_dump_prefix_pop(prefix);
359 : :
360 [ # # ]: 0 : DUMP(prefix, "printer: struct bf_printer *");
361 : 0 : bf_dump_prefix_push(prefix);
362 : 0 : bf_printer_dump(program->printer, prefix);
363 : 0 : bf_dump_prefix_pop(prefix);
364 : :
365 [ # # ]: 0 : DUMP(prefix, "img: %p", program->img.data);
366 [ # # ]: 0 : DUMP(prefix, "img.size: %lu", program->img.size);
367 [ # # ]: 0 : DUMP(prefix, "img.cap: %lu", program->img.cap);
368 : :
369 [ # # ]: 0 : DUMP(prefix, "fixups: bf_list<struct bf_fixup>[%lu]",
370 : : bf_list_size(&program->fixups));
371 : 0 : bf_dump_prefix_push(prefix);
372 [ # # # # : 0 : bf_list_foreach (&program->fixups, fixup_node) {
# # ]
373 : : struct bf_fixup *fixup = bf_list_node_get_data(fixup_node);
374 : :
375 [ # # ]: 0 : if (bf_list_is_tail(&program->fixups, fixup_node))
376 : 0 : bf_dump_prefix_last(prefix);
377 : :
378 : 0 : bf_fixup_dump(fixup, prefix);
379 : : }
380 : 0 : bf_dump_prefix_pop(prefix);
381 : :
382 [ # # ]: 0 : DUMP(prefix, "groups: bf_list<struct bf_set_group>[%lu]",
383 : : bf_list_size(&program->set_groups));
384 : 0 : bf_dump_prefix_push(prefix);
385 [ # # # # : 0 : bf_list_foreach (&program->set_groups, group_node) {
# # ]
386 : : const struct bf_set_group *group = bf_list_node_get_data(group_node);
387 : : size_t i = 0;
388 : :
389 [ # # ]: 0 : if (bf_list_is_tail(&program->set_groups, group_node))
390 : 0 : bf_dump_prefix_last(prefix);
391 : :
392 [ # # ]: 0 : DUMP(prefix, "struct bf_set_group at %p (%lu set(s), map=%p)", group,
393 : : bf_list_size(&group->sets), (void *)group->map);
394 : 0 : bf_dump_prefix_push(prefix);
395 [ # # # # ]: 0 : bf_list_foreach (&group->sets, set_node) {
396 : : const struct bf_set *set = bf_list_node_get_data(set_node);
397 : :
398 [ # # ]: 0 : if (bf_list_is_tail(&group->sets, set_node))
399 : 0 : bf_dump_prefix_last(prefix);
400 [ # # # # ]: 0 : DUMP(prefix, "bit %lu: bf_set '%s' (%lu element(s))", i,
401 : : set->name ?: "<anonymous>", bf_hashset_size(&set->elems));
402 [ # # ]: 0 : ++i;
403 : : }
404 : 0 : bf_dump_prefix_pop(prefix);
405 : : }
406 : 0 : bf_dump_prefix_pop(prefix);
407 : :
408 [ # # ]: 0 : DUMP(bf_dump_prefix_last(prefix), "runtime: <anonymous>");
409 : 0 : bf_dump_prefix_push(prefix);
410 [ # # ]: 0 : DUMP(bf_dump_prefix_last(prefix), "ops: %p", program->runtime.ops);
411 : 0 : bf_dump_prefix_pop(prefix);
412 : :
413 : 0 : bf_dump_prefix_pop(prefix);
414 : 0 : }
415 : :
416 : 25471 : static void _bf_codegen_fixup_insn(struct bpf_insn *insn,
417 : : enum bf_fixup_insn type, int32_t value)
418 : : {
419 [ + + - ]: 25471 : switch (type) {
420 : 4953 : case BF_FIXUP_INSN_OFF:
421 : : assert(!insn->off);
422 : : assert(value < SHRT_MAX);
423 : 4953 : insn->off = (int16_t)value;
424 : 4953 : break;
425 : 20518 : case BF_FIXUP_INSN_IMM:
426 : : assert(!insn->imm);
427 : 20518 : insn->imm = value;
428 : 20518 : break;
429 : 0 : default:
430 [ # # ]: 0 : bf_abort(
431 : : "unsupported fixup instruction type, this should not happen: %d",
432 : : type);
433 : : break;
434 : : }
435 : 25471 : }
436 : :
437 : 7666 : static int _bf_codegen_fixup(struct bf_codegen *program,
438 : : enum bf_fixup_type type)
439 : : {
440 : : assert(program);
441 : : assert(type >= 0 && type < _BF_FIXUP_TYPE_MAX);
442 : :
443 [ + - + + : 161440 : bf_list_foreach (&program->fixups, fixup_node) {
+ + ]
444 : : enum bf_fixup_insn insn_type = _BF_FIXUP_INSN_MAX;
445 : : int32_t value;
446 : : size_t offset;
447 : : struct bf_fixup *fixup = bf_list_node_get_data(fixup_node);
448 : : struct bpf_insn *insn;
449 : :
450 [ + + ]: 73054 : if (type != fixup->type)
451 : 47583 : continue;
452 : :
453 : 25471 : insn = bf_vector_get(&program->img, fixup->insn);
454 [ - + ]: 25471 : if (!insn) {
455 [ # # ]: 0 : return bf_err_r(-EINVAL,
456 : : "fixup references invalid instruction index %lu",
457 : : fixup->insn);
458 : : }
459 : :
460 [ + + + + : 25471 : switch (type) {
+ + + - ]
461 : 4953 : case BF_FIXUP_TYPE_JMP_NEXT_RULE:
462 : : insn_type = BF_FIXUP_INSN_OFF;
463 : 4953 : value = (int)(program->img.size - fixup->insn - 1U);
464 : 4953 : break;
465 : 8332 : case BF_FIXUP_TYPE_COUNTERS_MAP_FD:
466 : : insn_type = BF_FIXUP_INSN_IMM;
467 : 8332 : value = program->handle->cmap->fd;
468 : 8332 : break;
469 : 1482 : case BF_FIXUP_TYPE_PRINTER_MAP_FD:
470 : : insn_type = BF_FIXUP_INSN_IMM;
471 : 1482 : value = program->handle->pmap->fd;
472 : 1482 : break;
473 : 44 : case BF_FIXUP_TYPE_LOG_MAP_FD:
474 : : insn_type = BF_FIXUP_INSN_IMM;
475 : 44 : value = program->handle->lmap->fd;
476 : 44 : break;
477 : 4 : case BF_FIXUP_TYPE_STATE_MAP_FD:
478 : : insn_type = BF_FIXUP_INSN_IMM;
479 : 4 : value = program->handle->smap->fd;
480 : 4 : break;
481 : 341 : case BF_FIXUP_TYPE_SET_MAP_FD: {
482 : : const struct bf_set_group *group =
483 : 341 : _bf_codegen_find_set_group(program, fixup->attr.set_ptr);
484 [ + - - + ]: 341 : if (!group || !group->map) {
485 [ # # # # : 0 : return bf_err_r(
# # ]
486 : : -ENOENT, "set map fixup: set '%s' not in any loaded group",
487 : : fixup->attr.set_ptr ?
488 : : (fixup->attr.set_ptr->name ?: "<anonymous>") :
489 : : "(null)");
490 : : }
491 : : insn_type = BF_FIXUP_INSN_IMM;
492 : 341 : value = group->map->fd;
493 : 341 : break;
494 : : }
495 : 10315 : case BF_FIXUP_ELFSTUB_CALL:
496 : : insn_type = BF_FIXUP_INSN_IMM;
497 : 10315 : offset = program->elfstubs_location[fixup->attr.elfstub_id] -
498 : 10315 : fixup->insn - 1;
499 [ - + ]: 10315 : if (offset >= INT_MAX)
500 [ # # ]: 0 : return bf_err_r(-EINVAL, "invalid ELF stub call offset");
501 : 10315 : value = (int32_t)offset;
502 : 10315 : break;
503 : 0 : default:
504 [ # # ]: 0 : bf_abort("unsupported fixup type, this should not happen: %d",
505 : : type);
506 : : break;
507 : : }
508 : :
509 : 25471 : _bf_codegen_fixup_insn(insn, insn_type, value);
510 : 25471 : bf_list_delete(&program->fixups, fixup_node);
511 : : }
512 : :
513 : : return 0;
514 : : }
515 : :
516 : 2982 : static int _bf_codegen_check_proto(struct bf_codegen *program,
517 : : enum bf_matcher_type type,
518 : : uint32_t *checked_layers)
519 : : {
520 : : const struct bf_matcher_meta *meta;
521 : :
522 : : assert(program);
523 : : assert(checked_layers);
524 : :
525 : 2982 : meta = bf_matcher_get_meta(type);
526 [ - + ]: 2982 : if (!meta)
527 [ # # ]: 0 : return bf_err_r(-EINVAL, "missing meta for matcher type %d", type);
528 : :
529 [ + + ]: 2982 : if (*checked_layers & BF_FLAG(meta->layer))
530 : : return 0;
531 : :
532 : 2083 : if (meta->layer == BF_MATCHER_LAYER_2 ||
533 [ + + ]: 2083 : meta->layer == BF_MATCHER_LAYER_3 ||
534 : : meta->layer == BF_MATCHER_LAYER_4) {
535 : 1316 : int r = bf_stub_rule_check_protocol(program, meta);
536 [ + - ]: 1316 : if (r)
537 : : return r;
538 : 1316 : *checked_layers |= BF_FLAG(meta->layer);
539 : : }
540 : :
541 : : return 0;
542 : : }
543 : :
544 : 1733 : static int _bf_codegen_generate_log(struct bf_codegen *program,
545 : : const struct bf_rule *rule)
546 : : {
547 : 1733 : _clean_bf_jmpctx_ struct bf_jmpctx l3_ctx = bf_jmpctx_default();
548 : 1733 : _clean_bf_jmpctx_ struct bf_jmpctx l4_ctx = bf_jmpctx_default();
549 : 1733 : _clean_bf_jmpctx_ struct bf_jmpctx null_ctx = bf_jmpctx_default();
550 : 1733 : _clean_bf_jmpctx_ struct bf_jmpctx rate_ctx = bf_jmpctx_default();
551 : : int r;
552 : :
553 : : assert(program);
554 : : assert(rule);
555 : :
556 [ + + ]: 1733 : if (!rule->log)
557 : : return 0;
558 : :
559 [ + + ]: 56 : if (rule->log == BF_FLAG(BF_LOG_OPT_5_TUPLE)) {
560 : : /* A 5-tuple is only complete for IPv4/IPv6 packets using TCP/UDP.
561 : : * Skip only the log action for other packets, leaving the rule's
562 : : * remaining actions and verdict unchanged. */
563 [ + - ]: 3 : EMIT(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_7, htobe16(ETH_P_IP), 2));
564 [ + - ]: 3 : EMIT(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_7, htobe16(ETH_P_IPV6), 1));
565 [ + - ]: 3 : l3_ctx = bf_jmpctx_get(program, BPF_JMP_A(0));
566 : :
567 [ + - ]: 3 : EMIT(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_8, IPPROTO_TCP, 2));
568 [ + - ]: 3 : EMIT(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_8, IPPROTO_UDP, 1));
569 [ + - ]: 3 : l4_ctx = bf_jmpctx_get(program, BPF_JMP_A(0));
570 : : }
571 : :
572 [ + + ]: 56 : if (rule->log_rate_ns) {
573 : 7 : const struct bpf_insn rate_insn[2] = {
574 : 7 : BPF_LD_IMM64(BPF_REG_1, rule->log_rate_ns),
575 : : };
576 : :
577 : : /* Rate-limited log: check last_log_ts in the state map before logging.
578 : : *
579 : : * R9 (callee-saved) holds the pointer to this rule's state entry
580 : : * across the bpf_ktime_get_ns() call. */
581 [ + - ]: 7 : EMIT(program, BPF_LDX_MEM(BPF_DW, BPF_REG_9, BPF_REG_10,
582 : : BF_PROG_CTX_OFF(state_map)));
583 : :
584 : : /* Skip the log if state_map is NULL. This shouldn't happen at runtime,
585 : : * but the verifier requires the NULL check. */
586 : 7 : null_ctx =
587 [ + - ]: 7 : bf_jmpctx_get(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_9, 0, 0));
588 : :
589 [ + + ]: 7 : if (rule->index > 0) {
590 [ + - ]: 5 : EMIT(program, BPF_ALU64_IMM(BPF_ADD, BPF_REG_9,
591 : : (int)(rule->index *
592 : : sizeof(struct bf_rule_state))));
593 : : }
594 : :
595 [ + - ]: 7 : EMIT(program, BPF_EMIT_CALL(BPF_FUNC_ktime_get_ns));
596 : :
597 [ + - ]: 7 : EMIT(program, BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_9, 0));
598 [ + - ]: 7 : EMIT(program, BPF_MOV64_REG(BPF_REG_2, BPF_REG_0));
599 [ + - ]: 7 : EMIT(program, BPF_ALU64_REG(BPF_SUB, BPF_REG_2, BPF_REG_1));
600 : :
601 : : // Load log_rate_ns as a 64-bit immediate into R1.
602 [ + - ]: 7 : EMIT(program, rate_insn[0]);
603 [ + - ]: 7 : EMIT(program, rate_insn[1]);
604 : :
605 : : // Skip the log while delta is smaller than log_rate_ns.
606 [ + - ]: 7 : rate_ctx = bf_jmpctx_get(program,
607 : : BPF_JMP_REG(BPF_JLT, BPF_REG_2, BPF_REG_1, 0));
608 : :
609 [ + - ]: 7 : EMIT(program, BPF_STX_MEM(BPF_DW, BPF_REG_9, BPF_REG_0, 0));
610 : : }
611 : :
612 : 56 : r = program->runtime.ops->gen_inline_log(program, rule);
613 [ + - ]: 56 : if (r)
614 : : return r;
615 : :
616 [ + + ]: 56 : if (bf_ctx_is_verbose(BF_VERBOSE_BPF)) {
617 : 2 : _clean_bf_jmpctx_ struct bf_jmpctx _ =
618 [ + - ]: 2 : bf_jmpctx_get(program, BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 0));
619 : :
620 [ + - + - : 6 : EMIT_PRINT(program, "failed to reserve a log entry in the ring buffer");
+ - + - ]
621 : : }
622 : :
623 : : return 0;
624 : : }
625 : :
626 : : /**
627 : : * @brief Check whether a matcher needs no bytecode.
628 : : *
629 : : * A matcher needs no bytecode if it matches every packet the rule applies
630 : : * to. The protocol checks derived from the matcher are still generated.
631 : : *
632 : : * @param program Program to generate the matcher for. Can't be NULL.
633 : : * @param matcher Matcher to check. Can't be NULL.
634 : : * @return True if no bytecode is needed for the matcher, false otherwise.
635 : : */
636 : 2933 : static bool _bf_codegen_matcher_is_noop(const struct bf_codegen *program,
637 : : const struct bf_matcher *matcher)
638 : : {
639 : : assert(program);
640 : : assert(matcher);
641 : :
642 [ + + ]: 2933 : if (bf_matcher_get_type(matcher) == BF_MATCHER_SET) {
643 : : const struct bf_set *set =
644 : 353 : bf_chain_get_set_for_matcher(program->runtime.chain, matcher);
645 : :
646 : : /* ... not in {} will match every packet, so no need to generate the
647 : : * bytecode for it. */
648 [ + + ]: 353 : if (bf_set_is_empty(set) && bf_matcher_get_negate(matcher))
649 : : return true;
650 : : }
651 : :
652 : : return false;
653 : : }
654 : :
655 : 1751 : static int _bf_codegen_generate_rule(struct bf_codegen *program,
656 : : struct bf_rule *rule)
657 : : {
658 : 1751 : uint32_t checked_layers = 0;
659 : : int ret_code;
660 : : int r = 0;
661 : :
662 : : assert(program);
663 : : assert(rule);
664 : : assert(program->runtime.ops->gen_inline_matcher);
665 : : assert(program->runtime.ops->gen_inline_log);
666 : :
667 [ + + ]: 1751 : if (rule->disabled)
668 : : return 0;
669 : :
670 [ + - + + : 9332 : bf_list_foreach (&rule->matchers, matcher_node) {
+ + ]
671 : : struct bf_matcher *matcher = bf_list_node_get_data(matcher_node);
672 : :
673 [ + + ]: 2933 : if (bf_matcher_get_type(matcher) == BF_MATCHER_SET) {
674 : : const struct bf_set *set =
675 : 353 : bf_chain_get_set_for_matcher(program->runtime.chain, matcher);
676 : :
677 [ - + ]: 353 : if (!set) {
678 [ # # ]: 0 : return bf_err_r(-ENOENT, "rule %u references non-existent set",
679 : : rule->index);
680 : : }
681 : :
682 [ + + + - ]: 755 : for (size_t i = 0; i < set->n_comps && !r; ++i) {
683 : 402 : r = _bf_codegen_check_proto(program, set->key[i],
684 : : &checked_layers);
685 : : }
686 : : } else {
687 : 2580 : r = _bf_codegen_check_proto(program, bf_matcher_get_type(matcher),
688 : : &checked_layers);
689 : : }
690 : :
691 [ + - ]: 2933 : if (r)
692 : : return r;
693 : : }
694 : :
695 [ + - + + : 9332 : bf_list_foreach (&rule->matchers, matcher_node) {
+ + ]
696 : : struct bf_matcher *matcher = bf_list_node_get_data(matcher_node);
697 : :
698 [ + + ]: 2933 : if (_bf_codegen_matcher_is_noop(program, matcher))
699 : 12 : continue;
700 : :
701 : 2921 : r = program->runtime.ops->gen_inline_matcher(program, matcher);
702 [ + - ]: 2921 : if (r)
703 : : return r;
704 : : }
705 : :
706 [ + + ]: 1733 : if (bf_rule_mark_is_set(rule)) {
707 [ - + ]: 10 : if (!program->runtime.ops->gen_inline_set_mark) {
708 [ # # ]: 0 : return bf_err_r(-ENOTSUP, "set mark is not supported by %s",
709 : : program->runtime.chain->name);
710 : : }
711 : :
712 : 10 : r = program->runtime.ops->gen_inline_set_mark(program,
713 : : bf_rule_mark_get(rule));
714 [ - + ]: 10 : if (r) {
715 [ # # ]: 0 : return bf_err_r(r,
716 : : "failed to generate bytecode to set mark for '%s'",
717 : : program->runtime.chain->name);
718 : : }
719 : : }
720 : :
721 : 1733 : r = _bf_codegen_generate_log(program, rule);
722 [ + - ]: 1733 : if (r)
723 : : return r;
724 : :
725 [ + + ]: 1733 : if (rule->has_counters) {
726 [ + - ]: 1668 : EMIT(program, BPF_MOV64_REG(BPF_REG_1, BPF_REG_10));
727 [ + - ]: 1668 : EMIT(program, BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, BF_PROG_CTX_OFF(arg)));
728 [ + - + - ]: 3336 : EMIT_LOAD_COUNTERS_FD_FIXUP(program, BPF_REG_2);
729 [ + - ]: 1668 : EMIT(program, BPF_MOV32_IMM(BPF_REG_3, rule->index));
730 [ + - ]: 1668 : EMIT_FIXUP_ELFSTUB(program, BF_ELFSTUB_UPDATE_COUNTERS);
731 : : }
732 : :
733 [ + + - + ]: 1733 : switch (rule->verdict) {
734 : 1681 : case BF_VERDICT_ACCEPT:
735 : : case BF_VERDICT_DROP:
736 : : case BF_VERDICT_NEXT:
737 : 1681 : r = program->runtime.ops->get_verdict(rule->verdict, &ret_code);
738 [ + - ]: 1681 : if (r)
739 : : return r;
740 [ + - ]: 1681 : EMIT(program, BPF_MOV64_IMM(BPF_REG_0, ret_code));
741 [ + - ]: 1681 : EMIT(program, BPF_EXIT_INSN());
742 : : break;
743 : 12 : case BF_VERDICT_REDIRECT:
744 [ + + ]: 12 : if (!program->runtime.ops->gen_inline_redirect) {
745 [ + - ]: 2 : return bf_err_r(-ENOTSUP, "redirect is not supported by %s hook",
746 : : bf_hook_to_str(program->runtime.chain->hook));
747 : : }
748 : 10 : r = program->runtime.ops->gen_inline_redirect(
749 : : program, rule->redirect_ifindex, rule->redirect_dir);
750 [ + + ]: 10 : if (r)
751 : : return r;
752 : : break;
753 : : case BF_VERDICT_CONTINUE:
754 : : // Fall through to next rule or default chain policy.
755 : : break;
756 : 0 : default:
757 : : // The verdict comes from the caller's chain: it can be out of range.
758 [ # # ]: 0 : return bf_err_r(-EINVAL, "unsupported verdict %d", rule->verdict);
759 : : }
760 : :
761 : 1730 : r = _bf_codegen_fixup(program, BF_FIXUP_TYPE_JMP_NEXT_RULE);
762 [ - + ]: 1730 : if (r)
763 [ # # ]: 0 : return bf_err_r(r, "failed to generate next rule fixups");
764 : :
765 : : return 0;
766 : : }
767 : :
768 : 1472 : static int _bf_codegen_generate_elfstubs(struct bf_codegen *program)
769 : : {
770 : : const struct bf_elfstub *elfstub;
771 : : size_t start_at;
772 : : int r;
773 : :
774 : : assert(program);
775 : :
776 [ + - + + : 43972 : bf_list_foreach (&program->fixups, fixup_node) {
+ + ]
777 : : struct bf_fixup *fixup = bf_list_node_get_data(fixup_node);
778 : 20514 : size_t off = program->img.size;
779 : :
780 [ + + ]: 20514 : if (fixup->type != BF_FIXUP_ELFSTUB_CALL)
781 : 10199 : continue;
782 : :
783 : : // Only generate each ELF stub once
784 [ + + ]: 10315 : if (program->elfstubs_location[fixup->attr.elfstub_id])
785 : 6872 : continue;
786 : :
787 [ - + ]: 3443 : bf_dbg("generate ELF stub for ID %d", fixup->attr.elfstub_id);
788 : :
789 : 3443 : elfstub = bf_ctx_get_elfstub(fixup->attr.elfstub_id);
790 [ - + ]: 3443 : if (!elfstub) {
791 [ # # ]: 0 : return bf_err_r(-ENOENT, "no ELF stub found for ID %d",
792 : : fixup->attr.elfstub_id);
793 : : }
794 : :
795 : 3443 : start_at = program->img.size;
796 : :
797 [ + + ]: 124865 : for (size_t i = 0; i < elfstub->ninsns; ++i) {
798 : 121422 : r = bf_codegen_emit(program, elfstub->insns[i]);
799 [ - + ]: 121422 : if (r)
800 [ # # ]: 0 : return bf_err_r(r, "failed to insert ELF stub instruction");
801 : : }
802 : :
803 [ + + - + : 9830 : bf_list_foreach (&elfstub->strs, pstr_node) {
+ + ]
804 : 1472 : _free_bf_fixup_ struct bf_fixup *fixup = NULL;
805 : : struct bf_printk_str *pstr = bf_list_node_get_data(pstr_node);
806 : 1472 : size_t insn_idx = start_at + pstr->insn_idx;
807 : : const struct bf_printer_msg *msg =
808 : 1472 : bf_printer_add_msg(program->printer, pstr->str);
809 : 1472 : struct bpf_insn ld_insn[2] = {
810 : : BPF_LD_MAP_FD(BPF_REG_1, 0),
811 : : };
812 : :
813 : 1472 : ld_insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
814 : 1472 : ld_insn[1].imm = (int)bf_printer_msg_offset(msg);
815 : :
816 : 1472 : r = bf_vector_set(&program->img, insn_idx, &ld_insn[0]);
817 [ - + ]: 1472 : if (r) {
818 [ # # ]: 0 : return bf_err_r(
819 : : r, "failed to set ELF stub instruction at index %lu",
820 : : insn_idx);
821 : : }
822 : 1472 : r = bf_vector_set(&program->img, insn_idx + 1, &ld_insn[1]);
823 [ - + ]: 1472 : if (r) {
824 [ # # ]: 0 : return bf_err_r(
825 : : r, "failed to set ELF stub instruction at index %lu",
826 : : insn_idx + 1);
827 : : }
828 : :
829 : 1472 : r = bf_fixup_new(&fixup, BF_FIXUP_TYPE_PRINTER_MAP_FD, insn_idx,
830 : : NULL);
831 [ + - ]: 1472 : if (r)
832 : : return r;
833 : :
834 : 1472 : r = bf_list_add_tail(&program->fixups, fixup);
835 [ + - ]: 1472 : if (r)
836 : : return r;
837 : :
838 : 1472 : TAKE_PTR(fixup);
839 : : }
840 : :
841 : 3443 : program->elfstubs_location[fixup->attr.elfstub_id] = off;
842 : : }
843 : :
844 : : return 0;
845 : : }
846 : :
847 : 4688 : int bf_codegen_emit_kfunc_call(struct bf_codegen *program, const char *name)
848 : : {
849 : : int r;
850 : :
851 : : assert(program);
852 : : assert(name);
853 : :
854 : 4688 : r = bf_btf_get_id(name);
855 [ + - ]: 4688 : if (r < 0)
856 : : return r;
857 : :
858 : 4688 : EMIT(program, ((struct bpf_insn) {.code = BPF_JMP | BPF_CALL,
859 : : .dst_reg = 0,
860 : : .src_reg = BPF_PSEUDO_KFUNC_CALL,
861 : : .off = 0,
862 : : .imm = r}));
863 : :
864 : : return 0;
865 : : }
866 : :
867 : 13701 : int bf_codegen_emit_fixup(struct bf_codegen *program, enum bf_fixup_type type,
868 : : struct bpf_insn insn, const union bf_fixup_attr *attr)
869 : : {
870 : 27402 : _free_bf_fixup_ struct bf_fixup *fixup = NULL;
871 : : int r;
872 : :
873 : : assert(program);
874 : :
875 [ + - ]: 13701 : EMIT(program, insn);
876 : :
877 : 13701 : r = bf_fixup_new(&fixup, type, program->img.size - 1, attr);
878 [ + - ]: 13701 : if (r)
879 : : return r;
880 : :
881 : 13701 : r = bf_list_add_tail(&program->fixups, fixup);
882 [ + - ]: 13701 : if (r)
883 : : return r;
884 : :
885 : 13701 : TAKE_PTR(fixup);
886 : :
887 : 13701 : return 0;
888 : : }
889 : :
890 : 10330 : int bf_codegen_emit_fixup_elfstub(struct bf_codegen *program,
891 : : enum bf_elfstub_id id)
892 : : {
893 : 20660 : _free_bf_fixup_ struct bf_fixup *fixup = NULL;
894 : : int r;
895 : :
896 : : assert(program);
897 : :
898 [ + - ]: 10330 : EMIT(program, BPF_CALL_REL(0));
899 : :
900 : 10330 : r = bf_fixup_new(&fixup, BF_FIXUP_ELFSTUB_CALL, program->img.size - 1,
901 : : NULL);
902 [ + - ]: 10330 : if (r)
903 : : return r;
904 : :
905 : 10330 : fixup->attr.elfstub_id = id;
906 : :
907 : 10330 : r = bf_list_add_tail(&program->fixups, fixup);
908 [ + - ]: 10330 : if (r)
909 : : return r;
910 : :
911 : 10330 : TAKE_PTR(fixup);
912 : :
913 : 10330 : return 0;
914 : : }
915 : :
916 : 1475 : int bf_codegen_generate(struct bf_codegen *program)
917 : : {
918 : 1475 : const struct bf_chain *chain = program->runtime.chain;
919 : : int ret_code;
920 : : int r;
921 : :
922 : 1475 : r = _bf_codegen_build_set_groups(program);
923 [ - + ]: 1475 : if (r)
924 [ # # ]: 0 : return bf_err_r(r, "failed to build set groups");
925 : :
926 : : // Save the program's argument into the context.
927 [ + - ]: 1475 : EMIT(program,
928 : : BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_1, BF_PROG_CTX_OFF(arg)));
929 : :
930 : : // Reset the protocol ID registers
931 [ + - ]: 1475 : EMIT(program, BPF_MOV64_IMM(BPF_REG_7, 0));
932 [ + - ]: 1475 : EMIT(program, BPF_MOV64_IMM(BPF_REG_8, 0));
933 : :
934 : : // If at least one rule logs the matched packets, populate ctx->log_map
935 [ + + ]: 1475 : if (program->runtime.chain->flags & BF_FLAG(BF_CHAIN_LOG)) {
936 [ + - + - ]: 88 : EMIT_LOAD_LOG_FD_FIXUP(program, BPF_REG_2);
937 [ + - ]: 44 : EMIT(program, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2,
938 : : BF_PROG_CTX_OFF(log_map)));
939 : : }
940 : :
941 : : // Zeroing IPv6 extension headers
942 [ + + ]: 1475 : if (program->runtime.chain->flags & BF_FLAG(BF_CHAIN_STORE_NEXTHDR)) {
943 [ + - ]: 30 : EMIT(program, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7,
944 : : BF_PROG_CTX_OFF(ipv6_eh)));
945 : : }
946 : :
947 : 1475 : r = program->runtime.ops->gen_inline_prologue(program);
948 [ + - ]: 1475 : if (r)
949 : : return r;
950 : :
951 : : // Populate ctx->state_map with the base pointer from the single-entry
952 : : // state map. The key (0) is written to scratch[0..3] temporarily.
953 : : // Placed after gen_inline_prologue so R1-R5 are free: the helper call
954 : : // does not need to be followed by a ctx restore.
955 [ + + ]: 1475 : if (program->runtime.chain->flags & BF_FLAG(BF_CHAIN_LOG_RATELIMIT)) {
956 [ + - ]: 4 : EMIT(program, BPF_ST_MEM(BPF_W, BPF_REG_10, BF_PROG_SCR_OFF(0), 0));
957 [ + - + - ]: 8 : EMIT_LOAD_STATE_FD_FIXUP(program, BPF_REG_1);
958 [ + - ]: 4 : EMIT(program, BPF_MOV64_REG(BPF_REG_2, BPF_REG_10));
959 [ + - ]: 4 : EMIT(program, BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, BF_PROG_SCR_OFF(0)));
960 [ + - ]: 4 : EMIT(program, BPF_EMIT_CALL(BPF_FUNC_map_lookup_elem));
961 [ + - ]: 4 : EMIT(program, BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_0,
962 : : BF_PROG_CTX_OFF(state_map)));
963 : : }
964 : :
965 [ + + + + : 6446 : bf_list_foreach (&chain->rules, rule_node) {
+ + ]
966 : 1751 : r = _bf_codegen_generate_rule(program,
967 : : bf_list_node_get_data(rule_node));
968 [ + + ]: 1751 : if (r)
969 : : return r;
970 : : }
971 : :
972 : 1472 : r = program->runtime.ops->gen_inline_epilogue(program);
973 [ + - ]: 1472 : if (r)
974 : : return r;
975 : :
976 : : // Call the update counters function
977 : : /// @todo Allow chains to have no counters at all.
978 [ + - ]: 1472 : EMIT(program, BPF_MOV64_REG(BPF_REG_1, BPF_REG_10));
979 [ + - ]: 1472 : EMIT(program, BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, BF_PROG_CTX_OFF(arg)));
980 [ + - + - ]: 2944 : EMIT_LOAD_COUNTERS_FD_FIXUP(program, BPF_REG_2);
981 [ + - ]: 1472 : EMIT(program,
982 : : BPF_MOV32_IMM(BPF_REG_3, bf_codegen_chain_counter_idx(program)));
983 [ + - ]: 1472 : EMIT_FIXUP_ELFSTUB(program, BF_ELFSTUB_UPDATE_COUNTERS);
984 : :
985 : 1472 : r = program->runtime.ops->get_verdict(chain->policy, &ret_code);
986 [ + - ]: 1472 : if (r)
987 : : return r;
988 [ + - ]: 1472 : EMIT(program, BPF_MOV64_IMM(BPF_REG_0, ret_code));
989 [ + - ]: 1472 : EMIT(program, BPF_EXIT_INSN());
990 : :
991 : 1472 : r = _bf_codegen_generate_elfstubs(program);
992 [ + - ]: 1472 : if (r)
993 : : return r;
994 : :
995 : 1472 : r = _bf_codegen_fixup(program, BF_FIXUP_ELFSTUB_CALL);
996 [ - + ]: 1472 : if (r)
997 [ # # ]: 0 : return bf_err_r(r, "failed to generate ELF stub call fixups");
998 : :
999 : : return 0;
1000 : : }
1001 : :
1002 : 1472 : static int _bf_codegen_load_printer_map(struct bf_codegen *program)
1003 : : {
1004 : 1472 : _cleanup_free_ void *pstr = NULL;
1005 : : size_t pstr_len;
1006 : 1472 : uint32_t key = 0;
1007 : : int r;
1008 : :
1009 : : assert(program);
1010 : :
1011 : 1472 : r = bf_printer_assemble(program->printer, &pstr, &pstr_len);
1012 [ - + ]: 1472 : if (r)
1013 [ # # ]: 0 : return bf_err_r(r, "failed to assemble printer map string");
1014 : :
1015 : 1472 : r = bf_map_new(&program->handle->pmap, _BF_PRINTER_MAP_NAME,
1016 : : BF_MAP_TYPE_PRINTER, sizeof(uint32_t), pstr_len, 1);
1017 [ - + ]: 1472 : if (r)
1018 [ # # ]: 0 : return bf_err_r(r, "failed to create the printer bf_map object");
1019 : :
1020 : 1472 : r = bf_map_set_elem(program->handle->pmap, &key, pstr);
1021 [ - + ]: 1472 : if (r)
1022 [ # # ]: 0 : return bf_err_r(r, "failed to set print map elem");
1023 : :
1024 : 1472 : r = _bf_codegen_fixup(program, BF_FIXUP_TYPE_PRINTER_MAP_FD);
1025 [ - + ]: 1472 : if (r)
1026 [ # # ]: 0 : return bf_err_r(r, "failed to fixup printer map FD");
1027 : :
1028 : : return 0;
1029 : : }
1030 : :
1031 : 1472 : static int _bf_codegen_load_counters_map(struct bf_codegen *program)
1032 : : {
1033 : : int r;
1034 : :
1035 : : assert(program);
1036 : :
1037 : 1472 : r = bf_map_new(&program->handle->cmap, _BF_COUNTER_MAP_NAME,
1038 : : BF_MAP_TYPE_COUNTERS, sizeof(uint32_t),
1039 : : sizeof(struct bf_counter),
1040 : 1472 : bf_codegen_parser_drop_counter_idx(program) + 1);
1041 [ - + ]: 1472 : if (r)
1042 [ # # ]: 0 : return bf_err_r(r, "failed to create the counters bf_map object");
1043 : :
1044 : 1472 : r = _bf_codegen_fixup(program, BF_FIXUP_TYPE_COUNTERS_MAP_FD);
1045 [ - + ]: 1472 : if (r)
1046 [ # # ]: 0 : return bf_err_r(r, "failed to fixup counters map FD");
1047 : :
1048 : : return 0;
1049 : : }
1050 : :
1051 : 1472 : static int _bf_codegen_load_log_map(struct bf_codegen *program)
1052 : : {
1053 : : int r;
1054 : :
1055 : : assert(program);
1056 : :
1057 : : // Do not create a log map if it's unused in the chain
1058 [ + + ]: 1472 : if (!(program->runtime.chain->flags & BF_FLAG(BF_CHAIN_LOG)))
1059 : : return 0;
1060 : :
1061 : : // The handle might already reuse the log map of the program it replaces
1062 [ + + ]: 44 : if (!program->handle->lmap) {
1063 : 42 : r = bf_map_new(&program->handle->lmap, _BF_LOG_MAP_NAME,
1064 : : BF_MAP_TYPE_LOG, 0, 0, _BF_LOG_MAP_SIZE);
1065 [ - + ]: 42 : if (r)
1066 [ # # ]: 0 : return bf_err_r(r, "failed to create the log bf_map object");
1067 : : }
1068 : :
1069 : 44 : r = _bf_codegen_fixup(program, BF_FIXUP_TYPE_LOG_MAP_FD);
1070 [ - + ]: 44 : if (r)
1071 [ # # ]: 0 : return bf_err_r(r, "failed to fixup log map FD");
1072 : :
1073 : : return 0;
1074 : : }
1075 : :
1076 : 1472 : static int _bf_codegen_load_state_map(struct bf_codegen *program)
1077 : : {
1078 : : size_t n_rules;
1079 : : int r;
1080 : :
1081 : : assert(program);
1082 : :
1083 [ + + ]: 1472 : if (!(program->runtime.chain->flags & BF_FLAG(BF_CHAIN_LOG_RATELIMIT)))
1084 : : return 0;
1085 : :
1086 : : n_rules = bf_list_size(&program->runtime.chain->rules);
1087 [ + - ]: 4 : if (n_rules == 0)
1088 : : return 0;
1089 : :
1090 : 4 : r = bf_map_new(&program->handle->smap, _BF_STATE_MAP_NAME,
1091 : : BF_MAP_TYPE_STATE, sizeof(uint32_t),
1092 : 4 : n_rules * sizeof(struct bf_rule_state), 1);
1093 [ - + ]: 4 : if (r)
1094 [ # # ]: 0 : return bf_err_r(r, "failed to create the state bf_map object");
1095 : :
1096 : 4 : r = _bf_codegen_fixup(program, BF_FIXUP_TYPE_STATE_MAP_FD);
1097 [ - + ]: 4 : if (r)
1098 [ # # ]: 0 : return bf_err_r(r, "failed to fixup state map FD");
1099 : :
1100 : : return 0;
1101 : : }
1102 : :
1103 : 763 : static uint64_t _bf_dedup_hash(const void *data, void *ctx)
1104 : : {
1105 : 763 : return bf_fnv1a(data, *(const size_t *)ctx, bf_fnv1a_init());
1106 : : }
1107 : :
1108 : 43 : static bool _bf_dedup_equal(const void *lhs, const void *rhs, void *ctx)
1109 : : {
1110 : 43 : return memcmp(lhs, rhs, *(const size_t *)ctx) == 0;
1111 : : }
1112 : :
1113 : : /**
1114 : : * @brief Load set maps, one BPF map per `bf_set_group`.
1115 : : *
1116 : : * Hash-keyed sets that share the same key format have already been
1117 : : * grouped by `_bf_codegen_build_set_groups()`; LPM trie sets each occupy
1118 : : * their own single-set group. Each group collapses to one BPF map whose
1119 : : * value is a bitmask: bit `i` of byte `i / CHAR_BIT` identifies the `i`-th
1120 : : * set in the group.
1121 : : *
1122 : : * Per-group keys and bitmask values are prepared in user space so a single
1123 : : * `bf_bpf_map_update_batch()` call populates the map on the kernel side.
1124 : : *
1125 : : * The map is created with room for `max(bf_set.min_size, element count)`
1126 : : * entries for each set in the group: a set that outgrows its `min_size`
1127 : : * grows the map on its own, it never borrows the room reserved for another
1128 : : * set of the group. Shared elements are stored once but counted once per
1129 : : * set, so the map over-reserves when grouped sets overlap; this is the cost
1130 : : * of keeping per-set reservations independent.
1131 : : * For each group, we calculate:
1132 : : * - `n_total_elems`: sum of `set.n_elems` for each sets of a group. Will count
1133 : : * duplicates if any.
1134 : : * - `n_unique_elems`: same as `n_total_elems`, but doesn't count duplicate
1135 : : * elements.
1136 : : * - `n_map_elems`: number of elements that we should have room for in the map,
1137 : : * sum of `max(set.min_size, set.n_elems)` for each set in the group.
1138 : : *
1139 : : * Empty sets are not part of any group (see `_bf_codegen_build_set_groups()`),
1140 : : * so they get no map whatever their `min_size`: their reservation only takes
1141 : : * effect once they become non-empty and the program is regenerated.
1142 : : *
1143 : : * Group ownership of the created maps is transferred to `handle->sets`;
1144 : : * the `bf_set_group::map` pointer is a non-owning back-reference used by
1145 : : * `_bf_codegen_fixup()` when resolving `BF_FIXUP_TYPE_SET_MAP_FD` fixups.
1146 : : */
1147 : 1472 : static int _bf_codegen_load_sets_maps(struct bf_codegen *new_prog)
1148 : : {
1149 : : char name[BPF_OBJ_NAME_LEN];
1150 : : size_t map_idx = 0;
1151 : : int r;
1152 : :
1153 : : assert(new_prog);
1154 : :
1155 [ + + + + : 3672 : bf_list_foreach (&new_prog->set_groups, group_node) {
+ + ]
1156 : : struct bf_set_group *group = bf_list_node_get_data(group_node);
1157 : : const struct bf_set *key_set =
1158 : : bf_list_node_get_data(bf_list_get_head(&group->sets));
1159 : : size_t n_sets = bf_list_size(&group->sets);
1160 : : size_t i = 0;
1161 : : _cleanup_free_ uint8_t *keys = NULL;
1162 : 364 : size_t key_size = key_set->elem_size;
1163 : : _cleanup_free_ uint8_t *values = NULL;
1164 : 364 : size_t value_size = (n_sets + CHAR_BIT - 1) / CHAR_BIT;
1165 : : const bf_hashset_ops dedup_ops = {
1166 : : .hash = _bf_dedup_hash,
1167 : : .equal = _bf_dedup_equal,
1168 : : // The dedup hashset borrows elements from `bf_set`s.
1169 : : .free = NULL,
1170 : : };
1171 : 364 : _clean_bf_hashset_ bf_hashset unique_elements =
1172 : : bf_hashset_default(&dedup_ops, &key_size);
1173 : : size_t n_total_elems = 0;
1174 : : size_t n_unique_elems;
1175 : : size_t n_map_elems = 0;
1176 : 0 : _free_bf_map_ struct bf_map *new_map = NULL;
1177 : : struct bf_map *map_ref;
1178 : :
1179 : : /* Upper-bound the set capacity to avoid incremental rehashing, and
1180 : : * size the BPF map so every set is guaranteed room for
1181 : : * max(min_size, element count) entries, independently of the other
1182 : : * sets in the group. */
1183 [ + + ]: 784 : bf_list_foreach (&group->sets, set_node) {
1184 : : const struct bf_set *set = bf_list_node_get_data(set_node);
1185 : :
1186 : 392 : n_total_elems += bf_hashset_size(&set->elems);
1187 [ + + ]: 392 : n_map_elems += bf_max(set->min_size, bf_hashset_size(&set->elems));
1188 : : }
1189 : :
1190 : 364 : r = bf_hashset_reserve(&unique_elements, n_total_elems);
1191 [ - + ]: 364 : if (r)
1192 [ # # ]: 0 : return bf_err_r(r, "failed to reserve dedup hashset capacity");
1193 : :
1194 : : // Find all unique elements across all sets in this group.
1195 [ + - + + : 1512 : bf_list_foreach (&group->sets, set_node) {
+ + ]
1196 : : const struct bf_set *set = bf_list_node_get_data(set_node);
1197 : :
1198 [ + - + + : 2310 : bf_hashset_foreach (&set->elems, elem) {
+ + ]
1199 : 763 : void *to_add = elem->data;
1200 : 763 : r = bf_hashset_add(&unique_elements, &to_add);
1201 [ - + ]: 763 : if (r && r != -EEXIST)
1202 [ # # ]: 0 : return bf_err_r(r, "failed to dedup element");
1203 : : }
1204 : : }
1205 : 364 : n_unique_elems = bf_hashset_size(&unique_elements);
1206 : :
1207 : : // Compute bf_map keys and values for batch insertion.
1208 : 364 : keys = calloc(n_unique_elems, key_size);
1209 [ - + ]: 364 : if (!keys)
1210 [ # # ]: 0 : return bf_err_r(-ENOMEM, "failed to allocate map keys");
1211 : :
1212 : 364 : values = calloc(n_unique_elems, value_size);
1213 [ - + ]: 364 : if (!values)
1214 [ # # ]: 0 : return bf_err_r(-ENOMEM, "failed to allocate map values");
1215 : :
1216 [ + - + + ]: 1868 : bf_hashset_foreach (&unique_elements, hentry) {
1217 : : size_t bit_idx = 0;
1218 : :
1219 : : // Compute the key.
1220 : 752 : memcpy(keys + (i * key_size), hentry->data, key_size);
1221 : :
1222 : : // Compute the value (bitmask).
1223 [ + - + + ]: 2532 : bf_list_foreach (&group->sets, set_node) {
1224 : : const struct bf_set *set = bf_list_node_get_data(set_node);
1225 : :
1226 [ + + ]: 890 : if (bf_hashset_contains(&set->elems, hentry->data)) {
1227 : 763 : values[(i * value_size) + (bit_idx / CHAR_BIT)] |=
1228 : 763 : (uint8_t)(1U << (bit_idx % CHAR_BIT));
1229 : : }
1230 [ + + ]: 890 : ++bit_idx;
1231 : : }
1232 [ + + ]: 752 : ++i;
1233 : : }
1234 : :
1235 : : // Create the BPF map from the computed keys and values.
1236 : 364 : (void)snprintf(name, BPF_OBJ_NAME_LEN, _BF_SET_MAP_PREFIX "%04x",
1237 : 364 : (uint16_t)map_idx++);
1238 : :
1239 : 364 : r = bf_map_new_from_set(&new_map, name, key_set, n_map_elems,
1240 : : value_size);
1241 [ + - ]: 364 : if (r)
1242 : : return r;
1243 : :
1244 : 364 : r = bf_bpf_map_update_batch(new_map->fd, keys, values, n_unique_elems,
1245 : : BPF_ANY);
1246 [ - + ]: 364 : if (r)
1247 [ # # ]: 0 : return bf_err_r(r, "failed to add set elements to the map");
1248 : :
1249 : 364 : map_ref = new_map;
1250 : 364 : r = bf_list_push(&new_prog->handle->sets, (void **)&new_map);
1251 [ + - ]: 364 : if (r)
1252 : : return r;
1253 : 364 : group->map = map_ref;
1254 : : }
1255 : :
1256 : 1472 : return _bf_codegen_fixup(new_prog, BF_FIXUP_TYPE_SET_MAP_FD);
1257 : : }
1258 : :
1259 : 1472 : int bf_codegen_load(struct bf_codegen *prog)
1260 : : {
1261 : : _cleanup_free_ char *log_buf = NULL;
1262 : 1472 : bool log_enabled = bf_ctx_is_verbose(BF_VERBOSE_DEBUG);
1263 : : int r;
1264 : :
1265 : : assert(prog);
1266 : :
1267 : 1472 : r = _bf_codegen_load_sets_maps(prog);
1268 [ - + ]: 1472 : if (r)
1269 [ # # ]: 0 : return bf_err_r(r, "failed to load the sets map");
1270 : :
1271 : 1472 : r = _bf_codegen_load_counters_map(prog);
1272 [ - + ]: 1472 : if (r)
1273 [ # # ]: 0 : return bf_err_r(r, "failed to load the counter map");
1274 : :
1275 : 1472 : r = _bf_codegen_load_printer_map(prog);
1276 [ - + ]: 1472 : if (r)
1277 [ # # ]: 0 : return bf_err_r(r, "failed to load the printer map");
1278 : :
1279 : 1472 : r = _bf_codegen_load_log_map(prog);
1280 [ - + ]: 1472 : if (r)
1281 [ # # ]: 0 : return bf_err_r(r, "failed to load the log map");
1282 : :
1283 : 1472 : r = _bf_codegen_load_state_map(prog);
1284 [ - + ]: 1472 : if (r)
1285 [ # # ]: 0 : return bf_err_r(r, "failed to load the state map");
1286 : :
1287 [ + - ]: 1472 : if (bf_ctx_is_verbose(BF_VERBOSE_BYTECODE))
1288 : 0 : bf_codegen_dump_bytecode(prog);
1289 : :
1290 : 1472 : retry_load:
1291 [ + + ]: 1472 : if (log_enabled) {
1292 : 2 : log_buf = malloc(_BF_LOG_BUF_SIZE);
1293 [ - + ]: 2 : if (!log_buf) {
1294 [ # # ]: 0 : return bf_err_r(-ENOMEM,
1295 : : "failed to allocate BPF_PROG_LOAD logs buffer");
1296 : : }
1297 : 2 : log_buf[0] = '\0';
1298 : : }
1299 : :
1300 [ + + ]: 2944 : r = bf_bpf_prog_load(prog->handle->prog_name,
1301 : 1472 : bf_hook_to_bpf_prog_type(prog->runtime.chain->hook),
1302 : : prog->img.data, prog->img.size,
1303 : 1472 : bf_hook_to_bpf_attach_type(prog->runtime.chain->hook),
1304 : : log_buf, log_buf ? _BF_LOG_BUF_SIZE : 0,
1305 : 1472 : bf_ctx_token(), &prog->handle->prog_fd);
1306 [ - + ]: 1472 : if (r && !log_enabled) {
1307 : : log_enabled = true;
1308 : 0 : goto retry_load;
1309 : : }
1310 : :
1311 [ - + ]: 1472 : if (r) {
1312 [ # # # # ]: 0 : return bf_err_r(r, "failed to load bf_codegen (%lu insns):\n%s\nerrno:",
1313 : : prog->img.size, log_buf ? log_buf : "<NO LOG BUFFER>");
1314 : : }
1315 : :
1316 : : return r;
1317 : : }
1318 : :
1319 : 0 : int bf_codegen_get_counter(const struct bf_codegen *program,
1320 : : uint32_t counter_idx, struct bf_counter *counter)
1321 : : {
1322 : : assert(program);
1323 : : assert(counter);
1324 : :
1325 : 0 : return bf_handle_get_counter(program->handle, counter_idx, counter);
1326 : : }
1327 : :
1328 : 1472 : size_t bf_codegen_chain_counter_idx(const struct bf_codegen *program)
1329 : : {
1330 : 1472 : return bf_list_size(&program->runtime.chain->rules);
1331 : : }
1332 : :
1333 : 4688 : size_t bf_codegen_error_counter_idx(const struct bf_codegen *program)
1334 : : {
1335 : 4688 : return bf_list_size(&program->runtime.chain->rules) + 1;
1336 : : }
1337 : :
1338 : 1987 : size_t bf_codegen_parser_drop_counter_idx(const struct bf_codegen *program)
1339 : : {
1340 : 1987 : return bf_list_size(&program->runtime.chain->rules) + 2;
1341 : : }
|