Skip to contentSkip to conversation

selftests: drv-net: rss_ctx: add tests for RSS contexts

PATCH Superseded Jakub Kicinski 5 participants 18 messages Jun 20, 2024 – Jun 24, 2024

Subsystems (3)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Jakub Kicinski

author maintainer
#0 lore raw

cover selftests: drv-net: rss_ctx: add tests for RSS contexts

Add a few tests exercising RSS context API.
In addition to basic sanity checks, tests add RSS contexts, n-tuple rule to direct traffic to them (based on dst port), and qstats to make sure traffic landed where we expected.

  $ ./drivers/net/hw/rss_ctx.py
  KTAP version 1
  1..6
  ok 1 rss_ctx.test_rss_key_indir
  ok 2 rss_ctx.test_rss_context
  ok 3 rss_ctx.test_rss_context4
  # Increasing queue count 44 -> 66
  # Failed to create context 32, trying to test what we got
  ok 4 rss_ctx.test_rss_context32 # SKIP Tested only 31 contexts, wanted 32
  ok 5 rss_ctx.test_rss_context_overlap
  ok 6 rss_ctx.test_rss_context_overlap2
  # Totals: pass:5 fail:0 xfail:0 xpass:0 skip:1 error:0

Jakub Kicinski (4):
selftests: drv-net: try to check if port is in use
selftests: drv-net: add helper to wait for HW stats to sync
selftests: drv-net: add ability to wait for at least N packets to load
gen
selftests: drv-net: rss_ctx: add tests for RSS configuration and
contexts

 .../testing/selftests/drivers/net/hw/Makefile |   1 +
 .../selftests/drivers/net/hw/rss_ctx.py       | 243 ++++++++++++++++++
 .../selftests/drivers/net/lib/py/env.py       |  21 +-
 .../selftests/drivers/net/lib/py/load.py      |  33 ++-
 tools/testing/selftests/net/lib/py/ksft.py    |   5 +
 tools/testing/selftests/net/lib/py/utils.py   |  25 +-
 6 files changed, 314 insertions(+), 14 deletions(-)
 create mode 100755 tools/testing/selftests/drivers/net/hw/rss_ctx.py
Signature · 1 line
2.45.2
author maintainer
#1 lore raw

PATCH 1/4 selftests: drv-net: try to check if port is in use

We use random ports for communication. As Willem predicted this leads to occasional failures. Try to check if port is already in use by opening a socket and binding to that port.

---
 tools/testing/selftests/net/lib/py/utils.py | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
tools/testing/selftests/net/lib/py/utils.py +12 -1
index 0540ea24921d..9fa9ec720c89 100644
@@ -3,6 +3,7 @@
 import json as _json
 import random
 import re
+import socket
 import subprocess
 import time
 
@@ -81,7 +82,17 @@ import time
     """
     Get unprivileged port, for now just random, one day we may decide to check if used.
     """
-    return random.randint(10000, 65535)
+    while True:
+        port = random.randint(10000, 65535)
+        try:
+            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            return port
+        except OSError as e:
+            if e.errno != 98:  # already in use
+                raise
 
 
 def wait_port_listen(port, proto="tcp", ns=None, host=None, sleep=0.005, deadline=5):
Signature · 1 line
2.45.2
author maintainer
#5 lore raw

PATCH 2/4 selftests: drv-net: add helper to wait for HW stats to sync

In reply to Jakub Kicinski

Some devices DMA stats to the host periodically. Add a helper which can wait for that to happen, based on frequency reported by the driver in ethtool.

---
 .../selftests/drivers/net/lib/py/env.py       | 21 ++++++++++++++++++-
 tools/testing/selftests/net/lib/py/utils.py   |  4 ++++
 2 files changed, 24 insertions(+), 1 deletion(-)
tools/testing/selftests/drivers/net/lib/py/env.py +20 -1
index edcedd7bffab..34f62002b741 100644
@@ -1,9 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
 
 import os
+import time
 from pathlib import Path
 from lib.py import KsftSkipEx, KsftXfailEx
-from lib.py import cmd, ip
+from lib.py import cmd, ethtool, ip
 from lib.py import NetNS, NetdevSimDev
 from .remote import Remote
 
@@ -82,6 +83,8 @@ from .remote import Remote
 
         self.env = _load_env_file(src_path)
 
+        self._stats_settle_time = None
+
         # Things we try to destroy
         self.remote = None
         # These are for local testing state
@@ -222,3 +225,19 @@ from .remote import Remote
         if remote:
             if not self._require_cmd(comm, "remote"):
                 raise KsftSkipEx("Test requires (remote) command: " + comm)
+
+    def wait_hw_stats_settle(self):
+        """
+        Wait for HW stats to become consistent, some devices DMA HW stats
+        periodically so events won't be reflected until next sync.
+        Good drivers will tell us via ethtool what their sync period is.
+        """
+        if self._stats_settle_time is None:
+            data = ethtool("-c " + self.ifname, json=True)[0]
+            if 'stats-block-usecs' in data:
+                self._stats_settle_time = data['stats-block-usecs'] / 1000 / 1000
+            else:
+                # Assume sync not required, we may use a small (50ms?) sleep
+                # regardless if we see flakiness
+                self._stats_settle_time = 0
+        time.sleep(self._stats_settle_time)
tools/testing/selftests/net/lib/py/utils.py +4 -0
index 9fa9ec720c89..bf8b5e4d9bac 100644
@@ -78,6 +78,10 @@ import time
     return tool('ip', args, json=json, host=host)
 
 
+def ethtool(args, json=None, ns=None, host=None):
+    return tool('ethtool', args,  json=json, ns=ns, host=host)
+
+
 def rand_port():
     """
     Get unprivileged port, for now just random, one day we may decide to check if used.
Signature · 1 line
2.45.2
author maintainer
#8 lore raw

PATCH 3/4 selftests: drv-net: add ability to wait for at least N packets to load gen

In reply to Jakub Kicinski

Teach the load generator how to wait for at least given number of packets to be received. This will be useful for filtering where we'll want to send a non-trivial number of packets and make sure they landed in right queues.

---
 .../selftests/drivers/net/lib/py/load.py      | 26 ++++++++++++++-----
 1 file changed, 19 insertions(+), 7 deletions(-)
tools/testing/selftests/drivers/net/lib/py/load.py +19 -7
index abdb677bdb1c..ae60c438f6c2 100644
@@ -18,15 +18,27 @@ from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen
                                  background=True, host=env.remote)
 
         # Wait for traffic to ramp up
-        pkt = ip("-s link show dev " + env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
+        if not self._wait_pkts(pps=1000):
+            self.stop(verbose=True)
+            raise Exception("iperf3 traffic did not ramp up")
+
+    def _wait_pkts(self, pkt_cnt=None, pps=None):
+        pkt = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
         for _ in range(50):
             time.sleep(0.1)
-            now = ip("-s link show dev " + env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
-            if now - pkt > 1000:
-                return
-            pkt = now
-        self.stop(verbose=True)
-        raise Exception("iperf3 traffic did not ramp up")
+            now = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
+            if pps:
+                if now - pkt > pps / 10:
+                    return True
+                pkt = now
+            elif pkt_cnt:
+                if now - pkt > pkt_cnt:
+                    return True
+        return False
+
+    def wait_pkts_and_stop(self, pkt_cnt):
+        failed = not self._wait_pkts(pkt_cnt=pkt_cnt)
+        self.stop(verbose=failed)
 
     def stop(self, verbose=None):
         self._iperf_client.process(terminate=True)
Signature · 1 line
2.45.2
author maintainer
#10 lore raw

PATCH 4/4 selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Jakub Kicinski

Add tests focusing on indirection table configuration and creating extra RSS contexts in drivers which support it.

  $ ./drivers/net/hw/rss_ctx.py
  KTAP version 1
  1..6
  ok 1 rss_ctx.test_rss_key_indir
  ok 2 rss_ctx.test_rss_context
  ok 3 rss_ctx.test_rss_context4
  # Increasing queue count 44 -> 66
  # Failed to create context 32, trying to test what we got
  ok 4 rss_ctx.test_rss_context32 # SKIP Tested only 31 contexts, wanted 32
  ok 5 rss_ctx.test_rss_context_overlap
  ok 6 rss_ctx.test_rss_context_overlap2
  # Totals: pass:5 fail:0 xfail:0 xpass:0 skip:1 error:0
---
 .../testing/selftests/drivers/net/hw/Makefile |   1 +
 .../selftests/drivers/net/hw/rss_ctx.py       | 243 ++++++++++++++++++
 .../selftests/drivers/net/lib/py/load.py      |   7 +-
 tools/testing/selftests/net/lib/py/ksft.py    |   5 +
 tools/testing/selftests/net/lib/py/utils.py   |   8 +-
 5 files changed, 259 insertions(+), 5 deletions(-)
 create mode 100755 tools/testing/selftests/drivers/net/hw/rss_ctx.py
tools/testing/selftests/drivers/net/hw/Makefile +1 -0
index 4933d045ab66..c9f2f48fc30f 100644
@@ -11,6 +11,7 @@ TEST_PROGS = \
 	hw_stats_l3_gre.sh \
 	loopback.sh \
 	pp_alloc_fail.py \
+	rss_ctx.py \
 	#
 
 TEST_FILES := \
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +243 -0

243 lines not on this page · raw message

tools/testing/selftests/drivers/net/lib/py/load.py +4 -3
index ae60c438f6c2..1de62977433b 100644
@@ -5,13 +5,14 @@ import time
 from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen
 
 class GenerateTraffic:
-    def __init__(self, env):
+    def __init__(self, env, port=None):
         env.require_cmd("iperf3", remote=True)
 
         self.env = env
 
-        port = rand_port()
-        self._iperf_server = cmd(f"iperf3 -s -p {port}", background=True)
+        if port is None:
+            port = rand_port()
+        self._iperf_server = cmd(f"iperf3 -s -1 -p {port}", background=True)
         wait_port_listen(port)
         time.sleep(0.1)
         self._iperf_client = cmd(f"iperf3 -c {env.addr} -P 16 -p {port} -t 86400",
tools/testing/selftests/net/lib/py/ksft.py +5 -0
index 4769b4eb1ea1..91648c5baf40 100644
@@ -57,6 +57,11 @@ KSFT_RESULT_ALL = True
         _fail("Check failed", a, "<", b, comment)
 
 
+def ksft_lt(a, b, comment=""):
+    if a > b:
+        _fail("Check failed", a, ">", b, comment)
+
+
 class ksft_raises:
     def __init__(self, expected_type):
         self.exception = None
tools/testing/selftests/net/lib/py/utils.py +6 -2
index bf8b5e4d9bac..b3ee57a650ae 100644
@@ -8,6 +8,10 @@ import subprocess
 import time
 
 
+class CmdExitFailure(Exception):
+    pass
+
+
 class cmd:
     def __init__(self, comm, shell=True, fail=True, ns=None, background=False, host=None, timeout=5):
         if ns:
@@ -42,8 +46,8 @@ import time
         if self.proc.returncode != 0 and fail:
             if len(stderr) > 0 and stderr[-1] == "\n":
                 stderr = stderr[:-1]
-            raise Exception("Command failed: %s\nSTDOUT: %s\nSTDERR: %s" %
-                            (self.proc.args, stdout, stderr))
+            raise CmdExitFailure("Command failed: %s\nSTDOUT: %s\nSTDERR: %s" %
+                                 (self.proc.args, stdout, stderr))
 
 
 class bkg(cmd):
Signature · 1 line
2.45.2
#9 lore raw

Re: [PATCH net-next 3/4] selftests: drv-net: add ability to wait for at least N packets to load gen

In reply to Jakub Kicinski
Quoted 15 lines · Jakub Kicinski

Teach the load generator how to wait for at least given number of packets to be received. This will be useful for filtering where we'll want to send a non-trivial number of packets and make sure they landed in right queues.

---
 .../selftests/drivers/net/lib/py/load.py      | 26 ++++++++++++++-----
 1 file changed, 19 insertions(+), 7 deletions(-)
tools/testing/selftests/drivers/net/lib/py/load.py +0 -0
index abdb677bdb1c..ae60c438f6c2 100644

tools/testing/selftests/drivers/net/lib/py/load.py from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen · line 25

Quoted 9 lines
tools/testing/selftests/drivers/net/lib/py/load.py +5 -1
@@ -18,15 +18,27 @@ from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen
                                  background=True, host=env.remote)
 
         # Wait for traffic to ramp up
-        pkt = ip("-s link show dev " + env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
+        if not self._wait_pkts(pps=1000):
+            self.stop(verbose=True)
+            raise Exception("iperf3 traffic did not ramp up")
+
+    def _wait_pkts(self, pkt_cnt=None, pps=None):

Do you need to emphasise that pkt_cnt and pps are mutually exclusive?

tools/testing/selftests/drivers/net/lib/py/load.py from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen · line 29

Quoted 10 lines
tools/testing/selftests/drivers/net/lib/py/load.py +2 -6
+        pkt = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
         for _ in range(50):
             time.sleep(0.1)
-            now = ip("-s link show dev " + env.ifname, json=True)[0]["stats64"]["rx"]["packets"]
-            if now - pkt > 1000:
-                return
-            pkt = now
-        self.stop(verbose=True)
-        raise Exception("iperf3 traffic did not ramp up")
+            now = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"]

nit: with duck typing `now' reads like a time value to me. Maybe pkt_start and pkt_now?

Quoted 15 lines
tools/testing/selftests/drivers/net/lib/py/load.py +12 -0
+            if pps:
+                if now - pkt > pps / 10:
+                    return True
+                pkt = now
+            elif pkt_cnt:
+                if now - pkt > pkt_cnt:
+                    return True
+        return False
+
+    def wait_pkts_and_stop(self, pkt_cnt):
+        failed = not self._wait_pkts(pkt_cnt=pkt_cnt)
+        self.stop(verbose=failed)
 
     def stop(self, verbose=None):
         self._iperf_client.process(terminate=True)
#11 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Jakub Kicinski
Quoted 57 lines · Jakub Kicinski

Add tests focusing on indirection table configuration and creating extra RSS contexts in drivers which support it.

  $ ./drivers/net/hw/rss_ctx.py
  KTAP version 1
  1..6
  ok 1 rss_ctx.test_rss_key_indir
  ok 2 rss_ctx.test_rss_context
  ok 3 rss_ctx.test_rss_context4
  # Increasing queue count 44 -> 66
  # Failed to create context 32, trying to test what we got
  ok 4 rss_ctx.test_rss_context32 # SKIP Tested only 31 contexts, wanted 32
  ok 5 rss_ctx.test_rss_context_overlap
  ok 6 rss_ctx.test_rss_context_overlap2
  # Totals: pass:5 fail:0 xfail:0 xpass:0 skip:1 error:0
---
 .../testing/selftests/drivers/net/hw/Makefile |   1 +
 .../selftests/drivers/net/hw/rss_ctx.py       | 243 ++++++++++++++++++
 .../selftests/drivers/net/lib/py/load.py      |   7 +-
 tools/testing/selftests/net/lib/py/ksft.py    |   5 +
 tools/testing/selftests/net/lib/py/utils.py   |   8 +-
 5 files changed, 259 insertions(+), 5 deletions(-)
 create mode 100755 tools/testing/selftests/drivers/net/hw/rss_ctx.py
tools/testing/selftests/drivers/net/hw/Makefile +1 -0
index 4933d045ab66..c9f2f48fc30f 100644
@@ -11,6 +11,7 @@ TEST_PROGS = \
 	hw_stats_l3_gre.sh \
 	loopback.sh \
 	pp_alloc_fail.py \
+	rss_ctx.py \
 	#
 
 TEST_FILES := \
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +13 -0
new file mode 100755
index 000000000000..74d2ca62083f
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+import datetime
+import random
+from lib.py import ksft_run, ksft_pr, ksft_exit, ksft_eq, ksft_ge, ksft_lt
+from lib.py import NetDrvEpEnv
+from lib.py import NetdevFamily
+from lib.py import KsftSkipEx
+from lib.py import rand_port
+from lib.py import ethtool, ip, GenerateTraffic, CmdExitFailure
+
+

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 23

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+def _rss_key_str(key):
+    return ":".join(["{:02x}".format(x) for x in key])
+
+
+def _rss_key_rand(length):
+    return [random.randint(0, 255) for _ in range(length)]
+
+
+def get_rss(cfg):
+    return ethtool(f"-x {cfg.ifname}", json=True)[0]

At this point I think json=True can be the default.

Quoted 59 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +59 -0
+
+
+def ethtool_create(cfg, act, opts):
+    output = ethtool(f"{act} {cfg.ifname} {opts}").stdout
+    # Output will be something like: "New RSS context is 1" or
+    # "Added rule with ID 7", we want the integer from the end
+    return int(output.split()[-1])
+
+
+# Get Rx packet counts for all queues, as a simple list of integers
+# if @prev is specified the prev counts will be subtracted
+def _get_rx_cnts(cfg, prev=None):
+    cfg.wait_hw_stats_settle()
+    data = cfg.netdevnl.qstats_get({"ifindex": cfg.ifindex, "scope": ["queue"]}, dump=True)
+    data = [x for x in data if x['queue-type'] == "rx"]
+    max_q = max([x["queue-id"] for x in data])
+    queue_stats = [0] * (max_q + 1)
+    for q in data:
+        queue_stats[q["queue-id"]] = q["rx-packets"]
+        if prev and q["queue-id"] < len(prev):
+            queue_stats[q["queue-id"]] -= prev[q["queue-id"]]
+    return queue_stats
+
+
+def test_rss_key_indir(cfg):
+    """
+    Test basics like updating the main RSS key and indirection table.
+    """
+    data = get_rss(cfg)
+    want_keys = ['rss-hash-key', 'rss-hash-function', 'rss-indirection-table']
+    for k in want_keys:
+        if k not in data:
+            raise KsftFailEx("ethtool results missing key: " + k)
+        if not data[k]:
+            raise KsftFailEx(f"ethtool results empty for '{k}': {data[k]}")
+
+    key_len = len(data['rss-hash-key'])
+
+    # Set the key
+    key = _rss_key_rand(key_len)
+    ethtool(f"-X {cfg.ifname} hkey " + _rss_key_str(key))
+
+    data = get_rss(cfg)
+    ksft_eq(key, data['rss-hash-key'])
+
+    # Set the indirection table
+    ethtool(f"-X {cfg.ifname} equal 2")
+    data = get_rss(cfg)
+    ksft_eq(0, min(data['rss-indirection-table']))
+    ksft_eq(1, max(data['rss-indirection-table']))
+
+    # Check we only get traffic on the first 2 queues
+    cnts = _get_rx_cnts(cfg)
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # 2 queues, 20k packets, must be at least 5k per queue
+    ksft_ge(cnts[0], 5000, "traffic on main context (1/2): " + str(cnts))
+    ksft_ge(cnts[1], 5000, "traffic on main context (2/2): " + str(cnts))
+    # The other queues should be unused

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 92

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+    ksft_eq(sum(cnts[2:]), 0, "traffic on unused queues: " + str(cnts))
+
+    # Restore, and check traffic gets spread again
+    ethtool(f"-X {cfg.ifname} default")
+
+    cnts = _get_rx_cnts(cfg)
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # First two queues get less traffic than all the rest
+    ksft_ge(sum(cnts[2:]), sum(cnts[:2]), "traffic distributed: " + str(cnts))

Do you need to check the number of queues? If it's 3 then would this check potentially fail?

Quoted 43 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +43 -0
+
+
+def test_rss_context(cfg, ctx_cnt=1):
+    """
+    Test separating traffic into RSS contexts.
+    The queues will be allocated 2 for each context:
+     ctx0  ctx1  ctx2  ctx3
+    [0 1] [2 3] [4 5] [6 7] ...
+    """
+
+    requested_ctx_cnt = ctx_cnt
+
+    # Try to allocate more queues when necessary
+    qcnt = len(_get_rx_cnts(cfg))
+    if qcnt >= 2 + 2 * ctx_cnt:
+        qcnt = None
+    else:
+        try:
+            ksft_pr(f"Increasing queue count {qcnt} -> {2 + 2 * ctx_cnt}")
+            ethtool(f"-L {cfg.ifname} combined {2 + 2 * ctx_cnt}")
+        except:
+            raise KsftSkipEx("Not enough queues for the test")
+
+    ntuple = []
+    ctx_id = []
+    ports = []
+    try:
+        # Use queues 0 and 1 for normal traffic
+        ethtool(f"-X {cfg.ifname} equal 2")
+
+        for i in range(ctx_cnt):
+            try:
+                ctx_id.append(ethtool_create(cfg, "-X", "context new"))
+            except CmdExitFailure:
+                # try to carry on and skip at the end
+                if i == 0:
+                    raise
+                ksft_pr(f"Failed to create context {i + 1}, trying to test what we got")
+                ctx_cnt = i
+                break
+
+            ethtool(f"-X {cfg.ifname} context {ctx_id[i]} start {2 + i * 2} equal 2")
+

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 145

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+            ports.append(rand_port())
+            flow = f"flow-type tcp{cfg.addr_ipver} dst-port {ports[i]} context {ctx_id[i]}"
+            ntuple.append(ethtool_create(cfg, "-N", flow))
+
+        for i in range(ctx_cnt):
+            cnts = _get_rx_cnts(cfg)
+            GenerateTraffic(cfg, port=ports[i]).wait_pkts_and_stop(20000)
+            cnts = _get_rx_cnts(cfg, prev=cnts)
+
+            ksft_lt(sum(cnts[ :2]), 10000, "traffic on main context:" + str(cnts))

What if the host is getting significant traffic during the test?

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 146

Quoted 1 line
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +1 -0
+            ksft_ge(sum(cnts[2+i*2:4+i*2]), 20000, f"traffic on context {i}: " + str(cnts))

Is this exactly 20000?

Quoted 21 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +21 -0
+            ksft_eq(sum(cnts[2:2+i*2] + cnts[4+i*2:]), 0, "traffic on other contexts: " + str(cnts))
+    finally:
+        for nid in ntuple:
+            ethtool(f"-N {cfg.ifname} delete {nid}")
+        for cid in ctx_id:
+            ethtool(f"-X {cfg.ifname} context {cid} delete")
+        ethtool(f"-X {cfg.ifname} default")
+        if qcnt:
+            ethtool(f"-L {cfg.ifname} combined {qcnt}")
+
+    if requested_ctx_cnt != ctx_cnt:
+        raise KsftSkipEx(f"Tested only {ctx_cnt} contexts, wanted {requested_ctx_cnt}")
+
+
+def test_rss_context4(cfg):
+    test_rss_context(cfg, 4)
+
+
+def test_rss_context32(cfg):
+    test_rss_context(cfg, 32)
+

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 177

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+
+def test_rss_context_overlap(cfg, other_ctx=0):
+    """
+    Test contexts overlapping with each other.
+    Use 4 queues for the main context, but only queues 2 and 3 for context 1.
+    """
+    ctx_id = None
+    ntuple = None
+    if other_ctx == 0:
+        ethtool(f"-X {cfg.ifname} equal 4")

What if the queue count < 4?

Quoted 41 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +41 -0
+    else:
+        other_ctx = ethtool_create(cfg, "-X", "context new")
+        ethtool(f"-X {cfg.ifname} context {other_ctx} equal 4")
+
+    try:
+        ctx_id = ethtool_create(cfg, "-X", "context new")
+        ethtool(f"-X {cfg.ifname} context {ctx_id} start 2 equal 2")
+
+        port = rand_port()
+        if other_ctx:
+            flow = f"flow-type tcp{cfg.addr_ipver} dst-port {port} context {other_ctx}"
+            ntuple = ethtool_create(cfg, "-N", flow)
+
+        # Test the main context
+        cnts = _get_rx_cnts(cfg)
+        GenerateTraffic(cfg, port=port).wait_pkts_and_stop(20000)
+        cnts = _get_rx_cnts(cfg, prev=cnts)
+
+        ksft_ge(sum(cnts[ :4]), 20000, "traffic on main context: " + str(cnts))
+        ksft_ge(sum(cnts[ :2]),  7000, "traffic on main context (1/2): " + str(cnts))
+        ksft_ge(sum(cnts[2:4]),  7000, "traffic on main context (2/2): " + str(cnts))
+        if other_ctx == 0:
+            ksft_eq(sum(cnts[4: ]),     0, "traffic on other queues: " + str(cnts))
+
+        # Now create a rule for context 1 and make sure traffic goes to a subset
+        if other_ctx:
+            ethtool(f"-N {cfg.ifname} delete {ntuple}")
+        flow = f"flow-type tcp{cfg.addr_ipver} dst-port {port} context {ctx_id}"
+        ntuple = ethtool_create(cfg, "-N", flow)
+
+        cnts = _get_rx_cnts(cfg)
+        GenerateTraffic(cfg, port=port).wait_pkts_and_stop(20000)
+        cnts = _get_rx_cnts(cfg, prev=cnts)
+
+        ksft_lt(sum(cnts[ :2]),  7000, "traffic on main context: " + str(cnts))
+        ksft_ge(sum(cnts[2:4]), 20000, "traffic on extra context: " + str(cnts))
+        if other_ctx == 0:
+            ksft_eq(sum(cnts[4: ]),     0, "traffic on other queues: " + str(cnts))
+    finally:
+        if ntuple:
+            ethtool(f"-N {cfg.ifname} delete {ntuple}")

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 228

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+        if ctx_id:
+            ethtool(f"-X {cfg.ifname} context {ctx_id} delete")
+        if other_ctx == 0:
+            ethtool(f"-X {cfg.ifname} default")
+        else:
+            ethtool(f"-X {cfg.ifname} context {other_ctx} delete")
+
+
+def test_rss_context_overlap2(cfg):
+    test_rss_context_overlap(cfg, True)

Add a test case for other_ctx=0?

Quoted 79 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +15 -0
+
+
+def main() -> None:
+    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
+        cfg.netdevnl = NetdevFamily()
+
+        ksft_run([test_rss_key_indir, test_rss_context, test_rss_context4,
+                  test_rss_context32, test_rss_context_overlap,
+                  test_rss_context_overlap2],
+                 args=(cfg, ))
+    ksft_exit()
+
+
+if __name__ == "__main__":
+    main()
tools/testing/selftests/drivers/net/lib/py/load.py +4 -3
index ae60c438f6c2..1de62977433b 100644
@@ -5,13 +5,14 @@ import time
 from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen
 
 class GenerateTraffic:
-    def __init__(self, env):
+    def __init__(self, env, port=None):
         env.require_cmd("iperf3", remote=True)
 
         self.env = env
 
-        port = rand_port()
-        self._iperf_server = cmd(f"iperf3 -s -p {port}", background=True)
+        if port is None:
+            port = rand_port()
+        self._iperf_server = cmd(f"iperf3 -s -1 -p {port}", background=True)
         wait_port_listen(port)
         time.sleep(0.1)
         self._iperf_client = cmd(f"iperf3 -c {env.addr} -P 16 -p {port} -t 86400",
tools/testing/selftests/net/lib/py/ksft.py +5 -0
index 4769b4eb1ea1..91648c5baf40 100644
@@ -57,6 +57,11 @@ KSFT_RESULT_ALL = True
         _fail("Check failed", a, "<", b, comment)
 
 
+def ksft_lt(a, b, comment=""):
+    if a > b:
+        _fail("Check failed", a, ">", b, comment)
+
+
 class ksft_raises:
     def __init__(self, expected_type):
         self.exception = None
tools/testing/selftests/net/lib/py/utils.py +6 -2
index bf8b5e4d9bac..b3ee57a650ae 100644
@@ -8,6 +8,10 @@ import subprocess
 import time
 
 
+class CmdExitFailure(Exception):
+    pass
+
+
 class cmd:
     def __init__(self, comm, shell=True, fail=True, ns=None, background=False, host=None, timeout=5):
         if ns:
@@ -42,8 +46,8 @@ import time
         if self.proc.returncode != 0 and fail:
             if len(stderr) > 0 and stderr[-1] == "\n":
                 stderr = stderr[:-1]
-            raise Exception("Command failed: %s\nSTDOUT: %s\nSTDERR: %s" %
-                            (self.proc.args, stdout, stderr))
+            raise CmdExitFailure("Command failed: %s\nSTDOUT: %s\nSTDERR: %s" %
+                                 (self.proc.args, stdout, stderr))
 
 
 class bkg(cmd):
#2 lore raw

Re: [PATCH net-next 1/4] selftests: drv-net: try to check if port is in use

In reply to Jakub Kicinski
Quoted 22 lines · Jakub Kicinski

We use random ports for communication. As Willem predicted this leads to occasional failures. Try to check if port is already in use by opening a socket and binding to that port.

---
 tools/testing/selftests/net/lib/py/utils.py | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
tools/testing/selftests/net/lib/py/utils.py +1 -0
index 0540ea24921d..9fa9ec720c89 100644
@@ -3,6 +3,7 @@
 import json as _json
 import random
 import re
+import socket
 import subprocess
 import time
 

tools/testing/selftests/net/lib/py/utils.py import time · line 83

Quoted 2 lines
tools/testing/selftests/net/lib/py/utils.py +0 -0
@@ -81,7 +82,17 @@ import time
     """
     Get unprivileged port, for now just random, one day we may decide to check if used.

That day is today ;)

Quoted 16 lines
tools/testing/selftests/net/lib/py/utils.py +11 -1
     """
-    return random.randint(10000, 65535)
+    while True:
+        port = random.randint(10000, 65535)
+        try:
+            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            return port
+        except OSError as e:
+            if e.errno != 98:  # already in use
+                raise
 
 
 def wait_port_listen(port, proto="tcp", ns=None, host=None, sleep=0.005, deadline=5):
author maintainer
#12 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to David Wei
Quoted 5 lines · On Thu, 20 Jun 2024 18:52:21 -0700 David Wei wrote:

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 23

Quoted 2 lines · Jakub Kicinski
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +2 -0
+def get_rss(cfg):
+    return ethtool(f"-x {cfg.ifname}", json=True)[0]  

At this point I think json=True can be the default.

for ethtool specifically I'm constantly annoyed by how many sub-commands don't support JSON. I don't think we'll win much, and the grand plan is to have a netlink API for all of this, and switch to YNL calls.

Quoted 8 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 92

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +5 -0
+    cnts = _get_rx_cnts(cfg)
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # First two queues get less traffic than all the rest
+    ksft_ge(sum(cnts[2:]), sum(cnts[:2]), "traffic distributed: " + str(cnts))  

Do you need to check the number of queues? If it's 3 then would this check potentially fail?

Yeah, I lazy'd out, because ethtool -l doesn't support JSON! Ugh. At least on my machine. I'll add the check base on qstat, like I did in one of the later tests.

Quoted 8 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 145

Quoted 6 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +6 -0
+        for i in range(ctx_cnt):
+            cnts = _get_rx_cnts(cfg)
+            GenerateTraffic(cfg, port=ports[i]).wait_pkts_and_stop(20000)
+            cnts = _get_rx_cnts(cfg, prev=cnts)
+
+            ksft_lt(sum(cnts[ :2]), 10000, "traffic on main context:" + str(cnts))  

What if the host is getting significant traffic during the test?

Then IDK how to write a reasonable RSS test :) Hopefully 10k compared to the 20k of iperf is pretty safe, but we'll find out...

Quoted 3 lines
Quoted 1 line

+ ksft_ge(sum(cnts[2+i*2:4+i*2]), 20000, f"traffic on context {i}: " + str(cnts))

Is this exactly 20000?

Not sure I follow but ge means >=, iperf will probably do some more before we manage to stop it.

Quoted 5 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 228

Quoted 3 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +3 -0
+
+def test_rss_context_overlap2(cfg):
+    test_rss_context_overlap(cfg, True)  

Add a test case for other_ctx=0?

context 0 (i.e. the main one) will get tested when called directly. Annoyingly ethtool userspace is a bit picky about using context 0 as an id on the command line, hence the special handling in the test.

#3 lore raw

Re: [PATCH net-next 1/4] selftests: drv-net: try to check if port is in use

In reply to Jakub Kicinski
Quoted 23 lines · Jakub Kicinski

We use random ports for communication. As Willem predicted this leads to occasional failures. Try to check if port is already in use by opening a socket and binding to that port.

---
 tools/testing/selftests/net/lib/py/utils.py | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
tools/testing/selftests/net/lib/py/utils.py +1 -0
index 0540ea24921d..9fa9ec720c89 100644
@@ -3,6 +3,7 @@
 import json as _json
 import random
 import re
+import socket
 import subprocess
 import time
 
@@ -81,7 +82,17 @@ import time
     """

tools/testing/selftests/net/lib/py/utils.py import time · line 91

Quoted 10 lines
tools/testing/selftests/net/lib/py/utils.py +7 -1
     Get unprivileged port, for now just random, one day we may decide to check if used.
     """
-    return random.randint(10000, 65535)
+    while True:
+        port = random.randint(10000, 65535)
+        try:
+            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
+                s.bind(("", port))

Is the separate AF_INET needed? As AF_INET6 is not IPV6_V6ONLY.

The following correctly fails in the second bind

with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s6:
s6.bind(("", 8000))
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s4:
s4.bind(("", 8000))

Quoted 10 lines
tools/testing/selftests/net/lib/py/utils.py +4 -0
+            return port
+        except OSError as e:
+            if e.errno != 98:  # already in use
+                raise
 
 
 def wait_port_listen(port, proto="tcp", ns=None, host=None, sleep=0.005, deadline=5):
Signature · 1 line
2.45.2
#6 lore raw

Re: [PATCH net-next 2/4] selftests: drv-net: add helper to wait for HW stats to sync

In reply to Jakub Kicinski
Quoted 44 lines · Jakub Kicinski

Some devices DMA stats to the host periodically. Add a helper which can wait for that to happen, based on frequency reported by the driver in ethtool.

---
 .../selftests/drivers/net/lib/py/env.py       | 21 ++++++++++++++++++-
 tools/testing/selftests/net/lib/py/utils.py   |  4 ++++
 2 files changed, 24 insertions(+), 1 deletion(-)
tools/testing/selftests/drivers/net/lib/py/env.py +9 -1
index edcedd7bffab..34f62002b741 100644
@@ -1,9 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
 
 import os
+import time
 from pathlib import Path
 from lib.py import KsftSkipEx, KsftXfailEx
-from lib.py import cmd, ip
+from lib.py import cmd, ethtool, ip
 from lib.py import NetNS, NetdevSimDev
 from .remote import Remote
 
@@ -82,6 +83,8 @@ from .remote import Remote
 
         self.env = _load_env_file(src_path)
 
+        self._stats_settle_time = None
+
         # Things we try to destroy
         self.remote = None
         # These are for local testing state
@@ -222,3 +225,19 @@ from .remote import Remote
         if remote:
             if not self._require_cmd(comm, "remote"):
                 raise KsftSkipEx("Test requires (remote) command: " + comm)
+
+    def wait_hw_stats_settle(self):
+        """
+        Wait for HW stats to become consistent, some devices DMA HW stats
+        periodically so events won't be reflected until next sync.

tools/testing/selftests/drivers/net/lib/py/env.py from .remote import Remote · line 242

Quoted 10 lines
tools/testing/selftests/drivers/net/lib/py/env.py +10 -0
+        Good drivers will tell us via ethtool what their sync period is.
+        """
+        if self._stats_settle_time is None:
+            data = ethtool("-c " + self.ifname, json=True)[0]
+            if 'stats-block-usecs' in data:
+                self._stats_settle_time = data['stats-block-usecs'] / 1000 / 1000
+            else:
+                # Assume sync not required, we may use a small (50ms?) sleep
+                # regardless if we see flakiness
+                self._stats_settle_time = 0

Intended to set _stats_settle_time to 0.05 here? Else I don't follow the comment

Quoted 19 lines
tools/testing/selftests/drivers/net/lib/py/env.py +1 -0
+        time.sleep(self._stats_settle_time)
tools/testing/selftests/net/lib/py/utils.py +4 -0
index 9fa9ec720c89..bf8b5e4d9bac 100644
@@ -78,6 +78,10 @@ import time
     return tool('ip', args, json=json, host=host)
 
 
+def ethtool(args, json=None, ns=None, host=None):
+    return tool('ethtool', args,  json=json, ns=ns, host=host)
+
+
 def rand_port():
     """
     Get unprivileged port, for now just random, one day we may decide to check if used.
Signature · 1 line
2.45.2
#13 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Jakub Kicinski
Quoted 92 lines · Jakub Kicinski

Add tests focusing on indirection table configuration and creating extra RSS contexts in drivers which support it.

  $ ./drivers/net/hw/rss_ctx.py
  KTAP version 1
  1..6
  ok 1 rss_ctx.test_rss_key_indir
  ok 2 rss_ctx.test_rss_context
  ok 3 rss_ctx.test_rss_context4
  # Increasing queue count 44 -> 66
  # Failed to create context 32, trying to test what we got
  ok 4 rss_ctx.test_rss_context32 # SKIP Tested only 31 contexts, wanted 32
  ok 5 rss_ctx.test_rss_context_overlap
  ok 6 rss_ctx.test_rss_context_overlap2
  # Totals: pass:5 fail:0 xfail:0 xpass:0 skip:1 error:0
---
 .../testing/selftests/drivers/net/hw/Makefile |   1 +
 .../selftests/drivers/net/hw/rss_ctx.py       | 243 ++++++++++++++++++
 .../selftests/drivers/net/lib/py/load.py      |   7 +-
 tools/testing/selftests/net/lib/py/ksft.py    |   5 +
 tools/testing/selftests/net/lib/py/utils.py   |   8 +-
 5 files changed, 259 insertions(+), 5 deletions(-)
 create mode 100755 tools/testing/selftests/drivers/net/hw/rss_ctx.py
tools/testing/selftests/drivers/net/hw/Makefile +1 -0
index 4933d045ab66..c9f2f48fc30f 100644
@@ -11,6 +11,7 @@ TEST_PROGS = \
 	hw_stats_l3_gre.sh \
 	loopback.sh \
 	pp_alloc_fail.py \
+	rss_ctx.py \
 	#
 
 TEST_FILES := \
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +48 -0
new file mode 100755
index 000000000000..74d2ca62083f
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+import datetime
+import random
+from lib.py import ksft_run, ksft_pr, ksft_exit, ksft_eq, ksft_ge, ksft_lt
+from lib.py import NetDrvEpEnv
+from lib.py import NetdevFamily
+from lib.py import KsftSkipEx
+from lib.py import rand_port
+from lib.py import ethtool, ip, GenerateTraffic, CmdExitFailure
+
+
+def _rss_key_str(key):
+    return ":".join(["{:02x}".format(x) for x in key])
+
+
+def _rss_key_rand(length):
+    return [random.randint(0, 255) for _ in range(length)]
+
+
+def get_rss(cfg):
+    return ethtool(f"-x {cfg.ifname}", json=True)[0]
+
+
+def ethtool_create(cfg, act, opts):
+    output = ethtool(f"{act} {cfg.ifname} {opts}").stdout
+    # Output will be something like: "New RSS context is 1" or
+    # "Added rule with ID 7", we want the integer from the end
+    return int(output.split()[-1])
+
+
+# Get Rx packet counts for all queues, as a simple list of integers
+# if @prev is specified the prev counts will be subtracted
+def _get_rx_cnts(cfg, prev=None):
+    cfg.wait_hw_stats_settle()
+    data = cfg.netdevnl.qstats_get({"ifindex": cfg.ifindex, "scope": ["queue"]}, dump=True)
+    data = [x for x in data if x['queue-type'] == "rx"]
+    max_q = max([x["queue-id"] for x in data])
+    queue_stats = [0] * (max_q + 1)
+    for q in data:
+        queue_stats[q["queue-id"]] = q["rx-packets"]
+        if prev and q["queue-id"] < len(prev):
+            queue_stats[q["queue-id"]] -= prev[q["queue-id"]]
+    return queue_stats
+
+
+def test_rss_key_indir(cfg):

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 58

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+    """
+    Test basics like updating the main RSS key and indirection table.
+    """
+    data = get_rss(cfg)
+    want_keys = ['rss-hash-key', 'rss-hash-function', 'rss-indirection-table']
+    for k in want_keys:
+        if k not in data:
+            raise KsftFailEx("ethtool results missing key: " + k)
+        if not data[k]:
+            raise KsftFailEx(f"ethtool results empty for '{k}': {data[k]}")

No point in printing data[k]?

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 64

Quoted 6 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +6 -0
+
+    key_len = len(data['rss-hash-key'])
+
+    # Set the key
+    key = _rss_key_rand(key_len)
+    ethtool(f"-X {cfg.ifname} hkey " + _rss_key_str(key))

Probably too paranoid, but in case failure is only for some randomized input, is the key logged on error?

Quoted 12 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +12 -0
+
+    data = get_rss(cfg)
+    ksft_eq(key, data['rss-hash-key'])
+
+    # Set the indirection table
+    ethtool(f"-X {cfg.ifname} equal 2")
+    data = get_rss(cfg)
+    ksft_eq(0, min(data['rss-indirection-table']))
+    ksft_eq(1, max(data['rss-indirection-table']))
+
+    # Check we only get traffic on the first 2 queues
+    cnts = _get_rx_cnts(cfg)

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 86

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # 2 queues, 20k packets, must be at least 5k per queue
+    ksft_ge(cnts[0], 5000, "traffic on main context (1/2): " + str(cnts))
+    ksft_ge(cnts[1], 5000, "traffic on main context (2/2): " + str(cnts))
+    # The other queues should be unused
+    ksft_eq(sum(cnts[2:]), 0, "traffic on unused queues: " + str(cnts))
+
+    # Restore, and check traffic gets spread again
+    ethtool(f"-X {cfg.ifname} default")

Consider save and restore state at the start of the test, in case default is overridden at boot.

Not important, but this also repeats some of toeplitz.sh. That has not been integrated into net-drv, and the .c and .sh code is more verbose than this python code. Perhaps can be replaced entirely eventually.

Quoted 42 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +42 -0
+
+    cnts = _get_rx_cnts(cfg)
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # First two queues get less traffic than all the rest
+    ksft_ge(sum(cnts[2:]), sum(cnts[:2]), "traffic distributed: " + str(cnts))
+
+
+def test_rss_context(cfg, ctx_cnt=1):
+    """
+    Test separating traffic into RSS contexts.
+    The queues will be allocated 2 for each context:
+     ctx0  ctx1  ctx2  ctx3
+    [0 1] [2 3] [4 5] [6 7] ...
+    """
+
+    requested_ctx_cnt = ctx_cnt
+
+    # Try to allocate more queues when necessary
+    qcnt = len(_get_rx_cnts(cfg))
+    if qcnt >= 2 + 2 * ctx_cnt:
+        qcnt = None
+    else:
+        try:
+            ksft_pr(f"Increasing queue count {qcnt} -> {2 + 2 * ctx_cnt}")
+            ethtool(f"-L {cfg.ifname} combined {2 + 2 * ctx_cnt}")
+        except:
+            raise KsftSkipEx("Not enough queues for the test")
+
+    ntuple = []
+    ctx_id = []
+    ports = []
+    try:
+        # Use queues 0 and 1 for normal traffic
+        ethtool(f"-X {cfg.ifname} equal 2")
+
+        for i in range(ctx_cnt):
+            try:
+                ctx_id.append(ethtool_create(cfg, "-X", "context new"))
+            except CmdExitFailure:
+                # try to carry on and skip at the end
+                if i == 0:

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 138

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+                    raise
+                ksft_pr(f"Failed to create context {i + 1}, trying to test what we got")
+                ctx_cnt = i
+                break
+
+            ethtool(f"-X {cfg.ifname} context {ctx_id[i]} start {2 + i * 2} equal 2")
+
+            ports.append(rand_port())
+            flow = f"flow-type tcp{cfg.addr_ipver} dst-port {ports[i]} context {ctx_id[i]}"
+            ntuple.append(ethtool_create(cfg, "-N", flow))

Need to test feature ('-k') ntuple and skip test otherwise or set?

Quoted 112 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +105 -0
+
+        for i in range(ctx_cnt):
+            cnts = _get_rx_cnts(cfg)
+            GenerateTraffic(cfg, port=ports[i]).wait_pkts_and_stop(20000)
+            cnts = _get_rx_cnts(cfg, prev=cnts)
+
+            ksft_lt(sum(cnts[ :2]), 10000, "traffic on main context:" + str(cnts))
+            ksft_ge(sum(cnts[2+i*2:4+i*2]), 20000, f"traffic on context {i}: " + str(cnts))
+            ksft_eq(sum(cnts[2:2+i*2] + cnts[4+i*2:]), 0, "traffic on other contexts: " + str(cnts))
+    finally:
+        for nid in ntuple:
+            ethtool(f"-N {cfg.ifname} delete {nid}")
+        for cid in ctx_id:
+            ethtool(f"-X {cfg.ifname} context {cid} delete")
+        ethtool(f"-X {cfg.ifname} default")
+        if qcnt:
+            ethtool(f"-L {cfg.ifname} combined {qcnt}")
+
+    if requested_ctx_cnt != ctx_cnt:
+        raise KsftSkipEx(f"Tested only {ctx_cnt} contexts, wanted {requested_ctx_cnt}")
+
+
+def test_rss_context4(cfg):
+    test_rss_context(cfg, 4)
+
+
+def test_rss_context32(cfg):
+    test_rss_context(cfg, 32)
+
+
+def test_rss_context_overlap(cfg, other_ctx=0):
+    """
+    Test contexts overlapping with each other.
+    Use 4 queues for the main context, but only queues 2 and 3 for context 1.
+    """
+    ctx_id = None
+    ntuple = None
+    if other_ctx == 0:
+        ethtool(f"-X {cfg.ifname} equal 4")
+    else:
+        other_ctx = ethtool_create(cfg, "-X", "context new")
+        ethtool(f"-X {cfg.ifname} context {other_ctx} equal 4")
+
+    try:
+        ctx_id = ethtool_create(cfg, "-X", "context new")
+        ethtool(f"-X {cfg.ifname} context {ctx_id} start 2 equal 2")
+
+        port = rand_port()
+        if other_ctx:
+            flow = f"flow-type tcp{cfg.addr_ipver} dst-port {port} context {other_ctx}"
+            ntuple = ethtool_create(cfg, "-N", flow)
+
+        # Test the main context
+        cnts = _get_rx_cnts(cfg)
+        GenerateTraffic(cfg, port=port).wait_pkts_and_stop(20000)
+        cnts = _get_rx_cnts(cfg, prev=cnts)
+
+        ksft_ge(sum(cnts[ :4]), 20000, "traffic on main context: " + str(cnts))
+        ksft_ge(sum(cnts[ :2]),  7000, "traffic on main context (1/2): " + str(cnts))
+        ksft_ge(sum(cnts[2:4]),  7000, "traffic on main context (2/2): " + str(cnts))
+        if other_ctx == 0:
+            ksft_eq(sum(cnts[4: ]),     0, "traffic on other queues: " + str(cnts))
+
+        # Now create a rule for context 1 and make sure traffic goes to a subset
+        if other_ctx:
+            ethtool(f"-N {cfg.ifname} delete {ntuple}")
+        flow = f"flow-type tcp{cfg.addr_ipver} dst-port {port} context {ctx_id}"
+        ntuple = ethtool_create(cfg, "-N", flow)
+
+        cnts = _get_rx_cnts(cfg)
+        GenerateTraffic(cfg, port=port).wait_pkts_and_stop(20000)
+        cnts = _get_rx_cnts(cfg, prev=cnts)
+
+        ksft_lt(sum(cnts[ :2]),  7000, "traffic on main context: " + str(cnts))
+        ksft_ge(sum(cnts[2:4]), 20000, "traffic on extra context: " + str(cnts))
+        if other_ctx == 0:
+            ksft_eq(sum(cnts[4: ]),     0, "traffic on other queues: " + str(cnts))
+    finally:
+        if ntuple:
+            ethtool(f"-N {cfg.ifname} delete {ntuple}")
+        if ctx_id:
+            ethtool(f"-X {cfg.ifname} context {ctx_id} delete")
+        if other_ctx == 0:
+            ethtool(f"-X {cfg.ifname} default")
+        else:
+            ethtool(f"-X {cfg.ifname} context {other_ctx} delete")
+
+
+def test_rss_context_overlap2(cfg):
+    test_rss_context_overlap(cfg, True)
+
+
+def main() -> None:
+    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
+        cfg.netdevnl = NetdevFamily()
+
+        ksft_run([test_rss_key_indir, test_rss_context, test_rss_context4,
+                  test_rss_context32, test_rss_context_overlap,
+                  test_rss_context_overlap2],
+                 args=(cfg, ))
+    ksft_exit()
+
+
+if __name__ == "__main__":
+    main()
tools/testing/selftests/drivers/net/lib/py/load.py +0 -0
index ae60c438f6c2..1de62977433b 100644
@@ -5,13 +5,14 @@ import time
 from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen
 
#16 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Jakub Kicinski
Quoted 18 lines · Jakub Kicinski

Add tests focusing on indirection table configuration and creating extra RSS contexts in drivers which support it.

  $ ./drivers/net/hw/rss_ctx.py
  KTAP version 1
  1..6
  ok 1 rss_ctx.test_rss_key_indir
  ok 2 rss_ctx.test_rss_context
  ok 3 rss_ctx.test_rss_context4
  # Increasing queue count 44 -> 66
  # Failed to create context 32, trying to test what we got
  ok 4 rss_ctx.test_rss_context32 # SKIP Tested only 31 contexts, wanted 32
  ok 5 rss_ctx.test_rss_context_overlap
  ok 6 rss_ctx.test_rss_context_overlap2
  # Totals: pass:5 fail:0 xfail:0 xpass:0 skip:1 error:0

---

...

Quoted 30 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +30 -0
+def test_rss_context(cfg, ctx_cnt=1):
+    """
+    Test separating traffic into RSS contexts.
+    The queues will be allocated 2 for each context:
+     ctx0  ctx1  ctx2  ctx3
+    [0 1] [2 3] [4 5] [6 7] ...
+    """
+
+    requested_ctx_cnt = ctx_cnt
+
+    # Try to allocate more queues when necessary
+    qcnt = len(_get_rx_cnts(cfg))
+    if qcnt >= 2 + 2 * ctx_cnt:
+        qcnt = None
+    else:
+        try:
+            ksft_pr(f"Increasing queue count {qcnt} -> {2 + 2 * ctx_cnt}")
+            ethtool(f"-L {cfg.ifname} combined {2 + 2 * ctx_cnt}")
+        except:
+            raise KsftSkipEx("Not enough queues for the test")
+
+    ntuple = []
+    ctx_id = []
+    ports = []
+    try:
+        # Use queues 0 and 1 for normal traffic
+        ethtool(f"-X {cfg.ifname} equal 2")
+
+        for i in range(ctx_cnt):
+            try:

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 134

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+                ctx_id.append(ethtool_create(cfg, "-X", "context new"))
+            except CmdExitFailure:
+                # try to carry on and skip at the end
+                if i == 0:
+                    raise
+                ksft_pr(f"Failed to create context {i + 1}, trying to test what we got")
+                ctx_cnt = i
+                break
+
+            ethtool(f"-X {cfg.ifname} context {ctx_id[i]} start {2 + i * 2} equal 2")

Is it worth also testing the single command
f"ethtool -X {cfg.ifname} context new start {2 + i * 2} equal 2"
as that will exercise the kernel & driver slightly differently to first creating a context and then configuring it?

...

tools/testing/selftests/net/lib/py/ksft.py KSFT_RESULT_ALL = True · line 62

Quoted 11 lines
tools/testing/selftests/net/lib/py/ksft.py +3 -0
index 4769b4eb1ea1..91648c5baf40 100644
@@ -57,6 +57,11 @@ KSFT_RESULT_ALL = True
         _fail("Check failed", a, "<", b, comment)
 
 
+def ksft_lt(a, b, comment=""):
+    if a > b:
+        _fail("Check failed", a, ">", b, comment)

AFAICT this implements 'le' (less-or-equal), not 'lt' (less than) as
the name implies.

Apart from that these tests LGTM as far as they go. One thing that I
notice *isn't* tested here, that I generally make a point of testing,
is: add a bunch of contexts (and ntuple filters), remove some of them, then run your traffic and make sure that the ones you left intact still work (and that the deleted ones are actually gone).
Also wonder if it's worth adding tests for 'ethtool -x ... context N'?
You have it for context 0 in test_rss_key_indir(), but on custom contexts it can exercise different code in the kernel.

-ed

#4 lore raw

Re: [PATCH net-next 1/4] selftests: drv-net: try to check if port is in use

In reply to Jakub Kicinski
Quoted 22 lines · Jakub Kicinski

We use random ports for communication. As Willem predicted this leads to occasional failures. Try to check if port is already in use by opening a socket and binding to that port.

---
  tools/testing/selftests/net/lib/py/utils.py | 13 ++++++++++++-
  1 file changed, 12 insertions(+), 1 deletion(-)
tools/testing/selftests/net/lib/py/utils.py +1 -0
index 0540ea24921d..9fa9ec720c89 100644
@@ -3,6 +3,7 @@
  import json as _json
  import random
  import re
+import socket
  import subprocess
  import time
 

tools/testing/selftests/net/lib/py/utils.py import time · line 84

Quoted 3 lines
tools/testing/selftests/net/lib/py/utils.py +0 -0
@@ -81,7 +82,17 @@ import time
      """
      Get unprivileged port, for now just random, one day we may decide to check if used.
      """

nit: this comment could be now updated

tools/testing/selftests/net/lib/py/utils.py import time · line 85

Quoted 2 lines
tools/testing/selftests/net/lib/py/utils.py +1 -1
-    return random.randint(10000, 65535)
+    while True:

nit: perhaps you could limit the loop to some finite number of steps for the case that all ports are in use :P

Quoted 13 lines
tools/testing/selftests/net/lib/py/utils.py +10 -0
+        port = random.randint(10000, 65535)
+        try:
+            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
+                s.bind(("", port))
+            return port
+        except OSError as e:
+            if e.errno != 98:  # already in use
+                raise
 
 
  def wait_port_listen(port, proto="tcp", ns=None, host=None, sleep=0.005, deadline=5):
author maintainer
#7 lore raw

Re: [PATCH net-next 2/4] selftests: drv-net: add helper to wait for HW stats to sync

In reply to Willem de Bruijn
Quoted 7 lines · On Sun, 23 Jun 2024 03:37:19 -0400 Willem de Bruijn wrote:

tools/testing/selftests/drivers/net/lib/py/env.py from .remote import Remote · line 242

Quoted 4 lines
tools/testing/selftests/drivers/net/lib/py/env.py +4 -0
+            else:
+                # Assume sync not required, we may use a small (50ms?) sleep
+                # regardless if we see flakiness
+                self._stats_settle_time = 0  

Intended to set _stats_settle_time to 0.05 here? Else I don't follow the comment

My intuition was that we will need a sleep, but I didn't see failures in practice, so I removed it and added the comment. I'll just bring back the sleep.

author maintainer
#14 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Willem de Bruijn
Quoted 12 lines · On Sun, 23 Jun 2024 04:03:49 -0400 Willem de Bruijn wrote:

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 58

Quoted 11 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +11 -0
+def test_rss_key_indir(cfg):
+    """
+    Test basics like updating the main RSS key and indirection table.
+    """
+    data = get_rss(cfg)
+    want_keys = ['rss-hash-key', 'rss-hash-function', 'rss-indirection-table']
+    for k in want_keys:
+        if k not in data:
+            raise KsftFailEx("ethtool results missing key: " + k)
+        if not data[k]:
+            raise KsftFailEx(f"ethtool results empty for '{k}': {data[k]}")  
Quoted 1 line

No point in printing data[k]?

It can be one of many things which evaluate to False: None, False, [], ""..

Quoted 9 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 64

Quoted 6 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +6 -0
+
+    key_len = len(data['rss-hash-key'])
+
+    # Set the key
+    key = _rss_key_rand(key_len)
+    ethtool(f"-X {cfg.ifname} hkey " + _rss_key_str(key))  

Probably too paranoid, but in case failure is only for some randomized input, is the key logged on error?

Will add!

Quoted 25 lines
Quoted 11 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +11 -0
+    data = get_rss(cfg)
+    ksft_eq(key, data['rss-hash-key'])
+
+    # Set the indirection table
+    ethtool(f"-X {cfg.ifname} equal 2")
+    data = get_rss(cfg)
+    ksft_eq(0, min(data['rss-indirection-table']))
+    ksft_eq(1, max(data['rss-indirection-table']))
+
+    # Check we only get traffic on the first 2 queues
+    cnts = _get_rx_cnts(cfg)

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 86

Quoted 10 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +10 -0
+    GenerateTraffic(cfg).wait_pkts_and_stop(20000)
+    cnts = _get_rx_cnts(cfg, prev=cnts)
+    # 2 queues, 20k packets, must be at least 5k per queue
+    ksft_ge(cnts[0], 5000, "traffic on main context (1/2): " + str(cnts))
+    ksft_ge(cnts[1], 5000, "traffic on main context (2/2): " + str(cnts))
+    # The other queues should be unused
+    ksft_eq(sum(cnts[2:]), 0, "traffic on unused queues: " + str(cnts))
+
+    # Restore, and check traffic gets spread again
+    ethtool(f"-X {cfg.ifname} default")  

Consider save and restore state at the start of the test, in case default is overridden at boot.

Quoted 3 lines

Not important, but this also repeats some of toeplitz.sh. That has not been integrated into net-drv, and the .c and .sh code is more verbose than this python code. Perhaps can be replaced entirely eventually.

Agreed, I went with "default" because there seems to be no ethtool support for setting exact indir table :( I deferred exact restore until we have YNL support for setting, which should be soon.

Quoted 7 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 138

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +5 -0
+            ethtool(f"-X {cfg.ifname} context {ctx_id[i]} start {2 + i * 2} equal 2")
+
+            ports.append(rand_port())
+            flow = f"flow-type tcp{cfg.addr_ipver} dst-port {ports[i]} context {ctx_id[i]}"
+            ntuple.append(ethtool_create(cfg, "-N", flow))  

Need to test feature ('-k') ntuple and skip test otherwise or set?

Will do!

author maintainer
#17 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Edward Cree
Quoted 13 lines · On Mon, 24 Jun 2024 13:55:34 +0100 Edward Cree wrote:
Quoted 13 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +13 -0
+    try:
+        # Use queues 0 and 1 for normal traffic
+        ethtool(f"-X {cfg.ifname} equal 2")
+
+        for i in range(ctx_cnt):
+            try:
+                ctx_id.append(ethtool_create(cfg, "-X", "context new"))
+            except CmdExitFailure:
+                # try to carry on and skip at the end
+                if i == 0:
+                    raise
+                ksft_pr(f"Failed to create context {i + 1}, trying to test what we got")
+                ctx_cnt = i
Quoted 8 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 134

Quoted 3 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +3 -0
+                break
+
+            ethtool(f"-X {cfg.ifname} context {ctx_id[i]} start {2 + i * 2} equal 2")  

Is it worth also testing the single command
f"ethtool -X {cfg.ifname} context new start {2 + i * 2} equal 2"
as that will exercise the kernel & driver slightly differently to first creating a context and then configuring it?

Will add!

Quoted 8 lines
Quoted 8 lines
tools/testing/selftests/net/lib/py/ksft.py +0 -0
index 4769b4eb1ea1..91648c5baf40 100644
@@ -57,6 +57,11 @@ KSFT_RESULT_ALL = True
         _fail("Check failed", a, "<", b, comment)
 
 
Quoted 6 lines

tools/testing/selftests/net/lib/py/ksft.py KSFT_RESULT_ALL = True · line 62

Quoted 3 lines
tools/testing/selftests/net/lib/py/ksft.py +3 -0
+def ksft_lt(a, b, comment=""):
+    if a > b:
+        _fail("Check failed", a, ">", b, comment)  

AFAICT this implements 'le' (less-or-equal), not 'lt' (less than) as
the name implies.

Good catch!

Quoted 5 lines

Apart from that these tests LGTM as far as they go. One thing that I
notice *isn't* tested here, that I generally make a point of testing,
is: add a bunch of contexts (and ntuple filters), remove some of them, then run your traffic and make sure that the ones you left intact still work (and that the deleted ones are actually gone).

Good idea, will add.

Quoted 3 lines

Also wonder if it's worth adding tests for 'ethtool -x ... context N'?
You have it for context 0 in test_rss_key_indir(), but on custom contexts it can exercise different code in the kernel.

Good point, in my head I deferred all "context N read" tests until we have dump, but the simple read test should be added here.

author maintainer
#15 lore raw

Re: [PATCH net-next 4/4] selftests: drv-net: rss_ctx: add tests for RSS configuration and contexts

In reply to Jakub Kicinski
Quoted 10 lines · On Mon, 24 Jun 2024 07:50:35 -0700 Jakub Kicinski wrote:
Quoted 8 lines

tools/testing/selftests/drivers/net/hw/rss_ctx.py line 64

Quoted 5 lines
tools/testing/selftests/drivers/net/hw/rss_ctx.py new file +5 -0
+    key_len = len(data['rss-hash-key'])
+
+    # Set the key
+    key = _rss_key_rand(key_len)
+    ethtool(f"-X {cfg.ifname} hkey " + _rss_key_str(key))    

Probably too paranoid, but in case failure is only for some randomized input, is the key logged on error?

Will add!

I take that back, if ethtool() -> tool() -> cmd() fails we'll throw and exception which already includes the command as well as stdout and stderr. So we'll see in the logs what the key was.