Path: blob/master/tools/testing/selftests/drivers/net/xdp.py
49639 views
#!/usr/bin/env python31# SPDX-License-Identifier: GPL-2.023"""4This file contains tests to verify native XDP support in network drivers.5The tests utilize the BPF program `xdp_native.bpf.o` from the `selftests.net.lib`6directory, with each test focusing on a specific aspect of XDP functionality.7"""8import random9import string10from dataclasses import dataclass11from enum import Enum1213from lib.py import ksft_run, ksft_exit, ksft_eq, ksft_ge, ksft_ne, ksft_pr14from lib.py import KsftNamedVariant, ksft_variants15from lib.py import KsftFailEx, NetDrvEpEnv16from lib.py import EthtoolFamily, NetdevFamily, NlError17from lib.py import bkg, cmd, rand_port, wait_port_listen18from lib.py import ip, bpftool, defer192021class TestConfig(Enum):22"""Enum for XDP configuration options."""23MODE = 0 # Configures the BPF program for a specific test24PORT = 1 # Port configuration to communicate with the remote host25ADJST_OFFSET = 2 # Tail/Head adjustment offset for extension/shrinking26ADJST_TAG = 3 # Adjustment tag to annotate the start and end of extension272829class XDPAction(Enum):30"""Enum for XDP actions."""31PASS = 0 # Pass the packet up to the stack32DROP = 1 # Drop the packet33TX = 2 # Route the packet to the remote host34TAIL_ADJST = 3 # Adjust the tail of the packet35HEAD_ADJST = 4 # Adjust the head of the packet363738class XDPStats(Enum):39"""Enum for XDP statistics."""40RX = 0 # Count of valid packets received for testing41PASS = 1 # Count of packets passed up to the stack42DROP = 2 # Count of packets dropped43TX = 3 # Count of incoming packets routed to the remote host44ABORT = 4 # Count of packets that were aborted454647@dataclass48class BPFProgInfo:49"""Data class to store information about a BPF program."""50name: str # Name of the BPF program51file: str # BPF program object file52xdp_sec: str = "xdp" # XDP section name (e.g., "xdp" or "xdp.frags")53mtu: int = 1500 # Maximum Transmission Unit, default is 1500545556def _exchg_udp(cfg, port, test_string):57"""58Exchanges UDP packets between a local and remote host using the socat tool.5960Args:61cfg: Configuration object containing network settings.62port: Port number to use for the UDP communication.63test_string: String that the remote host will send.6465Returns:66The string received by the test host.67"""68cfg.require_cmd("socat", remote=True)6970rx_udp_cmd = f"socat -{cfg.addr_ipver} -T 2 -u UDP-RECV:{port},reuseport STDOUT"71tx_udp_cmd = f"echo -n {test_string} | socat -t 2 -u STDIN UDP:{cfg.baddr}:{port}"7273with bkg(rx_udp_cmd, exit_wait=True) as nc:74wait_port_listen(port, proto="udp")75cmd(tx_udp_cmd, host=cfg.remote, shell=True)7677return nc.stdout.strip()787980def _test_udp(cfg, port, size=256):81"""82Tests UDP packet exchange between a local and remote host.8384Args:85cfg: Configuration object containing network settings.86port: Port number to use for the UDP communication.87size: The length of the test string to be exchanged, default is 256 characters.8889Returns:90bool: True if the received string matches the sent string, False otherwise.91"""92test_str = "".join(random.choice(string.ascii_lowercase) for _ in range(size))93recvd_str = _exchg_udp(cfg, port, test_str)9495return recvd_str == test_str969798def _load_xdp_prog(cfg, bpf_info):99"""100Loads an XDP program onto a network interface.101102Args:103cfg: Configuration object containing network settings.104bpf_info: BPFProgInfo object containing information about the BPF program.105106Returns:107dict: A dictionary containing the XDP program ID, name, and associated map IDs.108"""109abs_path = cfg.net_lib_dir / bpf_info.file110prog_info = {}111112cmd(f"ip link set dev {cfg.remote_ifname} mtu {bpf_info.mtu}", shell=True, host=cfg.remote)113defer(ip, f"link set dev {cfg.remote_ifname} mtu 1500", host=cfg.remote)114115cmd(116f"ip link set dev {cfg.ifname} mtu {bpf_info.mtu} xdpdrv obj {abs_path} sec {bpf_info.xdp_sec}",117shell=True118)119defer(ip, f"link set dev {cfg.ifname} mtu 1500 xdpdrv off")120121xdp_info = ip(f"-d link show dev {cfg.ifname}", json=True)[0]122prog_info["id"] = xdp_info["xdp"]["prog"]["id"]123prog_info["name"] = xdp_info["xdp"]["prog"]["name"]124prog_id = prog_info["id"]125126map_ids = bpftool(f"prog show id {prog_id}", json=True)["map_ids"]127prog_info["maps"] = {}128for map_id in map_ids:129name = bpftool(f"map show id {map_id}", json=True)["name"]130prog_info["maps"][name] = map_id131132return prog_info133134135def format_hex_bytes(value):136"""137Helper function that converts an integer into a formatted hexadecimal byte string.138139Args:140value: An integer representing the number to be converted.141142Returns:143A string representing hexadecimal equivalent of value, with bytes separated by spaces.144"""145hex_str = value.to_bytes(4, byteorder='little', signed=True)146return ' '.join(f'{byte:02x}' for byte in hex_str)147148149def _set_xdp_map(map_name, key, value):150"""151Updates an XDP map with a given key-value pair using bpftool.152153Args:154map_name: The name of the XDP map to update.155key: The key to update in the map, formatted as a hexadecimal string.156value: The value to associate with the key, formatted as a hexadecimal string.157"""158key_formatted = format_hex_bytes(key)159value_formatted = format_hex_bytes(value)160bpftool(161f"map update name {map_name} key hex {key_formatted} value hex {value_formatted}"162)163164165def _get_stats(xdp_map_id):166"""167Retrieves and formats statistics from an XDP map.168169Args:170xdp_map_id: The ID of the XDP map from which to retrieve statistics.171172Returns:173A dictionary containing formatted packet statistics for various XDP actions.174The keys are based on the XDPStats Enum values.175176Raises:177KsftFailEx: If the stats retrieval fails.178"""179stats_dump = bpftool(f"map dump id {xdp_map_id}", json=True)180if not stats_dump:181raise KsftFailEx(f"Failed to get stats for map {xdp_map_id}")182183stats_formatted = {}184for key in range(0, 5):185val = stats_dump[key]["formatted"]["value"]186if stats_dump[key]["formatted"]["key"] == XDPStats.RX.value:187stats_formatted[XDPStats.RX.value] = val188elif stats_dump[key]["formatted"]["key"] == XDPStats.PASS.value:189stats_formatted[XDPStats.PASS.value] = val190elif stats_dump[key]["formatted"]["key"] == XDPStats.DROP.value:191stats_formatted[XDPStats.DROP.value] = val192elif stats_dump[key]["formatted"]["key"] == XDPStats.TX.value:193stats_formatted[XDPStats.TX.value] = val194elif stats_dump[key]["formatted"]["key"] == XDPStats.ABORT.value:195stats_formatted[XDPStats.ABORT.value] = val196197return stats_formatted198199200def _test_pass(cfg, bpf_info, msg_sz):201"""202Tests the XDP_PASS action by exchanging UDP packets.203204Args:205cfg: Configuration object containing network settings.206bpf_info: BPFProgInfo object containing information about the BPF program.207msg_sz: Size of the test message to send.208"""209210prog_info = _load_xdp_prog(cfg, bpf_info)211port = rand_port()212213_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, XDPAction.PASS.value)214_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)215216ksft_eq(_test_udp(cfg, port, msg_sz), True, "UDP packet exchange failed")217stats = _get_stats(prog_info["maps"]["map_xdp_stats"])218219ksft_ne(stats[XDPStats.RX.value], 0, "RX stats should not be zero")220ksft_eq(stats[XDPStats.RX.value], stats[XDPStats.PASS.value], "RX and PASS stats mismatch")221222223def test_xdp_native_pass_sb(cfg):224"""225Tests the XDP_PASS action for single buffer case.226227Args:228cfg: Configuration object containing network settings.229"""230bpf_info = BPFProgInfo("xdp_prog", "xdp_native.bpf.o", "xdp", 1500)231232_test_pass(cfg, bpf_info, 256)233234235def test_xdp_native_pass_mb(cfg):236"""237Tests the XDP_PASS action for a multi-buff size.238239Args:240cfg: Configuration object containing network settings.241"""242bpf_info = BPFProgInfo("xdp_prog_frags", "xdp_native.bpf.o", "xdp.frags", 9000)243244_test_pass(cfg, bpf_info, 8000)245246247def _test_drop(cfg, bpf_info, msg_sz):248"""249Tests the XDP_DROP action by exchanging UDP packets.250251Args:252cfg: Configuration object containing network settings.253bpf_info: BPFProgInfo object containing information about the BPF program.254msg_sz: Size of the test message to send.255"""256257prog_info = _load_xdp_prog(cfg, bpf_info)258port = rand_port()259260_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, XDPAction.DROP.value)261_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)262263ksft_eq(_test_udp(cfg, port, msg_sz), False, "UDP packet exchange should fail")264stats = _get_stats(prog_info["maps"]["map_xdp_stats"])265266ksft_ne(stats[XDPStats.RX.value], 0, "RX stats should be zero")267ksft_eq(stats[XDPStats.RX.value], stats[XDPStats.DROP.value], "RX and DROP stats mismatch")268269270def test_xdp_native_drop_sb(cfg):271"""272Tests the XDP_DROP action for a signle-buff case.273274Args:275cfg: Configuration object containing network settings.276"""277bpf_info = BPFProgInfo("xdp_prog", "xdp_native.bpf.o", "xdp", 1500)278279_test_drop(cfg, bpf_info, 256)280281282def test_xdp_native_drop_mb(cfg):283"""284Tests the XDP_DROP action for a multi-buff case.285286Args:287cfg: Configuration object containing network settings.288"""289bpf_info = BPFProgInfo("xdp_prog_frags", "xdp_native.bpf.o", "xdp.frags", 9000)290291_test_drop(cfg, bpf_info, 8000)292293294def _test_xdp_native_tx(cfg, bpf_info, payload_lens):295"""296Tests the XDP_TX action.297298Args:299cfg: Configuration object containing network settings.300bpf_info: BPFProgInfo object containing the BPF program metadata.301payload_lens: Array of packet lengths to send.302"""303cfg.require_cmd("socat", remote=True)304prog_info = _load_xdp_prog(cfg, bpf_info)305port = rand_port()306307_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, XDPAction.TX.value)308_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)309310expected_pkts = 0311for payload_len in payload_lens:312test_string = "".join(313random.choice(string.ascii_lowercase) for _ in range(payload_len)314)315316rx_udp = f"socat -{cfg.addr_ipver} -T 2 " + \317f"-u UDP-RECV:{port},reuseport STDOUT"318319# Writing zero bytes to stdin gets ignored by socat,320# but with the shut-null flag socat generates a zero sized packet321# when the socket is closed.322tx_cmd_suffix = ",shut-null" if payload_len == 0 else ""323tx_udp = f"echo -n {test_string} | socat -t 2 " + \324f"-u STDIN UDP:{cfg.baddr}:{port}{tx_cmd_suffix}"325326with bkg(rx_udp, host=cfg.remote, exit_wait=True) as rnc:327wait_port_listen(port, proto="udp", host=cfg.remote)328cmd(tx_udp, host=cfg.remote, shell=True)329330ksft_eq(rnc.stdout.strip(), test_string, "UDP packet exchange failed")331332expected_pkts += 1333stats = _get_stats(prog_info["maps"]["map_xdp_stats"])334ksft_eq(stats[XDPStats.RX.value], expected_pkts, "RX stats mismatch")335ksft_eq(stats[XDPStats.TX.value], expected_pkts, "TX stats mismatch")336337338def test_xdp_native_tx_sb(cfg):339"""340Tests the XDP_TX action for a single-buff case.341342Args:343cfg: Configuration object containing network settings.344"""345bpf_info = BPFProgInfo("xdp_prog", "xdp_native.bpf.o", "xdp", 1500)346347# Ensure there's enough room for an ETH / IP / UDP header348pkt_hdr_len = 42 if cfg.addr_ipver == "4" else 62349350_test_xdp_native_tx(cfg, bpf_info, [0, 1500 // 2, 1500 - pkt_hdr_len])351352353def test_xdp_native_tx_mb(cfg):354"""355Tests the XDP_TX action for a multi-buff case.356357Args:358cfg: Configuration object containing network settings.359"""360bpf_info = BPFProgInfo("xdp_prog_frags", "xdp_native.bpf.o",361"xdp.frags", 9000)362# The first packet ensures we exercise the fragmented code path.363# And the subsequent 0-sized packet ensures the driver364# reinitializes xdp_buff correctly.365_test_xdp_native_tx(cfg, bpf_info, [8000, 0])366367368def _validate_res(res, offset_lst, pkt_sz_lst):369"""370Validates the result of a test.371372Args:373res: The result of the test, which should be a dictionary with a "status" key.374375Raises:376KsftFailEx: If the test fails to pass any combination of offset and packet size.377"""378if "status" not in res:379raise KsftFailEx("Missing 'status' key in result dictionary")380381# Validate that not a single case was successful382if res["status"] == "fail":383if res["offset"] == offset_lst[0] and res["pkt_sz"] == pkt_sz_lst[0]:384raise KsftFailEx(f"{res['reason']}")385386# Get the previous offset and packet size to report the successful run387tmp_idx = offset_lst.index(res["offset"])388prev_offset = offset_lst[tmp_idx - 1]389if tmp_idx == 0:390tmp_idx = pkt_sz_lst.index(res["pkt_sz"])391prev_pkt_sz = pkt_sz_lst[tmp_idx - 1]392else:393prev_pkt_sz = res["pkt_sz"]394395# Use these values for error reporting396ksft_pr(397f"Failed run: pkt_sz {res['pkt_sz']}, offset {res['offset']}. "398f"Last successful run: pkt_sz {prev_pkt_sz}, offset {prev_offset}. "399f"Reason: {res['reason']}"400)401402403def _check_for_failures(recvd_str, stats):404"""405Checks for common failures while adjusting headroom or tailroom.406407Args:408recvd_str: The string received from the remote host after sending a test string.409stats: A dictionary containing formatted packet statistics for various XDP actions.410411Returns:412str: A string describing the failure reason if a failure is detected, otherwise None.413"""414415# Any adjustment failure result in an abort hence, we track this counter416if stats[XDPStats.ABORT.value] != 0:417return "Adjustment failed"418419# Since we are using aggregate stats for a single test across all offsets and packet sizes420# we can't use RX stats only to track data exchange failure without taking a previous421# snapshot. An easier way is to simply check for non-zero length of received string.422if len(recvd_str) == 0:423return "Data exchange failed"424425# Check for RX and PASS stats mismatch. Ideally, they should be equal for a successful run426if stats[XDPStats.RX.value] != stats[XDPStats.PASS.value]:427return "RX stats mismatch"428429return None430431432def _test_xdp_native_tail_adjst(cfg, pkt_sz_lst, offset_lst):433"""434Tests the XDP tail adjustment functionality.435436This function loads the appropriate XDP program based on the provided437program name and configures the XDP map for tail adjustment. It then438validates the tail adjustment by sending and receiving UDP packets439with specified packet sizes and offsets.440441Args:442cfg: Configuration object containing network settings.443prog: Name of the XDP program to load.444pkt_sz_lst: List of packet sizes to test.445offset_lst: List of offsets to validate support for tail adjustment.446447Returns:448dict: A dictionary with test status and failure details if applicable.449"""450port = rand_port()451bpf_info = BPFProgInfo("xdp_prog_frags", "xdp_native.bpf.o", "xdp.frags", 9000)452453prog_info = _load_xdp_prog(cfg, bpf_info)454455# Configure the XDP map for tail adjustment456_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, XDPAction.TAIL_ADJST.value)457_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)458459for offset in offset_lst:460tag = format(random.randint(65, 90), "02x")461462_set_xdp_map("map_xdp_setup", TestConfig.ADJST_OFFSET.value, offset)463if offset > 0:464_set_xdp_map("map_xdp_setup", TestConfig.ADJST_TAG.value, int(tag, 16))465466for pkt_sz in pkt_sz_lst:467test_str = "".join(random.choice(string.ascii_lowercase) for _ in range(pkt_sz))468recvd_str = _exchg_udp(cfg, port, test_str)469stats = _get_stats(prog_info["maps"]["map_xdp_stats"])470471failure = _check_for_failures(recvd_str, stats)472if failure is not None:473return {474"status": "fail",475"reason": failure,476"offset": offset,477"pkt_sz": pkt_sz,478}479480# Validate data content based on offset direction481expected_data = None482if offset > 0:483expected_data = test_str + (offset * chr(int(tag, 16)))484else:485expected_data = test_str[0:pkt_sz + offset]486487if recvd_str != expected_data:488return {489"status": "fail",490"reason": "Data mismatch",491"offset": offset,492"pkt_sz": pkt_sz,493}494495return {"status": "pass"}496497498def test_xdp_native_adjst_tail_grow_data(cfg):499"""500Tests the XDP tail adjustment by growing packet data.501502Args:503cfg: Configuration object containing network settings.504"""505pkt_sz_lst = [512, 1024, 2048]506offset_lst = [1, 16, 32, 64, 128, 256]507res = _test_xdp_native_tail_adjst(508cfg,509pkt_sz_lst,510offset_lst,511)512513_validate_res(res, offset_lst, pkt_sz_lst)514515516def test_xdp_native_adjst_tail_shrnk_data(cfg):517"""518Tests the XDP tail adjustment by shrinking packet data.519520Args:521cfg: Configuration object containing network settings.522"""523pkt_sz_lst = [512, 1024, 2048]524offset_lst = [-16, -32, -64, -128, -256]525res = _test_xdp_native_tail_adjst(526cfg,527pkt_sz_lst,528offset_lst,529)530531_validate_res(res, offset_lst, pkt_sz_lst)532533534def get_hds_thresh(cfg):535"""536Retrieves the header data split (HDS) threshold for a network interface.537538Args:539cfg: Configuration object containing network settings.540541Returns:542The HDS threshold value. If the threshold is not supported or an error occurs,543a default value of 1500 is returned.544"""545ethnl = cfg.ethnl546hds_thresh = 1500547548try:549rings = ethnl.rings_get({'header': {'dev-index': cfg.ifindex}})550if 'hds-thresh' not in rings:551ksft_pr(f'hds-thresh not supported. Using default: {hds_thresh}')552return hds_thresh553hds_thresh = rings['hds-thresh']554except NlError as e:555ksft_pr(f"Failed to get rings: {e}. Using default: {hds_thresh}")556557return hds_thresh558559560def _test_xdp_native_head_adjst(cfg, prog, pkt_sz_lst, offset_lst):561"""562Tests the XDP head adjustment action for a multi-buffer case.563564Args:565cfg: Configuration object containing network settings.566ethnl: Network namespace or link object (not used in this function).567568This function sets up the packet size and offset lists, then performs569the head adjustment test by sending and receiving UDP packets.570"""571cfg.require_cmd("socat", remote=True)572573prog_info = _load_xdp_prog(cfg, BPFProgInfo(prog, "xdp_native.bpf.o", "xdp.frags", 9000))574port = rand_port()575576_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, XDPAction.HEAD_ADJST.value)577_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)578579hds_thresh = get_hds_thresh(cfg)580for offset in offset_lst:581for pkt_sz in pkt_sz_lst:582# The "head" buffer must contain at least the Ethernet header583# after we eat into it. We send large-enough packets, but if HDS584# is enabled head will only contain headers. Don't try to eat585# more than 28 bytes (UDPv4 + eth hdr left: (14 + 20 + 8) - 14)586l2_cut_off = 28 if cfg.addr_ipver == 4 else 48587if pkt_sz > hds_thresh and offset > l2_cut_off:588ksft_pr(589f"Failed run: pkt_sz ({pkt_sz}) > HDS threshold ({hds_thresh}) and "590f"offset {offset} > {l2_cut_off}"591)592return {"status": "pass"}593594test_str = ''.join(random.choice(string.ascii_lowercase) for _ in range(pkt_sz))595tag = format(random.randint(65, 90), '02x')596597_set_xdp_map("map_xdp_setup",598TestConfig.ADJST_OFFSET.value,599offset)600_set_xdp_map("map_xdp_setup", TestConfig.ADJST_TAG.value, int(tag, 16))601_set_xdp_map("map_xdp_setup", TestConfig.ADJST_OFFSET.value, offset)602603recvd_str = _exchg_udp(cfg, port, test_str)604605# Check for failures around adjustment and data exchange606failure = _check_for_failures(recvd_str, _get_stats(prog_info['maps']['map_xdp_stats']))607if failure is not None:608return {609"status": "fail",610"reason": failure,611"offset": offset,612"pkt_sz": pkt_sz613}614615# Validate data content based on offset direction616expected_data = None617if offset < 0:618expected_data = chr(int(tag, 16)) * (0 - offset) + test_str619else:620expected_data = test_str[offset:]621622if recvd_str != expected_data:623return {624"status": "fail",625"reason": "Data mismatch",626"offset": offset,627"pkt_sz": pkt_sz628}629630return {"status": "pass"}631632633def test_xdp_native_adjst_head_grow_data(cfg):634"""635Tests the XDP headroom growth support.636637Args:638cfg: Configuration object containing network settings.639640This function sets up the packet size and offset lists, then calls the641_test_xdp_native_head_adjst_mb function to perform the actual test. The642test is passed if the headroom is successfully extended for given packet643sizes and offsets.644"""645pkt_sz_lst = [512, 1024, 2048]646647# Negative values result in headroom shrinking, resulting in growing of payload648offset_lst = [-16, -32, -64, -128, -256]649res = _test_xdp_native_head_adjst(cfg, "xdp_prog_frags", pkt_sz_lst, offset_lst)650651_validate_res(res, offset_lst, pkt_sz_lst)652653654def test_xdp_native_adjst_head_shrnk_data(cfg):655"""656Tests the XDP headroom shrinking support.657658Args:659cfg: Configuration object containing network settings.660661This function sets up the packet size and offset lists, then calls the662_test_xdp_native_head_adjst_mb function to perform the actual test. The663test is passed if the headroom is successfully shrunk for given packet664sizes and offsets.665"""666pkt_sz_lst = [512, 1024, 2048]667668# Positive values result in headroom growing, resulting in shrinking of payload669offset_lst = [16, 32, 64, 128, 256]670res = _test_xdp_native_head_adjst(cfg, "xdp_prog_frags", pkt_sz_lst, offset_lst)671672_validate_res(res, offset_lst, pkt_sz_lst)673674675@ksft_variants([676KsftNamedVariant("pass", XDPAction.PASS),677KsftNamedVariant("drop", XDPAction.DROP),678KsftNamedVariant("tx", XDPAction.TX),679])680def test_xdp_native_qstats(cfg, act):681"""682Send 1000 messages. Expect XDP action specified in @act.683Make sure the packets were counted to interface level qstats684(Rx, and Tx if act is TX).685"""686687cfg.require_cmd("socat")688689bpf_info = BPFProgInfo("xdp_prog", "xdp_native.bpf.o", "xdp", 1500)690prog_info = _load_xdp_prog(cfg, bpf_info)691port = rand_port()692693_set_xdp_map("map_xdp_setup", TestConfig.MODE.value, act.value)694_set_xdp_map("map_xdp_setup", TestConfig.PORT.value, port)695696# Discard the input, but we need a listener to avoid ICMP errors697rx_udp = f"socat -{cfg.addr_ipver} -T 2 -u UDP-RECV:{port},reuseport " + \698"/dev/null"699# Listener runs on "remote" in case of XDP_TX700rx_host = cfg.remote if act == XDPAction.TX else None701# We want to spew 1000 packets quickly, bash seems to do a good enough job702# Each reopening of the socket gives us a differenot local port (for RSS)703tx_udp = "for _ in `seq 20`; do " \704f"exec 5<>/dev/udp/{cfg.addr}/{port}; " \705"for i in `seq 50`; do echo a >&5; done; " \706"exec 5>&-; done"707708cfg.wait_hw_stats_settle()709# Qstats have more clearly defined semantics than rtnetlink.710# XDP is the "first layer of the stack" so XDP packets should be counted711# as received and sent as if the decision was made in the routing layer.712before = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True)[0]713714with bkg(rx_udp, host=rx_host, exit_wait=True):715wait_port_listen(port, proto="udp", host=rx_host)716cmd(tx_udp, host=cfg.remote, shell=True)717718cfg.wait_hw_stats_settle()719after = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True)[0]720721expected_pkts = 1000722ksft_ge(after['rx-packets'] - before['rx-packets'], expected_pkts)723if act == XDPAction.TX:724ksft_ge(after['tx-packets'] - before['tx-packets'], expected_pkts)725726stats = _get_stats(prog_info["maps"]["map_xdp_stats"])727ksft_eq(stats[XDPStats.RX.value], expected_pkts, "XDP RX stats mismatch")728if act == XDPAction.TX:729ksft_eq(stats[XDPStats.TX.value], expected_pkts, "XDP TX stats mismatch")730731# Flip the ring count back and forth to make sure the stats from XDP rings732# don't get lost.733chans = cfg.ethnl.channels_get({'header': {'dev-index': cfg.ifindex}})734if chans.get('combined-count', 0) > 1:735cfg.ethnl.channels_set({'header': {'dev-index': cfg.ifindex},736'combined-count': 1})737cfg.ethnl.channels_set({'header': {'dev-index': cfg.ifindex},738'combined-count': chans['combined-count']})739before = after740after = cfg.netnl.qstats_get({"ifindex": cfg.ifindex}, dump=True)[0]741742ksft_ge(after['rx-packets'], before['rx-packets'])743if act == XDPAction.TX:744ksft_ge(after['tx-packets'], before['tx-packets'])745746747def main():748"""749Main function to execute the XDP tests.750751This function runs a series of tests to validate the XDP support for752both the single and multi-buffer. It uses the NetDrvEpEnv context753manager to manage the network driver environment and the ksft_run754function to execute the tests.755"""756with NetDrvEpEnv(__file__) as cfg:757cfg.ethnl = EthtoolFamily()758cfg.netnl = NetdevFamily()759ksft_run(760[761test_xdp_native_pass_sb,762test_xdp_native_pass_mb,763test_xdp_native_drop_sb,764test_xdp_native_drop_mb,765test_xdp_native_tx_sb,766test_xdp_native_tx_mb,767test_xdp_native_adjst_tail_grow_data,768test_xdp_native_adjst_tail_shrnk_data,769test_xdp_native_adjst_head_grow_data,770test_xdp_native_adjst_head_shrnk_data,771test_xdp_native_qstats,772],773args=(cfg,))774ksft_exit()775776777if __name__ == "__main__":778main()779780781