diff mbox series

[bpf-next,1/9] selftests/bpf: Add unshare_netns helper

Message ID 50d0c331d3418c4dcde72bfbce45196c6806c9cc.1715751995.git.tanggeliang@kylinos.cn (mailing list archive)
State New
Headers show
Series add netns helpers | expand

Commit Message

Geliang Tang May 15, 2024, 5:59 a.m. UTC
From: Geliang Tang <tanggeliang@kylinos.cn>

Many BPF selftests create new test network namespaces by using CLONE_NEWNET
flag to unshare the network namespace, so that the calling process is moved
into a new network namespace which is not shared with any previously
existing process. So this patch adds a new helper in network_helpers.c
named unshare_netns(), which create a new network namespace and set the
net device lo up.

Signed-off-by: Geliang Tang <tanggeliang@kylinos.cn>
---
 tools/testing/selftests/bpf/network_helpers.c | 19 +++++++++++++++++++
 tools/testing/selftests/bpf/network_helpers.h |  1 +
 2 files changed, 20 insertions(+)
diff mbox series

Patch

diff --git a/tools/testing/selftests/bpf/network_helpers.c b/tools/testing/selftests/bpf/network_helpers.c
index 35250e6cde7f..919bb2a0c6a6 100644
--- a/tools/testing/selftests/bpf/network_helpers.c
+++ b/tools/testing/selftests/bpf/network_helpers.c
@@ -670,3 +670,22 @@  int send_recv_data(int lfd, int fd, uint32_t total_bytes)
 
 	return err;
 }
+
+int unshare_netns(void)
+{
+	int err;
+
+	err = unshare(CLONE_NEWNET);
+	if (err) {
+		log_err("unshare netns failed");
+		return err;
+	}
+
+	err = SYS_NOFAIL("ip link set dev lo up");
+	if (err) {
+		log_err("set dev lo up failed");
+		return err;
+	}
+
+	return 0;
+}
diff --git a/tools/testing/selftests/bpf/network_helpers.h b/tools/testing/selftests/bpf/network_helpers.h
index 883c7ea9d8d5..b087330f2861 100644
--- a/tools/testing/selftests/bpf/network_helpers.h
+++ b/tools/testing/selftests/bpf/network_helpers.h
@@ -82,6 +82,7 @@  struct nstoken;
 struct nstoken *open_netns(const char *name);
 void close_netns(struct nstoken *token);
 int send_recv_data(int lfd, int fd, uint32_t total_bytes);
+int unshare_netns(void);
 
 static __u16 csum_fold(__u32 csum)
 {