From e1d21538e3c420973382843311da3203f1dd5742 Mon Sep 17 00:00:00 2001 From: Mohamed Mahmoud Date: Wed, 20 Sep 2023 11:21:20 -0400 Subject: [PATCH] Support detaching xdp_link-based attachments fix #361 Signed-off-by: Mohamed Mahmoud --- lib/libxdp/libxdp.c | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/libxdp/libxdp.c b/lib/libxdp/libxdp.c index 13e2651f..107a3033 100644 --- a/lib/libxdp/libxdp.c +++ b/lib/libxdp/libxdp.c @@ -3223,6 +3223,42 @@ static int xdp_multiprog__unpin(struct xdp_multiprog *mp) return err; } +static void xdp_detach_links(uint32_t ifindex) { + struct bpf_link_info link_info; + u_int32_t link_info_len = sizeof(link_info), id; + int err, fd; + + while (true) { + err = bpf_link_get_next_id(id, &id); + if (err) { + if (errno == ENOENT) + break; + pr_debug("can't get next link: %s (id %d)", strerror(errno), id); + break; + } + + fd = bpf_link_get_fd_by_id(id); + if (fd < 0) { + pr_debug("can't get link by id (%u): %s", id, strerror(errno)); + continue; + } + memset(&link_info, 0, sizeof(link_info)); + err = bpf_obj_get_info_by_fd(fd, &link_info, &link_info_len); + if (err) { + pr_debug("can't get link info for %u: %s", id, strerror(errno)); + continue; + } + if (link_info.type == BPF_LINK_TYPE_XDP && link_info.xdp.ifindex == ifindex) { + err = bpf_link_detach(fd); + if (err) { + pr_debug("can't detach link %u: %s", id, strerror(errno)); + } + close(fd); + break; + } + } +} + static int xdp_multiprog__attach(struct xdp_multiprog *old_mp, struct xdp_multiprog *mp, enum xdp_attach_mode mode) @@ -3253,8 +3289,15 @@ static int xdp_multiprog__attach(struct xdp_multiprog *old_mp, err = xdp_attach_fd(prog_fd, old_fd, ifindex, mode); - if (err < 0) + if (err < 0) { + if (!mp) { + pr_debug("Detaching links on ifindex %d%s\n", ifindex, + mode == XDP_MODE_SKB? " in skb mode":""); + xdp_detach_links(ifindex); + return 0; + } goto err; + } if (mp) pr_debug("Loaded %zu programs on ifindex %d%s\n",