Skip to content

Commit de5bb43

Browse files
zhengchaoshaoanakryiko
authored andcommitted
samples/bpf: Check detach prog exist or not in xdp_fwd
Before detach the prog, we should check detach prog exist or not. Signed-off-by: Zhengchao Shao <[email protected]> Signed-off-by: Andrii Nakryiko <[email protected]> Reviewed-by: Toke Høiland-Jørgensen <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1 parent 3831cd1 commit de5bb43

File tree

1 file changed

+49
-6
lines changed

1 file changed

+49
-6
lines changed

samples/bpf/xdp_fwd_user.c

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,60 @@ static int do_attach(int idx, int prog_fd, int map_fd, const char *name)
4747
return err;
4848
}
4949

50-
static int do_detach(int idx, const char *name)
50+
static int do_detach(int ifindex, const char *ifname, const char *app_name)
5151
{
52-
int err;
52+
LIBBPF_OPTS(bpf_xdp_attach_opts, opts);
53+
struct bpf_prog_info prog_info = {};
54+
char prog_name[BPF_OBJ_NAME_LEN];
55+
__u32 info_len, curr_prog_id;
56+
int prog_fd;
57+
int err = 1;
58+
59+
if (bpf_xdp_query_id(ifindex, xdp_flags, &curr_prog_id)) {
60+
printf("ERROR: bpf_xdp_query_id failed (%s)\n",
61+
strerror(errno));
62+
return err;
63+
}
5364

54-
err = bpf_xdp_detach(idx, xdp_flags, NULL);
55-
if (err < 0)
56-
printf("ERROR: failed to detach program from %s\n", name);
65+
if (!curr_prog_id) {
66+
printf("ERROR: flags(0x%x) xdp prog is not attached to %s\n",
67+
xdp_flags, ifname);
68+
return err;
69+
}
5770

71+
info_len = sizeof(prog_info);
72+
prog_fd = bpf_prog_get_fd_by_id(curr_prog_id);
73+
if (prog_fd < 0) {
74+
printf("ERROR: bpf_prog_get_fd_by_id failed (%s)\n",
75+
strerror(errno));
76+
return prog_fd;
77+
}
78+
79+
err = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &info_len);
80+
if (err) {
81+
printf("ERROR: bpf_obj_get_info_by_fd failed (%s)\n",
82+
strerror(errno));
83+
goto close_out;
84+
}
85+
snprintf(prog_name, sizeof(prog_name), "%s_prog", app_name);
86+
prog_name[BPF_OBJ_NAME_LEN - 1] = '\0';
87+
88+
if (strcmp(prog_info.name, prog_name)) {
89+
printf("ERROR: %s isn't attached to %s\n", app_name, ifname);
90+
err = 1;
91+
goto close_out;
92+
}
93+
94+
opts.old_prog_fd = prog_fd;
95+
err = bpf_xdp_detach(ifindex, xdp_flags, &opts);
96+
if (err < 0)
97+
printf("ERROR: failed to detach program from %s (%s)\n",
98+
ifname, strerror(errno));
5899
/* TODO: Remember to cleanup map, when adding use of shared map
59100
* bpf_map_delete_elem((map_fd, &idx);
60101
*/
102+
close_out:
103+
close(prog_fd);
61104
return err;
62105
}
63106

@@ -169,7 +212,7 @@ int main(int argc, char **argv)
169212
return 1;
170213
}
171214
if (!attach) {
172-
err = do_detach(idx, argv[i]);
215+
err = do_detach(idx, argv[i], prog_name);
173216
if (err)
174217
ret = err;
175218
} else {

0 commit comments

Comments
 (0)