bpf: fix mount point parsing and drop the legacy loader
Subsystems (3)
cover bpf: fix mount point parsing and drop the legacy loader
While looking at OSS Scanner reports noticed a pattern of issues around the BPF loader. The first set related to parsing of mount points with fscanf("%s").
The next part were issues from the legacy BPF loader which is no longer needed. This series rips the band-aid off and related parts no longer needed.
There were also some bugs in error handling found
while changing all this.
Note: lib/bpf_legacy.c becomes lib/bpf_util.c. "ar rcs" does not drop members that are no longer built, so a stale bpf_legacy.o and sha1.o stay in lib/libutil.a and are picked up by the link. The build still succeeds, but run "make distclean" to be rid of them.
The libbpf build options are gone: libbpf is now always required, and pkg-config is the only way it is found. Both --libbpf_force and --libbpf_dir are now rejected rather than silently ignored.
The last patch adds a tc bpf test, there was none before. It caught a regression in this series that the build did not: the tc/ pin subdirectory quietly went missing.
Since v1: squashed the four libbpf configure patches into one, dropped the bpf_pinning fallback fix since the loader removal deletes that code anyway, moved the tc-bpf(8) update next to the change it documents, and reworded the export removal after Jamal pointed out that LIBBPF_FORCE=off builds did have a working import/run. Dropped Toke's Reviewed-by from the mount point check:
it now also restores the pin subdirectory, so it is not the patch he reviewed.
Stephen Hemminger (7):
lib/bpf: parse /proc/mounts with getmntent and check fs magic lib/fs: parse /proc/mounts with getmntent and check fs magic
tc: remove eBPF map export and exec bpf import
man: tc-bpf: drop references to the removed eBPF agent lib/bpf: require libbpf 1.0 and remove legacy ELF loader lib/bpf: check for missing bpf fs mount point
testsuite: add tc bpf test
bash-completion/tc | 18 +- configure | 129 +- etc/iproute2/bpf_pinning | 6 - examples/bpf/README | 18 +- examples/bpf/bpf_map_in_map.c | 4 +- examples/bpf/bpf_shared.c | 14 +- examples/bpf/legacy/bpf_cyclic.c | 35 - examples/bpf/legacy/bpf_graft.c | 66 - examples/bpf/legacy/bpf_map_in_map.c | 56 - examples/bpf/legacy/bpf_shared.c | 53 - examples/bpf/legacy/bpf_tailcall.c | 117 - include/bpf_api.h | 7 +- include/bpf_elf.h | 35 +- include/bpf_scm.h | 77 - include/bpf_util.h | 41 +- include/sha1.h | 18 - ip/iplink.c | 4 - lib/Makefile | 10 +- lib/bpf_glue.c | 15 +- lib/bpf_legacy.c | 3306 -------------------------- lib/bpf_libbpf.c | 260 +- lib/bpf_util.c | 1105 +++++++++ lib/fs.c | 33 +- lib/sha1.c | 108 - man/man8/ip-link.8.in | 5 +- man/man8/tc-bpf.8 | 173 +- misc/ss.c | 946 +++++--- tc/e_bpf.c | 157 +- tc/f_bpf.c | 12 +- tc/m_bpf.c | 13 +- testsuite/tests/tc/bpf.t | 153 ++ 31 files changed, 2095 insertions(+), 4899 deletions(-) delete mode 100644 etc/iproute2/bpf_pinning delete mode 100644 examples/bpf/legacy/bpf_cyclic.c delete mode 100644 examples/bpf/legacy/bpf_graft.c delete mode 100644 examples/bpf/legacy/bpf_map_in_map.c delete mode 100644 examples/bpf/legacy/bpf_shared.c delete mode 100644 examples/bpf/legacy/bpf_tailcall.c delete mode 100644 include/bpf_scm.h delete mode 100644 include/sha1.h delete mode 100644 lib/bpf_legacy.c create mode 100644 lib/bpf_util.c delete mode 100644 lib/sha1.c create mode 100755 testsuite/tests/tc/bpf.t
Signature · 1 line
2.53.0
PATCH v2 1/7 lib/bpf: parse /proc/mounts with getmntent and check fs magic
--- lib/bpf_legacy.c | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-)
lib/bpf_legacy.c +18 -18
@@ -32,6 +32,7 @@#include <sys/mman.h> #include <sys/mount.h> #include <sys/resource.h> +#include <mntent.h> #include <arpa/inet.h>
@@ -543,12 +544,13 @@ static const char *bpf_find_mntpt_single(unsigned long magic, char *mnt,int ret; ret =bpf_valid_mntpt (mntpt, magic); -if (!ret) { -strlcpy (mnt, mntpt, len); -return mnt; - } +if (ret) +return NULL ; -return NULL ; +if (strlcpy (mnt, mntpt, len) >= (size_t )len) +return NULL ; + +return mnt; } static const char *bpf_find_mntpt(const char *fstype, unsigned long magic,
@@ -556,7 +558,8 @@ static const char *bpf_find_mntpt(const char *fstype, unsigned long magic, const char * const *known_mnts) {const char *const *ptr; -char type[100 ]; +const char *found =NULL ; +struct mntent *ent;FILE *fp;if (known_mnts) {
@@ -568,24 +571,21 @@ static const char *bpf_find_mntpt(const char *fstype, unsigned long magic, } } -if (len !=PATH_MAX ) -return NULL ; - - fp =fopen ("/proc/mounts" ,"r" ); + fp =setmntent ("/proc/mounts" ,"r" );if (fp ==NULL )return NULL ; - while (fscanf(fp, "%*s %" textify(PATH_MAX) "s %99s %*s %*d %*d\n", - mnt, type) ==2 ) { -if (strcmp (type, fstype) ==0 ) +while ((ent =getmntent (fp)) !=NULL ) { +if (strcmp (ent->mnt_type, fstype) !=0 ) +continue ; + + found =bpf_find_mntpt_single (magic, mnt, len, ent->mnt_dir); +if (found)break ; } -fclose (fp); -if (strcmp (type, fstype) !=0 ) -return NULL ; - -return mnt; +endmntent (fp); +return found; }int bpf_trace_pipe (void )
Signature · 1 line
2.53.0
PATCH v2 2/7 lib/fs: parse /proc/mounts with getmntent and check fs magic
In reply to Stephen Hemminger--- lib/fs.c | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-)
lib/fs.c +20 -13
@@ -9,6 +9,8 @@#include <sys/stat.h> #include <sys/socket.h> #include <sys/mount.h> +#include <sys/vfs.h> +#include <mntent.h> #include <ctype.h> #include <fcntl.h> #include <stdio.h>
@@ -17,6 +19,7 @@#include <string.h> #include <errno.h> #include <limits.h> +#include <linux/magic.h> #include "utils.h"
@@ -50,30 +53,34 @@ static int open_by_handle_at(int mount_fd, struct file_handle *handle, int flags }#endif -/* return mount path of first occurrence of given fstype */ -static char *find_fs_mount (const char *fs_to_find) +/* return mount path of first mount of given fstype that passes statfs check */ +static char *find_fs_mount (const char *fs_to_find,unsigned long magic) { -char path[4096 ]; -char fstype[128 ];/* max length of any filesystem name */ +struct mntent *ent; +struct statfs st;char *mnt =NULL ;FILE *fp; - fp =fopen ("/proc/mounts" ,"r" ); + fp =setmntent ("/proc/mounts" ,"r" );if (!fp) {fprintf (stderr,"Failed to open mounts file: %s\n" ,strerror (errno));return NULL ; } -while (fscanf (fp,"%*s %4095s %127s %*s %*d %*d\n" , - path, fstype) ==2 ) { -if (strcmp (fstype, fs_to_find) ==0 ) { - mnt =strdup (path); -break ; - } +while ((ent =getmntent (fp)) !=NULL ) { +if (strcmp (ent->mnt_type, fs_to_find) !=0 ) +continue ; + +if (statfs (ent->mnt_dir, &st) <0 || + (unsigned long )st.f_type != magic) +continue ; + + mnt =strdup (ent->mnt_dir); +break ; } -fclose (fp); +endmntent (fp);return mnt; }
@@ -81,7 +88,7 @@ static char *find_fs_mount(const char *fs_to_find)/* caller needs to free string returned */ char *find_cgroup2_mount (bool do_mount) { -char *mnt =find_fs_mount (CGROUP2_FS_NAME ); +char *mnt =find_fs_mount (CGROUP2_FS_NAME ,CGROUP2_SUPER_MAGIC );if (mnt)return mnt;
Signature · 1 line
2.53.0
PATCH v2 3/7 tc: remove eBPF map export and exec bpf import
In reply to Stephen HemmingerThe export option of tc bpf filters and actions sends the map file descriptors to whatever process is bound to the given Unix socket. The socket owner is not checked, so the maps can end up with an unrelated process that happens to be bound to that path.
The path cannot be made safe without redesigning the trust model around it, so remove the export option, the exec bpf import and run commands, and the TC_BPF_UDS environment variable.
Default builds have used libbpf for years and send nothing, so they lose nothing here. Builds configured with LIBBPF_FORCE=off did have a working import/run, and it was the only in-tree way to hand maps to a helper without pinning them; those builds lose that. Pin the maps in bpffs instead and have the helper open them by path, or use bpftool to pass them along.
--- bash-completion/tc | 18 +--- include/bpf_scm.h | 77 ---------------- include/bpf_util.h | 18 +--- lib/bpf_legacy.c | 217 +-------------------------------------------- man/man8/tc-bpf.8 | 109 +++-------------------- tc/e_bpf.c | 157 ++++++-------------------------- tc/f_bpf.c | 12 +-- tc/m_bpf.c | 13 +-- 8 files changed, 48 insertions(+), 573 deletions(-) delete mode 100644 include/bpf_scm.h
bash-completion/tc +3 -15
@@ -205,7 +205,7 @@ _tc_direct_complete() ;; # BPF options - used for filters, actions, and exec - export|bytecode|bytecode-file|object-file) + bytecode|bytecode-file|object-file) _filedir return 0 ;;
@@ -230,10 +230,6 @@ _tc_direct_complete() fi return 0 ;; - import|run) - _filedir - return 0 - ;; type) COMPREPLY+=( $( compgen -W 'cls act' -- "$cur" ) ) return 0
@@ -387,10 +383,7 @@ _tc_qdisc_options() _tc_bpf_options() { [[ ${words[${#words[@]}-3]} == object-file ]] && \ - _tc_once_attr 'section export' - [[ ${words[${#words[@]}-5]} == object-file ]] && \ - [[ ${words[${#words[@]}-3]} =~ (section|export) ]] && \ - _tc_once_attr 'section export' + _tc_once_attr 'section' _tc_one_of_list 'bytecode bytecode-file object-file object-pinned' _tc_once_attr 'verbose index direct-action action classid' return 0
@@ -524,11 +517,6 @@ _tc_action_options() _tc_exec_options() { case $1 in - import) - [[ ${words[${#words[@]}-3]} == import ]] && \ - _tc_once_attr 'run' - return 0 - ;; graft) COMPREPLY+=( $( compgen -W 'key type' -- "$cur" ) ) [[ ${words[${#words[@]}-3]} == object-file ]] && \
@@ -772,7 +760,7 @@ _tc() exec) case $subcmd in bpf) - local excmd exwd EXEC_KIND=' import debug graft ' + local excmd exwd EXEC_KIND=' debug graft ' for ((exwd=$subcword; exwd < ${#words[@]}-1; exwd++)); do if [[ $EXEC_KIND =~ ' '${words[exwd]}' ' ]]; then excmd=${words[exwd]}
include/bpf_scm.h deleted +0 -77
77 lines not on this page · raw message
include/bpf_util.h +1 -17
@@ -16,9 +16,8 @@#include <linux/elf-em.h> #include "utils.h" -#include "bpf_scm.h" +#include "bpf_elf.h" -#define BPF_ENV_UDS "TC_BPF_UDS"#define BPF_ENV_MNT "TC_BPF_MNT"#ifndef BPF_MAX_LOG
@@ -60,7 +59,6 @@ struct bpf_cfg_in {const char *object;const char *section;const char *prog_name; -const char *uds;enum bpf_prog_type type;enum bpf_mode mode;__u32 ifindex;
@@ -282,9 +280,6 @@ int bpf_dump_prog_info(FILE *f, uint32_t id);int bpf (int cmd,union bpf_attr *attr,unsigned int size);#ifdef HAVE_ELF -int bpf_send_map_fds (const char *path,const char *obj); -int bpf_recv_map_fds (const char *path,int *fds,struct bpf_map_aux *aux, -unsigned int entries);#ifdef HAVE_LIBBPF int iproute2_bpf_elf_ctx_init (struct bpf_cfg_in *cfg);int iproute2_bpf_fetch_ancillary (void );
@@ -296,17 +291,6 @@ int iproute2_find_map_name_by_id(unsigned int map_id, char *name);int iproute2_load_libbpf (struct bpf_cfg_in *cfg);#endif /* HAVE_LIBBPF */ #else -static inline int bpf_send_map_fds (const char *path,const char *obj) -{ -return 0 ; -} - -static inline int bpf_recv_map_fds (const char *path,int *fds, -struct bpf_map_aux *aux, -unsigned int entries) -{ -return -1 ; -}#ifdef HAVE_LIBBPF static inline int iproute2_load_libbpf (struct bpf_cfg_in *cfg) {
lib/bpf_legacy.c +2 -215
299 lines not on this page · raw message
man/man8/tc-bpf.8 +12 -97
135 lines not on this page · raw message
tc/e_bpf.c +25 -132
192 lines not on this page · raw message
tc/f_bpf.c +2 -10
@@ -27,7 +27,7 @@ static void explain(void)" bytecode-file FILE\n" "\n" "eBPF use case:\n" -" object-file FILE [ section CLS_NAME ] [ export UDS_FILE ]" +" object-file FILE [ section CLS_NAME ]" " [ verbose ] [ direct-action ] [ skip_hw | skip_sw ]\n" " object-pinned FILE [ direct-action ] [ skip_hw | skip_sw ]\n" "\n"
@@ -74,7 +74,6 @@ static const struct bpf_cfg_ops bpf_cb_ops = {static int bpf_parse_opt (const struct filter_util *qu,char *handle,int argc,char **argv,struct nlmsghdr *n) { -const char *bpf_obj =NULL , *bpf_uds_name =NULL ;struct tcmsg *t =NLMSG_DATA (n);unsigned int bpf_gen_flags =0 ;unsigned int bpf_flags =0 ;
@@ -82,7 +81,6 @@ static int bpf_parse_opt(const struct filter_util *qu, char *handle,bool seen_run = false;bool skip_sw = false;struct rtattr *tail; -int ret =0 ;if (handle) {if (get_u32 (&t->tcm_handle, handle,0 )) {
@@ -117,9 +115,6 @@ opt_bpf: argc = cfg.argc; argv = cfg.argv; - - bpf_obj = cfg.object; - bpf_uds_name = cfg.uds; }else if (matches (*argv,"classid" ) ==0 ||matches (*argv,"flowid" ) ==0 ) {unsigned int classid;
@@ -181,10 +176,7 @@ opt_bpf: tail->rta_len = (((void *)n) + n->nlmsg_len) - (void *)tail; -if (bpf_uds_name) - ret =bpf_send_map_fds (bpf_uds_name, bpf_obj); - -return ret; +return 0 ; } static int bpf_print_opt(const struct filter_util *qu, FILE *f,
tc/m_bpf.c +3 -10
@@ -29,7 +29,7 @@ static void explain(void)" bytecode-file FILE\n" "\n" "eBPF use case:\n" -" object-file FILE [ section ACT_NAME ] [ export UDS_FILE ]" +" object-file FILE [ section ACT_NAME ]" " [ verbose ]\n" " object-pinned FILE\n" "\n"
@@ -72,12 +72,11 @@ static const struct bpf_cfg_ops bpf_cb_ops = {static int bpf_parse_opt (const struct action_util *a,int *ptr_argc,char ***ptr_argv,int tca_id,struct nlmsghdr *n) { -const char *bpf_obj =NULL , *bpf_uds_name =NULL ;struct tc_act_bpf parm = {};struct bpf_cfg_in cfg = {};bool seen_run = false;struct rtattr *tail; -int argc, ret =0 ; +int argc;char **argv; argv = *ptr_argv;
@@ -107,9 +106,6 @@ opt_bpf: argc = cfg.argc; argv = cfg.argv; - - bpf_obj = cfg.object; - bpf_uds_name = cfg.uds; }else if (matches (*argv,"help" ) ==0 ) {explain ();return -1 ;
@@ -142,13 +138,10 @@ opt_bpf:addattr_l (n,MAX_MSG ,TCA_ACT_BPF_PARMS , &parm,sizeof (parm));addattr_nest_end (n, tail); -if (bpf_uds_name) - ret =bpf_send_map_fds (bpf_uds_name, bpf_obj); - *ptr_argc = argc; *ptr_argv = argv; -return ret; +return 0 ; }static int bpf_print_opt (const struct action_util *au,FILE *f,struct rtattr *arg)
Signature · 1 line
2.53.0
Re: [PATCH iproute2-next v2 3/7] tc: remove eBPF map export and exec bpf import
Quoted 17 lines · Stephen Hemminger
The export option of tc bpf filters and actions sends the map file descriptors to whatever process is bound to the given Unix socket. The socket owner is not checked, so the maps can end up with an unrelated process that happens to be bound to that path.
The path cannot be made safe without redesigning the trust model around it, so remove the export option, the exec bpf import and run commands, and the
TC_BPF_UDSenvironment variable.Default builds have used libbpf for years and send nothing, so they lose nothing here. Builds configured with LIBBPF_FORCE=off did have a working import/run, and it was the only in-tree way to hand maps to a helper without pinning them; those builds lose that. Pin the maps in bpffs instead and have the helper open them by path, or use bpftool to pass them along.
Quoted 4 lines
Fixes 6256f8c9e45f ("tc, bpf: finalize eBPF support for cls and act front-end")Reported-by Anthropic OSS scanner (ANT-2026-5S9IO0L4)Assisted-by Claude:claude-opus-5-5Signed-off-by Stephen Hemminger <[email protected]>
cheers,
jamal
Quoted 964 lines
--- bash-completion/tc | 18 +--- include/bpf_scm.h | 77 ---------------- include/bpf_util.h | 18 +--- lib/bpf_legacy.c | 217 +-------------------------------------------- man/man8/tc-bpf.8 | 109 +++-------------------- tc/e_bpf.c | 157 ++++++-------------------------- tc/f_bpf.c | 12 +-- tc/m_bpf.c | 13 +-- 8 files changed, 48 insertions(+), 573 deletions(-) delete mode 100644 include/bpf_scm.hbash-completion/tc +3
-15@@ -205,7 +205,7 @@ _tc_direct_complete() ;; # BPF options - used for filters, actions, and exec - export|bytecode|bytecode-file|object-file) + bytecode|bytecode-file|object-file) _filedir return 0 ;;@@ -230,10 +230,6 @@ _tc_direct_complete() fi return 0 ;; - import|run) - _filedir - return 0 - ;; type) COMPREPLY+=( $( compgen -W 'cls act' -- "$cur" ) ) return 0@@ -387,10 +383,7 @@ _tc_qdisc_options() _tc_bpf_options() { [[ ${words[${#words[@]}-3]} == object-file ]] && \ - _tc_once_attr 'section export' - [[ ${words[${#words[@]}-5]} == object-file ]] && \ - [[ ${words[${#words[@]}-3]} =~ (section|export) ]] && \ - _tc_once_attr 'section export' + _tc_once_attr 'section' _tc_one_of_list 'bytecode bytecode-file object-file object-pinned' _tc_once_attr 'verbose index direct-action action classid' return 0@@ -524,11 +517,6 @@ _tc_action_options() _tc_exec_options() { case $1 in - import) - [[ ${words[${#words[@]}-3]} == import ]] && \ - _tc_once_attr 'run' - return 0 - ;; graft) COMPREPLY+=( $( compgen -W 'key type' -- "$cur" ) ) [[ ${words[${#words[@]}-3]} == object-file ]] && \@@ -772,7 +760,7 @@ _tc() exec) case $subcmd in bpf) - local excmd exwd EXEC_KIND=' import debug graft ' + local excmd exwd EXEC_KIND=' debug graft ' for ((exwd=$subcword; exwd < ${#words[@]}-1; exwd++)); do if [[ $EXEC_KIND =~ ' '${words[exwd]}' ' ]]; then excmd=${words[exwd]}include/bpf_scm.h deleted +0
-77@@ -1,77 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef __BPF_SCM__ -#define __BPF_SCM__ - -#include <sys/types.h> -#include <sys/socket.h> -#include <sys/un.h> - -#include "utils.h" -#include "bpf_elf.h" - -#define BPF_SCM_AUX_VER 1 -#define BPF_SCM_MAX_FDS ELF_MAX_MAPS -#define BPF_SCM_MSG_SIZE 1024 - -struct bpf_elf_st { -dev_t st_dev; -ino_t st_ino; -}; - -struct bpf_map_aux { -unsigned short uds_ver; -unsigned short num_ent; -char obj_name[64 ]; -struct bpf_elf_st obj_st; -struct bpf_elf_map ent[BPF_SCM_MAX_FDS ]; -}; - -struct bpf_map_set_msg { -struct msghdr hdr; -struct iovec iov; -char msg_buf[BPF_SCM_MSG_SIZE ]; -struct bpf_map_aux aux; -}; - -static inline int *bpf_map_set_init (struct bpf_map_set_msg *msg, -struct sockaddr_un *addr, -unsigned int addr_len) -{ -const unsigned int cmsg_ctl_len =sizeof (int ) *BPF_SCM_MAX_FDS ; -struct cmsghdr *cmsg; - - msg->iov.iov_base = &msg->aux; - msg->iov.iov_len =sizeof (msg->aux); - - msg->hdr.msg_iov = &msg->iov; - msg->hdr.msg_iovlen =1 ; - - msg->hdr.msg_name = (struct sockaddr *)addr; - msg->hdr.msg_namelen = addr_len; - -BUILD_BUG_ON (sizeof (msg->msg_buf) < cmsg_ctl_len); - msg->hdr.msg_control = &msg->msg_buf; - msg->hdr.msg_controllen = cmsg_ctl_len; - - cmsg =CMSG_FIRSTHDR (&msg->hdr); - cmsg->cmsg_len = msg->hdr.msg_controllen; - cmsg->cmsg_level =SOL_SOCKET ; - cmsg->cmsg_type =SCM_RIGHTS ; - -return (int *)CMSG_DATA (cmsg); -} - -static inline void bpf_map_set_init_single (struct bpf_map_set_msg *msg, -int num) -{ -struct cmsghdr *cmsg; - - msg->hdr.msg_controllen =CMSG_LEN (sizeof (int ) * num); - msg->iov.iov_len = offsetof(struct bpf_map_aux , ent) + -sizeof (struct bpf_elf_map ) * num; - - cmsg =CMSG_FIRSTHDR (&msg->hdr); - cmsg->cmsg_len = msg->hdr.msg_controllen; -} - -#endif /* __BPF_SCM__ */ include/bpf_util.h +1
-17@@ -16,9 +16,8 @@#include <linux/elf-em.h> #include "utils.h" -#include "bpf_scm.h" +#include "bpf_elf.h" -#define BPF_ENV_UDS "TC_BPF_UDS"#define BPF_ENV_MNT "TC_BPF_MNT"#ifndef BPF_MAX_LOG @@ -60,7 +59,6 @@ struct bpf_cfg_in {const char *object;const char *section;const char *prog_name; -const char *uds;enum bpf_prog_type type;enum bpf_mode mode;__u32 ifindex;@@ -282,9 +280,6 @@ int bpf_dump_prog_info(FILE *f, uint32_t id);int bpf (int cmd,union bpf_attr *attr,unsigned int size);#ifdef HAVE_ELF -int bpf_send_map_fds (const char *path,const char *obj); -int bpf_recv_map_fds (const char *path,int *fds,struct bpf_map_aux *aux, -unsigned int entries);#ifdef HAVE_LIBBPF int iproute2_bpf_elf_ctx_init (struct bpf_cfg_in *cfg);int iproute2_bpf_fetch_ancillary (void );@@ -296,17 +291,6 @@ int iproute2_find_map_name_by_id(unsigned int map_id, char *name);int iproute2_load_libbpf (struct bpf_cfg_in *cfg);#endif /* HAVE_LIBBPF */ #else -static inline int bpf_send_map_fds (const char *path,const char *obj) -{ -return 0 ; -} - -static inline int bpf_recv_map_fds (const char *path,int *fds, -struct bpf_map_aux *aux, -unsigned int entries) -{ -return -1 ; -}#ifdef HAVE_LIBBPF static inline int iproute2_load_libbpf (struct bpf_cfg_in *cfg) {lib/bpf_legacy.c +2
-215@@ -42,13 +42,11 @@#include "bpf_util.h" #include "bpf_elf.h" -#include "bpf_scm.h" struct bpf_prog_meta {const char *type;const char *subdir;const char *section; -bool may_uds_export; };static const enum bpf_prog_type __bpf_types[] = {@@ -65,13 +63,11 @@ static const struct bpf_prog_meta __bpf_prog_meta[] = { .type = "cls", .subdir = "tc", .section = ELF_SECTION_CLASSIFIER, - .may_uds_export = true, }, [BPF_PROG_TYPE_SCHED_ACT] = { .type = "act", .subdir = "tc", .section = ELF_SECTION_ACTION, - .may_uds_export = true, }, [BPF_PROG_TYPE_XDP] = { .type = "xdp",@@ -827,7 +823,7 @@ static int bpf_obj_pinned(const char *pathname, enum bpf_prog_type type)static int bpf_do_parse (struct bpf_cfg_in *cfg,const bool *opt_tbl) { -const char *file, *section, *uds_name, *prog_name; +const char *file, *section, *prog_name;bool verbose = false;int i, ret, argc;char **argv;@@ -858,7 +854,7 @@ static int bpf_do_parse(struct bpf_cfg_in *cfg, const bool *opt_tbl) }NEXT_ARG (); - file = section = uds_name = prog_name =NULL ; + file = section = prog_name =NULL ;if (cfg->mode ==EBPF_OBJECT || cfg->mode ==EBPF_PINNED ) { file = *argv;NEXT_ARG_FWD ();@@ -901,16 +897,6 @@ static int bpf_do_parse(struct bpf_cfg_in *cfg, const bool *opt_tbl)NEXT_ARG_FWD (); } -if (__bpf_prog_meta[cfg->type].may_uds_export) { - uds_name =getenv (BPF_ENV_UDS ); -if (argc >0 && !uds_name && -matches (*argv,"export" ) ==0 ) { -NEXT_ARG (); - uds_name = *argv; -NEXT_ARG_FWD (); - } - } -if (argc >0 &&matches (*argv,"verbose" ) ==0 ) { verbose = true;NEXT_ARG_FWD ();@@ -934,7 +920,6 @@ static int bpf_do_parse(struct bpf_cfg_in *cfg, const bool *opt_tbl) cfg->object = file; cfg->section = section; - cfg->uds = uds_name; cfg->argc = argc; cfg->argv = argv; cfg->verbose = verbose;@@ -1179,7 +1164,6 @@ struct bpf_elf_ctx {enum bpf_prog_type type;__u32 ifindex;bool verbose; -struct bpf_elf_st stat;struct bpf_hash_entry *ht[256 ];char *log;size_t log_size;@@ -1191,13 +1175,6 @@ struct bpf_elf_sec_data {const char *sec_name; }; -struct bpf_map_data { -int *fds; -const char *obj; -struct bpf_elf_st *st; -struct bpf_elf_map *ent; -}; -static bool bpf_log_has_data (struct bpf_elf_ctx *ctx) {return ctx->log && ctx->log[0 ];@@ -2647,24 +2624,6 @@ static int bpf_fill_prog_arrays(struct bpf_elf_ctx *ctx)return 0 ; } -static void bpf_save_finfo (struct bpf_elf_ctx *ctx) -{ -struct stat st; -int ret; - -memset (&ctx->stat,0 ,sizeof (ctx->stat)); - - ret =fstat (ctx->obj_fd, &st); -if (ret <0 ) { -fprintf (stderr,"Stat of elf file failed: %s\n" , -strerror (errno)); -return ; - } - - ctx->stat.st_dev = st.st_dev; - ctx->stat.st_ino = st.st_ino; -} -static int bpf_read_pin_mapping (FILE *fp,uint32_t *id,char *path) {char buff[PATH_MAX ];@@ -2877,7 +2836,6 @@ static int bpf_elf_ctx_init(struct bpf_elf_ctx *ctx, const char *pathname, goto out_free; } -bpf_save_finfo (ctx);bpf_hash_init (ctx,CONF_ETC_DIR "/bpf_pinning" );if (ret == -ENOENT ) ret =bpf_hash_init (ctx,CONF_USR_DIR "/bpf_pinning" );@@ -2892,19 +2850,6 @@ out_fd:return ret; } -static int bpf_maps_count (struct bpf_elf_ctx *ctx) -{ -int i, count =0 ; - -for (i =0 ; i <ARRAY_SIZE (ctx->map_fds); i++) { -if (!ctx->map_fds[i]) -break ; - count++; - } - -return count; -} -static void bpf_maps_teardown (struct bpf_elf_ctx *ctx) {int i;@@ -2975,164 +2920,6 @@ out:return fd; } -static int -bpf_map_set_send (int fd,struct sockaddr_un *addr,unsigned int addr_len, -const struct bpf_map_data *aux,unsigned int entries) -{ -struct bpf_map_set_msg msg = { - .aux.uds_ver =BPF_SCM_AUX_VER , - .aux.num_ent = entries, - }; -int *cmsg_buf, min_fd; -char *amsg_buf; -int i; - -strlcpy (msg.aux.obj_name, aux->obj,sizeof (msg.aux.obj_name)); -memcpy (&msg.aux.obj_st, aux->st,sizeof (msg.aux.obj_st)); - - cmsg_buf =bpf_map_set_init (&msg, addr, addr_len); - amsg_buf = (char *)msg.aux.ent; - -for (i =0 ; i < entries; i += min_fd) { -int ret; - - min_fd =min (BPF_SCM_MAX_FDS *1U , entries - i); -bpf_map_set_init_single (&msg, min_fd); - -memcpy (cmsg_buf, &aux->fds[i],sizeof (aux->fds[0 ]) * min_fd); -memcpy (amsg_buf, &aux->ent[i],sizeof (aux->ent[0 ]) * min_fd); - - ret =sendmsg (fd, &msg.hdr,0 ); -if (ret <=0 ) -return ret ? :-1 ; - } - -return 0 ; -} - -static int -bpf_map_set_recv (int fd,int *fds,struct bpf_map_aux *aux, -unsigned int entries) -{ -struct bpf_map_set_msg msg; -int *cmsg_buf, min_fd; -char *amsg_buf, *mmsg_buf; -unsigned int needed =1 ; -int i; - - cmsg_buf =bpf_map_set_init (&msg,NULL ,0 ); - amsg_buf = (char *)msg.aux.ent; - mmsg_buf = (char *)&msg.aux; - -for (i =0 ; i <min (entries, needed); i += min_fd) { -struct cmsghdr *cmsg; -int ret; - - min_fd =min (entries, entries - i); -bpf_map_set_init_single (&msg, min_fd); - - ret =recvmsg (fd, &msg.hdr,0 ); -if (ret <=0 ) -return ret ? :-1 ; - - cmsg =CMSG_FIRSTHDR (&msg.hdr); -if (!cmsg || cmsg->cmsg_type !=SCM_RIGHTS ) -return -EINVAL ; -if (msg.hdr.msg_flags &MSG_CTRUNC ) -return -EIO ; -if (msg.aux.uds_ver !=BPF_SCM_AUX_VER ) -return -ENOSYS ; - - min_fd = (cmsg->cmsg_len -sizeof (*cmsg)) /sizeof (fd); -if (min_fd > entries || min_fd <=0 ) -return -EINVAL ; - -memcpy (&fds[i], cmsg_buf,sizeof (fds[0 ]) * min_fd); -memcpy (&aux->ent[i], amsg_buf,sizeof (aux->ent[0 ]) * min_fd); -memcpy (aux, mmsg_buf, offsetof(struct bpf_map_aux , ent)); - - needed = aux->num_ent; - } - -return 0 ; -} - -int bpf_send_map_fds (const char *path,const char *obj) -{ -struct bpf_elf_ctx *ctx = &__ctx; -struct sockaddr_un addr = { .sun_family =AF_UNIX }; -struct bpf_map_data bpf_aux = { - .fds = ctx->map_fds, - .ent = ctx->maps, - .st = &ctx->stat, - .obj = obj, - }; -int fd, ret =-1 ; - - fd =socket (AF_UNIX ,SOCK_DGRAM ,0 ); -if (fd <0 ) { -fprintf (stderr,"Cannot open socket: %s\n" , -strerror (errno)); - goto out; - } - -strlcpy (addr.sun_path, path,sizeof (addr.sun_path)); - - ret =connect (fd, (struct sockaddr *)&addr,sizeof (addr)); -if (ret <0 ) { -fprintf (stderr,"Cannot connect to %s: %s\n" , - path,strerror (errno)); - goto out; - } - - ret =bpf_map_set_send (fd, &addr,sizeof (addr), &bpf_aux, -bpf_maps_count (ctx)); -if (ret <0 ) -fprintf (stderr,"Cannot send fds to %s: %s\n" , - path,strerror (errno)); - -bpf_maps_teardown (ctx); -out: -if (fd >=0 ) -close (fd); -return ret; -} - -int bpf_recv_map_fds (const char *path,int *fds,struct bpf_map_aux *aux, -unsigned int entries) -{ -struct sockaddr_un addr = { .sun_family =AF_UNIX }; -int fd, ret =-1 ; - - fd =socket (AF_UNIX ,SOCK_DGRAM ,0 ); -if (fd <0 ) { -fprintf (stderr,"Cannot open socket: %s\n" , -strerror (errno)); - goto out; - } - -strlcpy (addr.sun_path, path,sizeof (addr.sun_path)); - - ret =bind (fd, (struct sockaddr *)&addr,sizeof (addr)); -if (ret <0 ) { -fprintf (stderr,"Cannot bind to socket: %s\n" , -strerror (errno)); - goto out; - } - - ret =bpf_map_set_recv (fd, fds, aux, entries); -if (ret <0 ) -fprintf (stderr,"Cannot recv fds from %s: %s\n" , - path,strerror (errno)); - -unlink (addr.sun_path); - -out: -if (fd >=0 ) -close (fd); -return ret; -} -#ifdef HAVE_LIBBPF /* The following functions are wrapper functions for libbpf code to be * compatible with the legacy format. So all the functions have prefix man/man8/tc-bpf.8 +12
-97@@ -10,8 +10,6 @@ queueing disciplines OBJ_FILE ] [ .B section CLS_NAME ] [ -.B export -UDS_FILE ] [ .B verbose ] [ .B direct-action@@ -35,8 +33,6 @@ CLASSID ] OBJ_FILE ] [ .B section CLS_NAME ] [ -.B export -UDS_FILE ] [ .B verbose ]@@ -158,17 +154,6 @@ that a single object file can contain multiple classifier and actions, the corresponding section name needs to be specified, if it differs from the defaults. -.SS export -points to a Unix domain socket file. In case the eBPF object file also -contains a section named "maps" with eBPF map specifications, then the -map file descriptors can be handed off via the Unix domain socket to -an eBPF "agent" herding all descriptors after tc lifetime. This can be -some third party application implementing the IPC counterpart for the -import, that uses them for calling into -.B bpf(2) -system call to read out or update eBPF map data from user space, for -example, for monitoring purposes or to push down new policies. - .SS verbose if set, it will dump the eBPF verifier output, even if loading the eBPF program was successful. By default, only on error, the verifier log is@@ -424,90 +409,20 @@ example: The advantage of this is that the classifier and the two actions can then share eBPF maps with each other, if implemented in the programs. -In order to access eBPF maps from user space beyond -.B tc(8) -setup lifetime, the ownership can be transferred to an eBPF agent via -Unix domain sockets. There are two possibilities for implementing this: - -.B 1) -implementation of an own eBPF agent that takes care of setting up -the Unix domain socket and implementing the protocol that +eBPF maps can be accessed from user space beyond .B tc(8) -dictates. A code example of this can be found inside the iproute2 -source package under: -.B examples/bpf/ - -.B 2) -use -.B tc exec -for transferring the eBPF map file descriptors through a Unix domain -socket, and spawning an application such as -.B sh(1) -\&. This approach's advantage is that tc will place the file descriptors -into the environment and thus make them available just like stdin, stdout, -stderr file descriptors, meaning, in case user applications run from within -this fd-owner shell, they can terminate and restart without losing eBPF -maps file descriptors. Example invocation with the previous classifier and -action mixture: - -.in +4n -.B tc exec bpf imp /tmp/bpf -.br -.B tc filter add dev em1 parent 1: bpf obj bpf.o exp /tmp/bpf flowid 1:1 \e -.br -.in +25n -.B action bpf obj bpf.o sec action-mark \e -.br -.B action bpf obj bpf.o sec action-rand ok -.in -25n -.in -4n - -Assuming that eBPF maps are shared with classifier and actions, it's -enough to export them once, for example, from within the classifier -or action command. tc will setup all eBPF map file descriptors at the -time when the object file is first parsed. - -When a shell has been spawned, the environment will have a couple of -eBPF related variables. BPF_NUM_MAPS provides the total number of maps -that have been transferred over the Unix domain socket. BPF_MAP<X>'s -value is the file descriptor number that can be accessed in eBPF agent -applications, in other words, it can directly be used as the file -descriptor value for the +setup lifetime by pinning them in the BPF file system. Maps declared +with the +.B pinning +attribute set to +.B LIBBPF_PIN_BY_NAME +are pinned under +.B /sys/fs/bpf/tc/globals/ +and can be inspected or updated with +.B bpftool(8) +or any program using the .B bpf(2) -system call to retrieve or alter eBPF map values. <X> denotes the -identifier of the eBPF map. It corresponds to the -.B id -member of -.B struct bpf_elf_map -\& from the tc eBPF map specification. - -The environment in this example looks as follows: - -.in +4n -.nf -.sp -sh# env | grep BPF - BPF_NUM_MAPS=3 - BPF_MAP1=6 - BPF_MAP0=5 - BPF_MAP2=7 -sh# ls -la /proc/self/fd - [...] - lrwx------. 1 root root 64 Apr 14 16:46 5 -> anon_inode:bpf-map - lrwx------. 1 root root 64 Apr 14 16:46 6 -> anon_inode:bpf-map - lrwx------. 1 root root 64 Apr 14 16:46 7 -> anon_inode:bpf-map -sh# my_bpf_agent -.fi -.in - -eBPF agents are very useful in that they can prepopulate eBPF maps from -user space, monitor statistics via maps and based on that feedback, for -example, rewrite classids in eBPF map values during runtime. Given that eBPF -agents are implemented as normal applications, they can also dynamically -receive traffic control policies from external controllers and thus push -them down into eBPF maps to dynamically adapt to network conditions. Moreover, -eBPF maps can also be shared with other eBPF program types (e.g. tracing), -thus very powerful combination can therefore be implemented. +system call. .SS eBPF PROGRAMMINGtc/e_bpf.c +25
-132@@ -6,167 +6,60 @@*/ #include <stdio.h> -#include <unistd.h> #include "utils.h" #include "tc_util.h" #include "bpf_util.h" -#include "bpf_elf.h" -#include "bpf_scm.h" - -#define BPF_DEFAULT_CMD "/bin/sh" - -static char *argv_default[] = {BPF_DEFAULT_CMD ,NULL };static void explain (void ) {fprintf (stderr, -"Usage: ... bpf [ import UDS_FILE ] [ run CMD ]\n" -" ... bpf [ debug ]\n" +"Usage: ... bpf [ debug ]\n" " ... bpf [ graft MAP_FILE ] [ key KEY ]\n" " `... [ object-file OBJ_FILE ] [ type TYPE ] [ section NAME ] [ verbose ]\n" " `... [ object-pinned PROG_FILE ]\n" "\n" -"Where UDS_FILE provides the name of a unix domain socket file\n" -"to import eBPF maps and the optional CMD denotes the command\n" -"to be executed (default: \'%s\').\n" "Where MAP_FILE points to a pinned map, OBJ_FILE to an object file\n" "and PROG_FILE to a pinned program. TYPE can be {cls, act}, where\n" "\'cls\' is default. KEY is optional and can be inferred from the\n" -"section name, otherwise it needs to be provided.\n" , -BPF_DEFAULT_CMD ); -} - -static int bpf_num_env_entries (void ) -{ -char **envp; -int num; - -for (num =0 , envp = environ; *envp !=NULL ; envp++) - num++; -return num; +"section name, otherwise it needs to be provided.\n" ); }static int parse_bpf (const struct exec_util *eu,int argc,char **argv) { -char **argv_run = argv_default, **envp_run, *tmp; -int ret, i, env_old, env_num, env_map; -const char *bpf_uds_name =NULL ; -int fds[BPF_SCM_MAX_FDS ] = {}; -struct bpf_map_aux aux = {}; -if (argc ==0 )return 0 ; -while (argc >0 ) { -if (matches (*argv,"run" ) ==0 ) { -NEXT_ARG (); - argv_run = argv; -break ; - }else if (matches (*argv,"import" ) ==0 ) { -NEXT_ARG (); - bpf_uds_name = *argv; - }else if (matches (*argv,"debug" ) ==0 || -matches (*argv,"dbg" ) ==0 ) { -if (bpf_trace_pipe ()) -fprintf (stderr, -"No trace pipe, tracefs not mounted?\n" ); -return -1 ; - }else if (matches (*argv,"graft" ) ==0 ) { -const char *bpf_map_path; -bool has_key = false; -uint32_t key; - -NEXT_ARG (); - bpf_map_path = *argv; +if (matches (*argv,"debug" ) ==0 || +matches (*argv,"dbg" ) ==0 ) { +if (bpf_trace_pipe ()) +fprintf (stderr, +"No trace pipe, tracefs not mounted?\n" ); +return -1 ; + }else if (matches (*argv,"graft" ) ==0 ) { +const char *bpf_map_path; +bool has_key = false; +uint32_t key; + +NEXT_ARG (); + bpf_map_path = *argv; +NEXT_ARG (); +if (matches (*argv,"key" ) ==0 ) {NEXT_ARG (); -if (matches (*argv,"key" ) ==0 ) { -NEXT_ARG (); -if (get_unsigned (&key, *argv,0 )) { -fprintf (stderr,"Illegal \"key\"\n" ); -return -1 ; - } - has_key = true; -NEXT_ARG (); +if (get_unsigned (&key, *argv,0 )) { +fprintf (stderr,"Illegal \"key\"\n" ); +return -1 ; } -return bpf_graft_map (bpf_map_path, has_key ? - &key :NULL , argc, argv); - }else { -explain (); -return -1 ; + has_key = true; +NEXT_ARG (); } - -NEXT_ARG_FWD (); +return bpf_graft_map (bpf_map_path, has_key ? + &key :NULL , argc, argv); } -if (!bpf_uds_name) { -fprintf (stderr,"bpf: No import parameter provided!\n" ); -explain (); -return -1 ; - } - -if (argv_run != argv_default && argc ==0 ) { -fprintf (stderr,"bpf: No run command provided!\n" ); -explain (); -return -1 ; - } - - ret =bpf_recv_map_fds (bpf_uds_name, fds, &aux,ARRAY_SIZE (fds)); -if (ret <0 ) { -fprintf (stderr,"bpf: Could not receive fds!\n" ); -return -1 ; - } - -if (aux.num_ent ==0 ) { - envp_run = environ; - goto out; - } - - env_old =bpf_num_env_entries (); - env_num = env_old + aux.num_ent +2 ; - env_map = env_old +1 ; - - envp_run =malloc (sizeof (*envp_run) * env_num); -if (!envp_run) { -fprintf (stderr,"bpf: No memory left to allocate env!\n" ); - goto err; - } - -for (i =0 ; i < env_old; i++) - envp_run[i] = environ[i]; - - ret =asprintf (&tmp,"BPF_NUM_MAPS=%u" , aux.num_ent); -if (ret <0 ) - goto err_free; - - envp_run[env_old] = tmp; - -for (i = env_map; i < env_num -1 ; i++) { - ret =asprintf (&tmp,"BPF_MAP%u=%u" , - aux.ent[i - env_map].id, - fds[i - env_map]); -if (ret <0 ) - goto err_free_env; - - envp_run[i] = tmp; - } - - envp_run[env_num -1 ] =NULL ; -out: - ret =execvpe (argv_run[0 ], argv_run, envp_run); -free (envp_run); -return ret; - -err_free_env: -for (--i; i >= env_old; i--) -free (envp_run[i]); -err_free: -free (envp_run); -err: -for (i =0 ; i < aux.num_ent; i++) -close (fds[i]); +explain ();return -1 ; }tc/f_bpf.c +2
-10@@ -27,7 +27,7 @@ static void explain(void)" bytecode-file FILE\n" "\n" "eBPF use case:\n" -" object-file FILE [ section CLS_NAME ] [ export UDS_FILE ]" +" object-file FILE [ section CLS_NAME ]" " [ verbose ] [ direct-action ] [ skip_hw | skip_sw ]\n" " object-pinned FILE [ direct-action ] [ skip_hw | skip_sw ]\n" "\n" @@ -74,7 +74,6 @@ static const struct bpf_cfg_ops bpf_cb_ops = {static int bpf_parse_opt (const struct filter_util *qu,char *handle,int argc,char **argv,struct nlmsghdr *n) { -const char *bpf_obj =NULL , *bpf_uds_name =NULL ;struct tcmsg *t =NLMSG_DATA (n);unsigned int bpf_gen_flags =0 ;unsigned int bpf_flags =0 ;@@ -82,7 +81,6 @@ static int bpf_parse_opt(const struct filter_util *qu, char *handle,bool seen_run = false;bool skip_sw = false;struct rtattr *tail; -int ret =0 ;if (handle) {if (get_u32 (&t->tcm_handle, handle,0 )) {@@ -117,9 +115,6 @@ opt_bpf: argc = cfg.argc; argv = cfg.argv; - - bpf_obj = cfg.object; - bpf_uds_name = cfg.uds; }else if (matches (*argv,"classid" ) ==0 ||matches (*argv,"flowid" ) ==0 ) {unsigned int classid;@@ -181,10 +176,7 @@ opt_bpf: tail->rta_len = (((void *)n) + n->nlmsg_len) - (void *)tail; -if (bpf_uds_name) - ret =bpf_send_map_fds (bpf_uds_name, bpf_obj); - -return ret; +return 0 ; } static int bpf_print_opt(const struct filter_util *qu, FILE *f,tc/m_bpf.c +3
-11@@ -29,7 +29,7 @@ static void explain(void)" bytecode-file FILE\n" "\n" "eBPF use case:\n" -" object-file FILE [ section ACT_NAME ] [ export UDS_FILE ]" +" object-file FILE [ section ACT_NAME ]" " [ verbose ]\n" " object-pinned FILE\n" "\n" @@ -72,12 +72,11 @@ static const struct bpf_cfg_ops bpf_cb_ops = {static int bpf_parse_opt (const struct action_util *a,int *ptr_argc,char ***ptr_argv,int tca_id,struct nlmsghdr *n) { -const char *bpf_obj =NULL , *bpf_uds_name =NULL ;struct tc_act_bpf parm = {};struct bpf_cfg_in cfg = {};bool seen_run = false;struct rtattr *tail; -int argc, ret =0 ; +int argc;char **argv; argv = *ptr_argv;@@ -107,9 +106,6 @@ opt_bpf: argc = cfg.argc; argv = cfg.argv; - - bpf_obj = cfg.object; - bpf_uds_name = cfg.uds; }else if (matches (*argv,"help" ) ==0 ) {explain ();return -1 ;@@ -142,13 +138,10 @@ opt_bpf:addattr_l (n,MAX_MSG ,TCA_ACT_BPF_PARMS , &parm,sizeof (parm));addattr_nest_end (n, tail); -if (bpf_uds_name) - ret =bpf_send_map_fds (bpf_uds_name, bpf_obj); - *ptr_argc = argc; *ptr_argv = argv; -return ret; +return 0 ; }static int bpf_print_opt (const struct action_util *au,FILE *f,struct rtattr *arg) --2.53.0
PATCH v2 4/7 man: tc-bpf: drop references to the removed eBPF agent
In reply to Stephen Hemminger--- man/man8/tc-bpf.8 | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
man/man8/tc-bpf.8 +6 -5
@@ -235,8 +235,9 @@ rather resides in a text file. .SH EXAMPLES .SS eBPF TOOLING -A full blown example including eBPF agent code can be found inside the -iproute2 source package under: +Examples of map sharing through bpffs pinning and of altering classifier +behaviour with tail calls can be found inside the iproute2 source package +under: .B examples/bpf/ As prerequisites, the kernel needs to have the eBPF system call namely
@@ -435,8 +436,8 @@ provides eBPF helper functions that can be called from an eBPF program. This man page will only provide two minimal, stand-alone examples, have a look at .B examples/bpf -from the iproute2 source package for a fully fledged flow dissector -example to better demonstrate some of the possibilities with eBPF. +from the iproute2 source package for further examples demonstrating some +of the possibilities with eBPF. Supported 32 bit classifier return codes from the C program and their meanings: .in +4n
@@ -503,7 +504,7 @@ struct tuple { long bytes; }; -#define BPF_MAP_ID_STATS 1 /* agent's map identifier */ +#define BPF_MAP_ID_STATS 1 /* map identifier */ #define BPF_MAX_MARK 256 struct bpf_elf_map __section("maps") map_stats = {
Signature · 1 line
2.53.0
PATCH v2 5/7 lib/bpf: require libbpf 1.0 and remove legacy ELF loader
In reply to Stephen Hemmingeriproute2 has its own eBPF ELF loader from before libbpf existed. When built with libbpf that loader is bypassed, so there is no reason to keep both.
Make libbpf mandatory and remove the HAVE_LIBBPF and HAVE_ELF conditionals. libbpf 1.0 was released in 2022 and is in every current distribution, so require it and drop the compatibility code for older versions:
- bpf_program__title() fallback for bpf_program__section_name()
- version check for kernel_log_level in open options
- version check gating BPF socket-local storage support in ss
With libbpf 1.0, bpf_object__open_file() returns NULL on error, so check for that instead of using libbpf_get_error().
libbpf 1.0 refuses to open an object that has a "maps" section:
libbpf: elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+
so nothing reaches the code handling struct bpf_elf_map defined maps. Remove the ELF loader and everything that depended on that
section: pinning by PIN_OBJECT_NS and PIN_GLOBAL_NS, the bpf_pinning database, map-in-map setup, and tail call maps filled from "id/key" section names. The relaxed_maps open option went with them, it existed to tolerate the extra fields in those definitions. That was the only user of sha1, so lib/sha1.c goes too.
struct bpf_elf_map itself stays, reduced to the five fields that bpf_graft_map() reads back from /proc/self/fdinfo for its pinned map self-check. It no longer describes any on-disk layout.
libbpf predates the packaging conventions the rest of configure relies on, which is why it had its own --libbpf_dir pointing at a DESTDIR, with a hand built -I/-L and a uname test picking lib64 or lib. It has shipped a pkg-config file for years, with libelf and zlib in Requires.private, so none of that is needed and libbpf is found the same way as every other library here.
That also removes the static link path and with it the LIBBPF_DYNAMIC split: the compile-time and runtime versions could only disagree when libbpf was linked statically from a DESTDIR, so the /proc/self/maps lookup in get_libbpf_version() is now the only case and loses its #ifdef.
Both --libbpf_force and --libbpf_dir are rejected rather than ignored. A build that needs a libbpf outside the default search path can set PKG_CONFIG_PATH. The argument loop has a --*) catch-all that would otherwise accept them and quietly configure something else. Since a missing library is now a hard error, configure also removes a partial config.mk on failure instead of leaving it for the next make.
What is left of bpf_legacy.c is no longer a legacy anything: the loader agnostic front end, the cBPF bytecode parsing, the shared option parser, bpffs mount and work dir handling, graft and the prog info dump. Move it to lib/bpf_util.c, pairing with the include/bpf_util.h that was already its header.
Remove the legacy examples and update the example in tc-bpf(8) to BTF defined maps.
--- configure | 129 +- etc/iproute2/bpf_pinning | 6 - examples/bpf/README | 18 +- examples/bpf/bpf_map_in_map.c | 4 +- examples/bpf/bpf_shared.c | 14 +- examples/bpf/legacy/bpf_cyclic.c | 35 - examples/bpf/legacy/bpf_graft.c | 66 - examples/bpf/legacy/bpf_map_in_map.c | 56 - examples/bpf/legacy/bpf_shared.c | 53 - examples/bpf/legacy/bpf_tailcall.c | 117 - include/bpf_api.h | 7 +- include/bpf_elf.h | 35 +- include/bpf_util.h | 23 +- include/sha1.h | 18 - ip/iplink.c | 4 - lib/Makefile | 10 +- lib/bpf_glue.c | 15 +- lib/bpf_legacy.c | 3093 -------------------------- lib/bpf_libbpf.c | 260 +-- lib/bpf_util.c | 1093 +++++++++ lib/sha1.c | 108 - man/man8/ip-link.8.in | 5 +- man/man8/tc-bpf.8 | 67 +- misc/ss.c | 946 +++++--- 24 files changed, 1865 insertions(+), 4317 deletions(-) delete mode 100644 etc/iproute2/bpf_pinning delete mode 100644 examples/bpf/legacy/bpf_cyclic.c delete mode 100644 examples/bpf/legacy/bpf_graft.c delete mode 100644 examples/bpf/legacy/bpf_map_in_map.c delete mode 100644 examples/bpf/legacy/bpf_shared.c delete mode 100644 examples/bpf/legacy/bpf_tailcall.c delete mode 100644 include/sha1.h delete mode 100644 lib/bpf_legacy.c create mode 100644 lib/bpf_util.c delete mode 100644 lib/sha1.c
configure +25 -104
@@ -12,7 +12,7 @@ CONFIG=config.mk # Make a temp directory in build tree. TMPDIR=$(mktemp -d config.XXXXXX) -trap 'status=$?; rm -rf $TMPDIR; exit $status' EXIT HUP INT QUIT TERM +trap 'status=$?; rm -rf $TMPDIR; [ $status -ne 0 ] && rm -f $CONFIG; exit $status' EXIT HUP INT QUIT TERM check_toolchain() {
@@ -218,13 +218,14 @@ EOF check_elf() { if ${PKG_CONFIG} libelf --exists; then - echo "HAVE_ELF:=y" >>$CONFIG echo "yes" - echo 'CFLAGS += -DHAVE_ELF' "$(${PKG_CONFIG} libelf --cflags)" >> $CONFIG + echo 'CFLAGS += ' "$(${PKG_CONFIG} libelf --cflags)" >> $CONFIG echo 'LDLIBS += ' "$(${PKG_CONFIG} libelf --libs)" >>$CONFIG else echo "no" + echo " libelf is required, install libelf-dev or elfutils-libelf-devel" + exit 1 fi }
@@ -232,10 +233,10 @@ have_libbpf_basic() { cat >$TMPDIR/libbpf_test.c <<EOF #include <bpf/libbpf.h> +#if LIBBPF_MAJOR_VERSION < 1 +#error libbpf 1.0 or later is required +#endif int main(int argc, char **argv) { - bpf_program__set_autoload(NULL, false); - bpf_map__ifindex(NULL); - bpf_map__set_pin_path(NULL, NULL); bpf_object__open_file(NULL, NULL); return 0; }
@@ -248,92 +249,28 @@ EOF return $ret } -have_libbpf_sec_name() -{ - cat >$TMPDIR/libbpf_sec_test.c <<EOF -#include <bpf/libbpf.h> -int main(int argc, char **argv) { - void *ptr; - bpf_program__section_name(NULL); - return 0; -} -EOF - - $CC -o $TMPDIR/libbpf_sec_test $TMPDIR/libbpf_sec_test.c $LIBBPF_CFLAGS $LIBBPF_LDLIBS >/dev/null 2>&1 - local ret=$? - - rm -f $TMPDIR/libbpf_sec_test.c $TMPDIR/libbpf_sec_test - return $ret -} - -check_force_libbpf_on() -{ - # if set LIBBPF_FORCE=on but no libbpf support, just exist the config - # process to make sure we don't build without libbpf. - if [ "$LIBBPF_FORCE" = on ]; then - echo " LIBBPF_FORCE=on set, but couldn't find a usable libbpf" - exit 1 - fi -} - check_libbpf() { - # if set LIBBPF_FORCE=off, disable libbpf entirely - if [ "$LIBBPF_FORCE" = off ]; then + if ! ${PKG_CONFIG} libbpf --exists; then echo "no" - return - fi - - if ! ${PKG_CONFIG} libbpf --exists && [ -z "$LIBBPF_DIR" ] ; then - echo "no" - check_force_libbpf_on - return - fi - - if [ $(uname -m) = x86_64 ]; then - local LIBBPF_LIBDIR="${LIBBPF_DIR}/usr/lib64" - else - local LIBBPF_LIBDIR="${LIBBPF_DIR}/usr/lib" + echo " libbpf is required, install libbpf-dev or libbpf-devel" + echo " or set PKG_CONFIG_PATH to point at a libbpf build" + exit 1 fi - if [ -n "$LIBBPF_DIR" ]; then - LIBBPF_CFLAGS="-I${LIBBPF_DIR}/usr/include" - LIBBPF_LDLIBS="${LIBBPF_LIBDIR}/libbpf.a -lz -lelf" - LIBBPF_VERSION=$(PKG_CONFIG_LIBDIR=${LIBBPF_LIBDIR}/pkgconfig ${PKG_CONFIG} libbpf --modversion) - else - LIBBPF_CFLAGS=$(${PKG_CONFIG} libbpf --cflags) - LIBBPF_LDLIBS=$(${PKG_CONFIG} libbpf --libs) - LIBBPF_VERSION=$(${PKG_CONFIG} libbpf --modversion) - fi + LIBBPF_CFLAGS=$(${PKG_CONFIG} libbpf --cflags) + LIBBPF_LDLIBS=$(${PKG_CONFIG} libbpf --libs) + LIBBPF_VERSION=$(${PKG_CONFIG} libbpf --modversion) if ! have_libbpf_basic; then echo "no" - echo " libbpf version $LIBBPF_VERSION is too low, please update it to at least 0.1.0" - check_force_libbpf_on - return - else - echo "HAVE_LIBBPF:=y" >> $CONFIG - echo 'CFLAGS += -DHAVE_LIBBPF ' $LIBBPF_CFLAGS >> $CONFIG - echo "CFLAGS += -DLIBBPF_VERSION=\\\"$LIBBPF_VERSION\\\"" >> $CONFIG - LIBBPF_MAJOR=$(IFS="."; set $LIBBPF_VERSION; echo $1) - LIBBPF_MINOR=$(IFS="."; set $LIBBPF_VERSION; echo $2) - if [ "$LIBBPF_MAJOR" -eq 0 -a "$LIBBPF_MINOR" -lt 7 ]; then - # Newer libbpf versions provide these defines in the bpf/libbpf_version.h header. - echo "CFLAGS += -DLIBBPF_MAJOR_VERSION=$LIBBPF_MAJOR -DLIBBPF_MINOR_VERSION=$LIBBPF_MINOR" >> $CONFIG - fi - echo 'LDLIBS += ' $LIBBPF_LDLIBS >> $CONFIG - - if [ -z "$LIBBPF_DIR" ]; then - echo "CFLAGS += -DLIBBPF_DYNAMIC" >> $CONFIG - fi + echo " libbpf version $LIBBPF_VERSION is too low, please update it to at least 1.0" + exit 1 fi - # bpf_program__title() is deprecated since libbpf 0.2.0, use - # bpf_program__section_name() instead if we support - if have_libbpf_sec_name; then - echo "HAVE_LIBBPF_SECTION_NAME:=y" >> $CONFIG - echo 'CFLAGS += -DHAVE_LIBBPF_SECTION_NAME ' >> $CONFIG - fi + echo 'CFLAGS += ' $LIBBPF_CFLAGS >> $CONFIG + echo "CFLAGS += -DLIBBPF_VERSION=\\\"$LIBBPF_VERSION\\\"" >> $CONFIG + echo 'LDLIBS += ' $LIBBPF_LDLIBS >> $CONFIG echo "yes" echo " libbpf version $LIBBPF_VERSION"
@@ -494,10 +431,6 @@ Usage: $0 [OPTIONS] always: color output is enabled regardless of stdout state --include_dir <dir> Path to iproute2 include dir --libdir <dir> Path to iproute2 lib dir - --libbpf_dir <dir> Path to libbpf DESTDIR - --libbpf_force <on|off> Enable/disable libbpf by force. Available options: - on: require link against libbpf, quit config if no libbpf support - off: disable libbpf probing --prefix <dir> Path prefix of the lib files to install -h | --help Show this usage info EOF
@@ -525,16 +458,12 @@ else LIBDIR="$1" ;; --libdir=*) LIBDIR="${1#*=}" ;; - --libbpf_dir) - shift - LIBBPF_DIR="$1" ;; - --libbpf_dir=*) - LIBBPF_DIR="${1#*=}" ;; - --libbpf_force) - shift - LIBBPF_FORCE="$1" ;; - --libbpf_force=*) - LIBBPF_FORCE="${1#*=}" ;; + --libbpf_force | --libbpf_force=*) + echo "--libbpf_force is no longer supported, libbpf is required" >&2 + exit 1 ;; + --libbpf_dir | --libbpf_dir=*) + echo "--libbpf_dir is no longer supported, set PKG_CONFIG_PATH instead" >&2 + exit 1 ;; --prefix) shift PREFIX="$1" ;;
@@ -558,14 +487,6 @@ case "$COLOR" in *) usage 1 ;; esac [ -d "$INCLUDE" ] || usage 1 -if [ "${LIBBPF_DIR-unused}" != "unused" ]; then - [ -d "$LIBBPF_DIR" ] || usage 1 -fi -if [ "${LIBBPF_FORCE-unused}" != "unused" ]; then - if [ "$LIBBPF_FORCE" != 'on' ] && [ "$LIBBPF_FORCE" != 'off' ]; then - usage 1 - fi -fi [ -z "$PREFIX" ] && usage 1 [ -z "$LIBDIR" ] && usage 1
etc/iproute2/bpf_pinning deleted +0 -6
@@ -1,6 +0,0 @@ -# -# subpath mappings from mount point for pinning -# -#3 tracing -#4 foo/bar -#5 tc/cls1
examples/bpf/README +8 -10
@@ -1,18 +1,16 @@ eBPF toy code examples (running in kernel) to familiarize yourself with syntax and features: -- BTF defined map examples - bpf_graft.c -> Demo on altering runtime behaviour - bpf_shared.c -> Ingress/egress map sharing example - bpf_map_in_map.c -> Using map in map example -- legacy struct bpf_elf_map defined map examples - - legacy/bpf_shared.c -> Ingress/egress map sharing example - - legacy/bpf_tailcall.c -> Using tail call chains - - legacy/bpf_cyclic.c -> Simple cycle as tail calls - - legacy/bpf_graft.c -> Demo on altering runtime behaviour - - legacy/bpf_map_in_map.c -> Using map in map example +Maps are defined with BTF. Objects using the old struct bpf_elf_map +definitions in a "maps" section are rejected by libbpf. -Note: Users should use new BTF way to defined the maps, the examples -in legacy folder which is using struct bpf_elf_map defined maps is not -recommended. +Build with BTF enabled, which the BTF defined maps require: + + clang -target bpf -O2 -g -c bpf_shared.c -o bpf_shared.o + +Without -g libbpf refuses the object with "BTF is required, but is +missing or corrupted".
examples/bpf/bpf_map_in_map.c +2 -2
@@ -23,7 +23,7 @@ struct { __section("egress")int emain (struct __sk_buff *skb) { -struct bpf_elf_map *map_inner; +void *map_inner;int key =0 , *val; map_inner =map_lookup_elem (&map_outer, &key);
@@ -39,7 +39,7 @@ int emain(struct __sk_buff *skb) __section("ingress")int imain (struct __sk_buff *skb) { -struct bpf_elf_map *map_inner; +void *map_inner;int key =0 , *val; map_inner =map_lookup_elem (&map_outer, &key);
examples/bpf/bpf_shared.c +7 -7
@@ -2,20 +2,20 @@/* Minimal, stand-alone toy map pinning example: * -* clang -target bpf -O2 [...] -o bpf_shared.o -c bpf_shared.c +* clang -target bpf -O2 -g [...] -o bpf_shared.o -c bpf_shared.c * tc filter add dev foo parent 1: bpf obj bpf_shared.o sec egress * tc filter add dev foo parent ffff: bpf obj bpf_shared.o sec ingress * * Both classifier will share the very same map instance in this example, * so map content can be accessed from ingress *and* egress side! * -* This example has a pinning of PIN_OBJECT_NS, so it's private and -* thus shared among various program sections within the object. +* Sections within one object file always refer to the same map, so the +* two programs above would share map_sh even without any pinning. * -* A setting of PIN_GLOBAL_NS would place it into a global namespace, -* so that it can be shared among different object files. A setting -* of PIN_NONE (= 0) means no sharing, so each tc invocation a new map -* instance is being created. +* LIBBPF_PIN_BY_NAME pins the map under /sys/fs/bpf/tc/globals/map_sh, +* which is what lets a *different* object file, or a later tc +* invocation, pick up the same instance. Without it (LIBBPF_PIN_NONE, +* the default) each tc invocation creates a new map. */ struct {
examples/bpf/legacy/bpf_cyclic.c deleted +0 -35
@@ -1,35 +0,0 @@ -#include "../../../include/bpf_api.h" - -/* Cyclic dependency example to test the kernel's runtime upper -* bound on loops. Also demonstrates on how to use direct-actions, -* loaded as: tc filter add [...] bpf da obj [...] -*/ -#define JMP_MAP_ID 0xabccba - -struct bpf_elf_map __section_maps jmp_tc = { - .type =BPF_MAP_TYPE_PROG_ARRAY , - .id =JMP_MAP_ID , - .size_key =sizeof (uint32_t ), - .size_value =sizeof (uint32_t ), - .pinning =PIN_OBJECT_NS , - .max_elem =1 , -}; - -__section_tail(JMP_MAP_ID, 0) -int cls_loop (struct __sk_buff *skb) -{ -printt ("cb: %u\n" , skb->cb[0 ]++); -tail_call (skb, &jmp_tc,0 ); - - skb->tc_classid =TC_H_MAKE (1 ,42 ); -return TC_ACT_OK ; -} - -__section_cls_entry -int cls_entry(struct __sk_buff *skb) -{ -tail_call (skb, &jmp_tc,0 ); -return TC_ACT_SHOT ; -} - -BPF_LICENSE ("GPL" );
examples/bpf/legacy/bpf_graft.c deleted +0 -66
66 lines not on this page · raw message
examples/bpf/legacy/bpf_map_in_map.c deleted +0 -56
56 lines not on this page · raw message
examples/bpf/legacy/bpf_shared.c deleted +0 -53
53 lines not on this page · raw message
examples/bpf/legacy/bpf_tailcall.c deleted +0 -117
117 lines not on this page · raw message
include/bpf_api.h +1 -6
@@ -5,7 +5,7 @@/* Note: * * This file can be included into eBPF kernel programs. It contains -* a couple of useful helper functions, map/section ABI (bpf_elf.h), +* a couple of useful helper functions, section names (bpf_elf.h), * misc macros and some eBPF specific LLVM built-ins. */
@@ -111,11 +111,6 @@ enum libbpf_pin_type { __section(ELF_SECTION_LICENSE)#endif -#ifndef __section_maps -# define __section_maps \ - __section(ELF_SECTION_MAPS) -#endif -/** Declaration helper macros. */ #ifndef BPF_LICENSE
include/bpf_elf.h +7 -28
@@ -6,48 +6,27 @@/* Note: * -* Below ELF section names and bpf_elf_map structure definition -* are not (!) kernel ABI. It's rather a "contract" between the -* application and the BPF loader in tc. For compatibility, the -* section names should stay as-is. Introduction of aliases, if -* needed, are a possibility, though. +* The ELF section names below are the ones the tc front-end looks for +* when picking a program out of an object file. For compatibility, they +* should stay as-is. */ /* ELF section names, etc */ #define ELF_SECTION_LICENSE "license" -#define ELF_SECTION_MAPS "maps"#define ELF_SECTION_PROG "prog"#define ELF_SECTION_CLASSIFIER "classifier"#define ELF_SECTION_ACTION "action" -#define ELF_MAX_MAPS 64 -#define ELF_MAX_LICENSE_LEN 128 - -/* Object pinning settings */ -#define PIN_NONE 0 -#define PIN_OBJECT_NS 1 -#define PIN_GLOBAL_NS 2 - -/* ELF map definition */ +/* Map description used by the pinned map self-check in bpf_graft_map(). +* This is not a kernel ABI and no longer describes any on-disk format; +* it only holds the values read back from /proc/self/fdinfo. +*/ struct bpf_elf_map {__u32 type;__u32 size_key;__u32 size_value;__u32 max_elem;__u32 flags; -__u32 id; -__u32 pinning; -__u32 inner_id; -__u32 inner_idx; }; -#define BPF_ANNOTATE_KV_PAIR (name, type_key, type_val) \ - struct ____btf_map_##name { \ - type_key key; \ - type_val value; \ - }; \ - struct ____btf_map_##name \ - __attribute__ ((section(".maps." #name), used)) \ - ____btf_map_##name = { } -#endif /* __BPF_ELF__ */
include/bpf_util.h +2 -21
@@ -271,34 +271,15 @@ int bpf_program_load(enum bpf_prog_type type, const struct bpf_insn *insns, size_t size_insns, const char *license, char *log, size_t size_log, bool verbose); -int bpf_prog_attach_fd (int prog_fd,int target_fd,enum bpf_attach_type type); -int bpf_prog_detach_fd (int target_fd,enum bpf_attach_type type);int bpf_program_attach (int prog_fd,int target_fd,enum bpf_attach_type type);int bpf_dump_prog_info (FILE *f,uint32_t id);int bpf (int cmd,union bpf_attr *attr,unsigned int size); -#ifdef HAVE_ELF -#ifdef HAVE_LIBBPF -int iproute2_bpf_elf_ctx_init (struct bpf_cfg_in *cfg); -int iproute2_bpf_fetch_ancillary (void ); -int iproute2_get_root_path (char *root_path,size_t len); -bool iproute2_is_pin_map (const char *libbpf_map_name,char *pathname); -bool iproute2_is_map_in_map (const char *libbpf_map_name,struct bpf_elf_map *imap, -struct bpf_elf_map *omap,char *omap_name); -int iproute2_find_map_name_by_id (unsigned int map_id,char *name); +int iproute2_get_root_path (enum bpf_prog_type type,char *root_path, +size_t len);int iproute2_load_libbpf (struct bpf_cfg_in *cfg); -#endif /* HAVE_LIBBPF */ -#else -#ifdef HAVE_LIBBPF -static inline int iproute2_load_libbpf (struct bpf_cfg_in *cfg) -{ -fprintf (stderr,"No ELF library support compiled in.\n" ); -return -1 ; -} -#endif /* HAVE_LIBBPF */ -#endif /* HAVE_ELF */ const char *get_libbpf_version (void );
include/sha1.h deleted +0 -18
@@ -1,18 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-or-later */ -/* -* SHA-1 message digest algorithm -* -* Copyright 2025 Google LLC -*/ -#ifndef __SHA1_H__ -#define __SHA1_H__ - -#include <linux/types.h> -#include <stddef.h> - -#define SHA1_DIGEST_SIZE 20 -#define SHA1_BLOCK_SIZE 64 - -void sha1 (const __u8 *data,size_t len,__u8 out[SHA1_DIGEST_SIZE ]); - -#endif /* __SHA1_H__ */
ip/iplink.c +0 -4
@@ -94,11 +94,7 @@ void iplink_usage(void)" [ node_guid EUI64 ]\n" " [ port_guid EUI64 ] ]\n" " [ { xdp | xdpgeneric | xdpdrv | xdpoffload } { off |\n" -#ifdef HAVE_LIBBPF" object FILE [ { section | program } NAME ] [ verbose ] |\n" -#else -" object FILE [ section NAME ] [ verbose ] |\n" -#endif" pinned FILE } ]\n" " [ master DEVICE ][ vrf NAME ]\n" " [ nomaster ]\n"
lib/Makefile +2 -8
@@ -5,14 +5,8 @@ CFLAGS += -fPIC UTILOBJ = utils.o utils_math.o rt_names.o ll_map.o ll_types.o ll_proto.o ll_addr.o \ inet_proto.o namespace.o json_writer.o json_print.o json_print_math.o \ - names.o color.o bpf_legacy.o bpf_glue.o exec.o fs.o cg_map.o \ - ppp_proto.o bridge.o sha1.o escape.o - -ifeq ($(HAVE_ELF),y) -ifeq ($(HAVE_LIBBPF),y) -UTILOBJ += bpf_libbpf.o -endif -endif + names.o color.o bpf_util.o bpf_glue.o bpf_libbpf.o exec.o fs.o \ + cg_map.o ppp_proto.o bridge.o escape.o ifneq ($(HAVE_SELINUX),y) UTILOBJ += selinux.o
lib/bpf_glue.c +1 -14
@@ -1,6 +1,6 @@/* SPDX-License-Identifier: GPL-2.0 */ /* -* bpf_glue.c: BPF code to call both legacy and libbpf code +* bpf_glue.c: BPF syscall and libbpf wrappers * Authors: Hangbin Liu <[email protected]> * */
@@ -10,9 +10,7 @@#include <errno.h> #include "bpf_util.h" -#ifdef HAVE_LIBBPF #include <bpf/bpf.h> -#endif int bpf (int cmd,union bpf_attr *attr,unsigned int size) {
@@ -27,14 +25,9 @@ int bpf(int cmd, union bpf_attr *attr, unsigned int size)int bpf_program_attach (int prog_fd,int target_fd,enum bpf_attach_type type) { -#ifdef HAVE_LIBBPF return bpf_prog_attach (prog_fd, target_fd, type,0 ); -#else -return bpf_prog_attach_fd (prog_fd, target_fd, type); -#endif } -#ifdef HAVE_LIBBPF static const char *_libbpf_compile_version =LIBBPF_VERSION ;static char _libbpf_version[10 ] = {};
@@ -83,9 +76,3 @@ out: _libbpf_version[sizeof (_libbpf_version)-1 ] ='\0' ;return _libbpf_version; } -#else -const char *get_libbpf_version (void ) -{ -return NULL ; -} -#endif /* HAVE_LIBBPF */
lib/bpf_legacy.c deleted +0 -3093
2,217 lines not on this page · raw message
lib/bpf_libbpf.c +13 -247
260 lines not on this page · raw message
lib/bpf_util.c new file +1093 -0
1,093 lines not on this page · raw message
lib/sha1.c deleted +0 -108
108 lines not on this page · raw message
man/man8/tc-bpf.8 +22 -45
67 lines not on this page · raw message
misc/ss.c +681 -265
946 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.53.0
Part of the diff is not shown here. View the raw message.
PATCH v2 6/7 lib/bpf: check for missing bpf fs mount point
In reply to Stephen Hemmingerbpf_get_work_dir() returns NULL when it cannot provide a usable work directory. It does so even after finding a valid bpffs mount, because bpf_gen_hierarchy() fails if the tc/ subdirectory cannot be
created: running unprivileged against the default mode=700 mount, or as root against a read-only one.
iproute2_get_root_path() passed that NULL straight to snprintf("%s"), which glibc renders as "(null)":
$ tc filter add dev lo parent ffff: bpf obj prog.o sec egress mkdir /sys/fs/bpf/tc/ failed: Permission denied Continuing without mounted eBPF fs. Too old kernel? mkdir (null)/globals failed: No such file or directory Unable to load program
Check for NULL and report it instead. Also check the snprintf() return, since root_path is handed to libbpf as pin_root_path and a silently truncated pin root is worse than a hard failure.
The "Continuing without mounted eBPF fs" warning in bpf_init_env() goes away with it. The legacy loader could carry on without bpffs, which is what that message described, but the only remaining caller needs the pin root and now fails, so the warning no longer matched what happens next. The "Too old kernel?" guess was misleading as
well: the mount is usually present and simply not writable.
Removing the warning also removes the bpf_get_work_dir() call that primed its cache, and the per-program-type subdirectory was only appended on the cached path. Apply it on the first call too, so a cls program keeps pinning under tc/ instead of at the mount root.
--- lib/bpf_util.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-)
lib/bpf_util.c +17 -5
@@ -767,6 +767,11 @@ static const char *bpf_get_work_dir(enum bpf_prog_type type) mnt = bpf_wrk_dir; out: bpf_mnt_cached = true; +if (mnt && type) { +snprintf (bpf_tmp,sizeof (bpf_tmp),"%s%s/" , + mnt,bpf_prog_to_subdir (type)); +return bpf_tmp; + }return mnt; }
@@ -1068,20 +1073,27 @@ static void bpf_init_env(void)/* Don't bother in case we fail! */ setrlimit (RLIMIT_MEMLOCK , &limit); - -if (!bpf_get_work_dir (BPF_PROG_TYPE_UNSPEC )) -fprintf (stderr,"Continuing without mounted eBPF fs. Too old kernel?\n" ); }int iproute2_get_root_path (enum bpf_prog_type type,char *root_path,size_t len) { +const char *wrk_dir;int ret;bpf_init_env (); -snprintf (root_path, len,"%s/%s" , -bpf_get_work_dir (type),BPF_DIR_GLOBALS ); + wrk_dir =bpf_get_work_dir (type); +if (!wrk_dir) { +fprintf (stderr,"No mounted eBPF fs to pin maps under\n" ); +return -1 ; + } + +if ((size_t )snprintf (root_path, len,"%s/%s" , + wrk_dir,BPF_DIR_GLOBALS ) >= len) { +fprintf (stderr,"Pin root path for %s too long\n" , wrk_dir); +return -1 ; + } ret =mkdir (root_path,S_IRWXU );if (ret && errno !=EEXIST ) {
Signature · 1 line
2.53.0
PATCH v2 7/7 testsuite: add tc bpf test
In reply to Stephen HemmingerCovers the paths the BPF front end has no coverage for today: loading a classifier from an object file, the resulting filter output in plain and JSON form, where a cls program's maps get pinned, rejection of an object with a legacy "maps" section, and tc exec bpf graft against a pinned program array.
The pin path assertion is the interesting one. Maps of a cls program pin below the tc/ subdirectory of the bpffs mount, and that only held as a side effect of a cache priming call in bpf_init_env(). Nothing noticed when it stopped happening, because the object still loaded and the filter still attached. Check the full path, not just that the filter came up.
Needs clang with a bpf target and a mountable bpffs, and skips when either is missing rather than failing.
--- testsuite/tests/tc/bpf.t | 153 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100755 testsuite/tests/tc/bpf.t
testsuite/tests/tc/bpf.t new file +153 -0
@@ -0,0 +1,153 @@ +#!/bin/sh +# BPF classifier: object loading, map pinning and graft. +# +# Needs clang with a bpf target to build the test objects, and a +# mountable bpffs for anything that pins. Skips if either is missing. + +. lib/generic.sh + +CLANG="${CLANG:-clang}" + +command -v "$CLANG" >/dev/null 2>&1 || ts_skip +echo 'int f(void) { return 0; }' > "$STD_OUT.c" +$CLANG -target bpf -c "$STD_OUT.c" -o "$STD_OUT.o" 2>/dev/null || ts_skip +rm -f "$STD_OUT.c" "$STD_OUT.o" + +WORK=$(mktemp -d) +BPFFS="$WORK/bpffs" +mkdir -p "$BPFFS" +mount -t bpf bpf "$BPFFS" 2>/dev/null || ts_skip +trap 'umount "$BPFFS" 2>/dev/null; rm -rf "$WORK"' EXIT + +export TC_BPF_MNT="$BPFFS" + +# Headers live next to the test tree, reached via the iproute2 build dir. +SRCDIR=$(cd "$SNAME" && pwd) + +# linux/types.h pulls in asm/types.h, which lives in the multiarch +# directory that a bpf target does not search by default. +MULTIARCH=$(${CC:-cc} -print-multiarch 2>/dev/null) +[ -n "$MULTIARCH" ] && ARCHINC="-I/usr/include/$MULTIARCH" + +build_obj() +{ + $CLANG -target bpf -O2 -g -I"$SRCDIR/include" $ARCHINC \ + -c "$1" -o "$2" 2>/dev/null +} + +cat > "$WORK/cls.c" <<'EOF' +#include "bpf_api.h" + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(key_size, sizeof(uint32_t)); + __uint(value_size, sizeof(uint32_t)); + __uint(max_entries, 1); + __uint(pinning, LIBBPF_PIN_BY_NAME); +} test_map __section(".maps"); + +__section("classifier") +int cls(struct __sk_buff *skb) +{ + return 0; +} + +BPF_LICENSE("GPL"); +EOF + +build_obj "$WORK/cls.c" "$WORK/cls.o" || ts_skip + +DEV="$(rand_dev)" +ts_ip "$0" "Add $DEV dummy interface" link add dev $DEV up type dummy +ts_tc "$0" "Add clsact qdisc" qdisc add dev $DEV clsact + +ts_tc "$0" "Add BPF filter from object file" \ + filter add dev $DEV ingress bpf da obj $WORK/cls.o sec classifier +ts_tc "$0" "Show ingress filters" filter show dev $DEV ingress +test_on "cls.o:\[classifier\]" +test_on "direct-action" + +ts_tc "$0" "Show ingress filters as JSON" -json filter show dev $DEV ingress +test_on "\"bpf_name\":\"cls.o:\[classifier\]\"" + +# A cls program pins below the tc/ subdirectory, not at the mount root. +echo -n "test on: \"map pinned under tc/globals\"" +if [ -e "$BPFFS/tc/globals/test_map" ]; then + pr_success +else + pr_failed +fi + +# libbpf 1.0 and later refuse an object with a legacy "maps" section. +cat > "$WORK/legacy.c" <<'EOF' +#include <linux/bpf.h> + +struct bpf_elf_map { + __u32 type, size_key, size_value, max_elem, flags, id, pinning; +}; + +struct bpf_elf_map __attribute__((section("maps"), used)) old_map = { + .type = BPF_MAP_TYPE_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .max_elem = 1, +}; + +__attribute__((section("classifier"), used)) +int cls(struct __sk_buff *skb) +{ + return 0; +} + +char __attribute__((section("license"), used)) _license[] = "GPL"; +EOF + +if build_obj "$WORK/legacy.c" "$WORK/legacy.o"; then + echo -n "test on: \"legacy maps section rejected\"" + if $TC filter add dev $DEV ingress bpf da obj $WORK/legacy.o \ + sec classifier 2>&1 | grep -q .; then + pr_success + else + pr_failed + fi +fi + +# Graft: load an entry program that tail calls through a pinned prog +# array, then replace the entry in that map from a second object. +cat > "$WORK/graft.c" <<'EOF' +#include "bpf_api.h" + +struct { + __uint(type, BPF_MAP_TYPE_PROG_ARRAY); + __uint(key_size, sizeof(uint32_t)); + __uint(value_size, sizeof(uint32_t)); + __uint(max_entries, 1); + __uint(pinning, LIBBPF_PIN_BY_NAME); +} jmp_tc __section(".maps"); + +__section("aaa") +int cls_aaa(struct __sk_buff *skb) +{ + return 0; +} + +__section_cls_entry +int cls_entry(struct __sk_buff *skb) +{ + tail_call(skb, &jmp_tc, 0); + return BPF_H_DEFAULT; +} + +BPF_LICENSE("GPL"); +EOF + +if build_obj "$WORK/graft.c" "$WORK/graft.o"; then + ts_tc "$0" "Remove clsact qdisc" qdisc del dev $DEV clsact + ts_tc "$0" "Add clsact qdisc" qdisc add dev $DEV clsact + ts_tc "$0" "Add tail call entry program" \ + filter add dev $DEV ingress bpf da obj $WORK/graft.o \ + sec classifier + ts_tc "$0" "Graft section aaa into pinned prog array" \ + exec bpf graft m:globals/jmp_tc key 0 \ + obj $WORK/graft.o sec aaa +fi
Signature · 1 line
2.53.0
Quoted 24 lines · Stephen Hemminger
While looking at OSS Scanner reports noticed a pattern of issues around the BPF loader. The first set related to parsing of mount points with
fscanf("%s").The next part were issues from the legacy BPF loader which is no longer needed. This series rips the band-aid off and related parts no longer needed.
There were also some bugs in error handling found
while changing all this.Note:
lib/bpf_legacy.cbecomeslib/bpf_util.c. "ar rcs" does not drop members that are no longer built, so a stale bpf_legacy.o and sha1.o stay inlib/libutil.aand are picked up by the link. The build still succeeds, but run "make distclean" to be rid of them.The libbpf build options are gone: libbpf is now always required, and pkg-config is the only way it is found. Both --libbpf_force and --libbpf_dir are now rejected rather than silently ignored.
The last patch adds a tc bpf test, there was none before. It caught a regression in this series that the build did not: the tc/ pin subdirectory quietly went missing.
Quoted 9 lines
Since v1: squashed the four libbpf configure patches into one, dropped the
bpf_pinningfallback fix since the loader removal deletes that code anyway, moved the tc-bpf(8) update next to the change it documents, and reworded the export removal after Jamal pointed out that LIBBPF_FORCE=off builds did have a working import/run. Dropped Toke's Reviewed-by from the mount point check:
it now also restores the pin subdirectory, so it is not the patch he reviewed.
fixed a compile error introduced by patch 6 and applied the set to iproute2-next
This series was applied to iproute2/iproute2-next.git (main) by David Ahern <[email protected]>:
Hello:
This series was applied to iproute2/iproute2-next.git (main) by David Ahern <[email protected]>:
Quoted 9 lines · On Thu, 19 Nov 2026 11:02:35 -0800 you wrote:
While looking at OSS Scanner reports noticed a pattern of issues around the BPF loader. The first set related to parsing of mount points with
fscanf("%s").The next part were issues from the legacy BPF loader which is no longer needed. This series rips the band-aid off and related parts no longer needed.
[...]
Here is the summary with links:
- [iproute2-next,v2,1/7] lib/bpf: parse /proc/mounts with getmntent and check fs magic
https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=811d5c6fee81 - [iproute2-next,v2,2/7] lib/fs: parse /proc/mounts with getmntent and check fs magic https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=a472dd902002 - [iproute2-next,v2,3/7] tc: remove eBPF map export and exec bpf import https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=5ba7711088c8 - [iproute2-next,v2,4/7] man: tc-bpf: drop references to the removed eBPF agent https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=6ab6b5582f3a - [iproute2-next,v2,5/7] lib/bpf: require libbpf 1.0 and remove legacy ELF loader https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=ef57368a23ba - [iproute2-next,v2,6/7] lib/bpf: check for missing bpf fs mount point (no matching commit) - [iproute2-next,v2,7/7] testsuite: add tc bpf test https://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git/commit/?id=d462249417a1
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html