]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
selftests/bpf: move ip checksum helper to network helpers
authorAlexis Lothoré (eBPF Foundation) <alexis.lothore@bootlin.com>
Wed, 20 Nov 2024 07:43:19 +0000 (08:43 +0100)
committerAlexei Starovoitov <ast@kernel.org>
Mon, 2 Dec 2024 16:41:16 +0000 (08:41 -0800)
xdp_metadata test has a small helper computing ipv4 checksums to allow
manually building packets.

Move this helper to network_helpers to share it with other tests.

Signed-off-by: Alexis Lothoré (eBPF Foundation) <alexis.lothore@bootlin.com>
Acked-by: Stanislav Fomichev <sdf@fomichev.me>
Link: https://lore.kernel.org/r/20241120-flow_dissector-v3-9-45b46494f937@bootlin.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
tools/testing/selftests/bpf/network_helpers.h
tools/testing/selftests/bpf/prog_tests/xdp_metadata.c

index 5764155b6d25188ed38e828e1e4a8a08f8a83934..0b2ed90c763fa5a30af348c6faf3d5b6f504aafb 100644 (file)
@@ -105,6 +105,30 @@ static __u16 csum_fold(__u32 csum)
        return (__u16)~csum;
 }
 
+static __wsum csum_partial(const void *buf, int len, __wsum sum)
+{
+       __u16 *p = (__u16 *)buf;
+       int num_u16 = len >> 1;
+       int i;
+
+       for (i = 0; i < num_u16; i++)
+               sum += p[i];
+
+       return sum;
+}
+
+static inline __sum16 build_ip_csum(struct iphdr *iph)
+{
+       __u32 sum = 0;
+       __u16 *p;
+
+       iph->check = 0;
+       p = (void *)iph;
+       sum = csum_partial(p, iph->ihl << 2, 0);
+
+       return csum_fold(sum);
+}
+
 static inline __sum16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
                                        __u32 len, __u8 proto,
                                        __wsum csum)
index c87ee2bf558c1a7fb726cae0aa7b3d3735fb1aac..7f8e161655336127e5bd7a573d1a09db85a92f53 100644 (file)
@@ -133,23 +133,6 @@ static void close_xsk(struct xsk *xsk)
        munmap(xsk->umem_area, UMEM_SIZE);
 }
 
-static void ip_csum(struct iphdr *iph)
-{
-       __u32 sum = 0;
-       __u16 *p;
-       int i;
-
-       iph->check = 0;
-       p = (void *)iph;
-       for (i = 0; i < sizeof(*iph) / sizeof(*p); i++)
-               sum += p[i];
-
-       while (sum >> 16)
-               sum = (sum & 0xffff) + (sum >> 16);
-
-       iph->check = ~sum;
-}
-
 static int generate_packet(struct xsk *xsk, __u16 dst_port)
 {
        struct xsk_tx_metadata *meta;
@@ -192,7 +175,7 @@ static int generate_packet(struct xsk *xsk, __u16 dst_port)
        iph->protocol = IPPROTO_UDP;
        ASSERT_EQ(inet_pton(FAMILY, TX_ADDR, &iph->saddr), 1, "inet_pton(TX_ADDR)");
        ASSERT_EQ(inet_pton(FAMILY, RX_ADDR, &iph->daddr), 1, "inet_pton(RX_ADDR)");
-       ip_csum(iph);
+       iph->check = build_ip_csum(iph);
 
        udph->source = htons(UDP_SOURCE_PORT);
        udph->dest = htons(dst_port);