netpoll_basic.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # Author: Breno Leitao <leitao@debian.org>
  4. """
  5. This test aims to evaluate the netpoll polling mechanism (as in
  6. netpoll_poll_dev()). It presents a complex scenario where the network
  7. attempts to send a packet but fails, prompting it to poll the NIC from within
  8. the netpoll TX side.
  9. This has been a crucial path in netpoll that was previously untested. Jakub
  10. suggested using a single RX/TX queue, pushing traffic to the NIC, and then
  11. sending netpoll messages (via netconsole) to trigger the poll.
  12. In parallel, bpftrace is used to detect if netpoll_poll_dev() was called. If
  13. so, the test passes, otherwise it will be skipped. This test is very dependent on
  14. the driver and environment, given we are trying to trigger a tricky scenario.
  15. """
  16. import errno
  17. import logging
  18. import os
  19. import random
  20. import string
  21. import threading
  22. import time
  23. from typing import Optional
  24. from lib.py import (
  25. bpftrace,
  26. CmdExitFailure,
  27. defer,
  28. ethtool,
  29. GenerateTraffic,
  30. ksft_exit,
  31. ksft_pr,
  32. ksft_run,
  33. KsftFailEx,
  34. KsftSkipEx,
  35. NetDrvEpEnv,
  36. KsftXfailEx,
  37. )
  38. # Configure logging
  39. logging.basicConfig(
  40. level=logging.INFO,
  41. format="%(asctime)s - %(levelname)s - %(message)s",
  42. )
  43. NETCONSOLE_CONFIGFS_PATH: str = "/sys/kernel/config/netconsole"
  44. NETCONS_REMOTE_PORT: int = 6666
  45. NETCONS_LOCAL_PORT: int = 1514
  46. # Max number of netcons messages to send. Each iteration will setup
  47. # netconsole and send MAX_WRITES messages
  48. ITERATIONS: int = 20
  49. # Number of writes to /dev/kmsg per iteration
  50. MAX_WRITES: int = 40
  51. # MAPS contains the information coming from bpftrace it will have only one
  52. # key: "hits", which tells the number of times netpoll_poll_dev() was called
  53. MAPS: dict[str, int] = {}
  54. # Thread to run bpftrace in parallel
  55. BPF_THREAD: Optional[threading.Thread] = None
  56. # Time bpftrace will be running in parallel.
  57. BPFTRACE_TIMEOUT: int = 10
  58. def ethtool_get_ringsize(interface_name: str) -> tuple[int, int]:
  59. """
  60. Read the ringsize using ethtool. This will be used to restore it after the test
  61. """
  62. try:
  63. ethtool_result = ethtool(f"-g {interface_name}", json=True)[0]
  64. rxs = ethtool_result["rx"]
  65. txs = ethtool_result["tx"]
  66. except (KeyError, IndexError) as exception:
  67. raise KsftSkipEx(
  68. f"Failed to read RX/TX ringsize: {exception}. Not going to mess with them."
  69. ) from exception
  70. return rxs, txs
  71. def ethtool_set_ringsize(interface_name: str, ring_size: tuple[int, int]) -> bool:
  72. """Try to the number of RX and TX ringsize."""
  73. rxs = ring_size[0]
  74. txs = ring_size[1]
  75. logging.debug("Setting ring size to %d/%d", rxs, txs)
  76. try:
  77. ethtool(f"-G {interface_name} rx {rxs} tx {txs}")
  78. except CmdExitFailure:
  79. # This might fail on real device, retry with a higher value,
  80. # worst case, keep it as it is.
  81. return False
  82. return True
  83. def ethtool_get_queues_cnt(interface_name: str) -> tuple[int, int, int]:
  84. """Read the number of RX, TX and combined queues using ethtool"""
  85. try:
  86. ethtool_result = ethtool(f"-l {interface_name}", json=True)[0]
  87. rxq = ethtool_result.get("rx", -1)
  88. txq = ethtool_result.get("tx", -1)
  89. combined = ethtool_result.get("combined", -1)
  90. except IndexError as exception:
  91. raise KsftSkipEx(
  92. f"Failed to read queues numbers: {exception}. Not going to mess with them."
  93. ) from exception
  94. return rxq, txq, combined
  95. def ethtool_set_queues_cnt(interface_name: str, queues: tuple[int, int, int]) -> None:
  96. """Set the number of RX, TX and combined queues using ethtool"""
  97. rxq, txq, combined = queues
  98. cmdline = f"-L {interface_name}"
  99. if rxq != -1:
  100. cmdline += f" rx {rxq}"
  101. if txq != -1:
  102. cmdline += f" tx {txq}"
  103. if combined != -1:
  104. cmdline += f" combined {combined}"
  105. logging.debug("calling: ethtool %s", cmdline)
  106. try:
  107. ethtool(cmdline)
  108. except CmdExitFailure as exception:
  109. raise KsftSkipEx(
  110. f"Failed to configure RX/TX queues: {exception}. Ethtool not available?"
  111. ) from exception
  112. def netcons_generate_random_target_name() -> str:
  113. """Generate a random target name starting with 'netcons'"""
  114. random_suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
  115. return f"netcons_{random_suffix}"
  116. def netcons_create_target(
  117. config_data: dict[str, str],
  118. target_name: str,
  119. ) -> None:
  120. """Create a netconsole dynamic target against the interfaces"""
  121. logging.debug("Using netconsole name: %s", target_name)
  122. try:
  123. os.makedirs(f"{NETCONSOLE_CONFIGFS_PATH}/{target_name}", exist_ok=True)
  124. logging.debug(
  125. "Created target directory: %s/%s", NETCONSOLE_CONFIGFS_PATH, target_name
  126. )
  127. except OSError as exception:
  128. if exception.errno != errno.EEXIST:
  129. raise KsftFailEx(
  130. f"Failed to create netconsole target directory: {exception}"
  131. ) from exception
  132. try:
  133. for key, value in config_data.items():
  134. path = f"{NETCONSOLE_CONFIGFS_PATH}/{target_name}/{key}"
  135. logging.debug("Writing %s to %s", key, path)
  136. with open(path, "w", encoding="utf-8") as file:
  137. # Always convert to string to write to file
  138. file.write(str(value))
  139. # Read all configuration values for debugging purposes
  140. for debug_key in config_data.keys():
  141. with open(
  142. f"{NETCONSOLE_CONFIGFS_PATH}/{target_name}/{debug_key}",
  143. "r",
  144. encoding="utf-8",
  145. ) as file:
  146. content = file.read()
  147. logging.debug(
  148. "%s/%s/%s : %s",
  149. NETCONSOLE_CONFIGFS_PATH,
  150. target_name,
  151. debug_key,
  152. content.strip(),
  153. )
  154. except Exception as exception:
  155. raise KsftFailEx(
  156. f"Failed to configure netconsole target: {exception}"
  157. ) from exception
  158. def netcons_configure_target(
  159. cfg: NetDrvEpEnv, interface_name: str, target_name: str
  160. ) -> None:
  161. """Configure netconsole on the interface with the given target name"""
  162. config_data = {
  163. "extended": "1",
  164. "dev_name": interface_name,
  165. "local_port": NETCONS_LOCAL_PORT,
  166. "remote_port": NETCONS_REMOTE_PORT,
  167. "local_ip": cfg.addr,
  168. "remote_ip": cfg.remote_addr,
  169. "remote_mac": "00:00:00:00:00:00", # Not important for this test
  170. "enabled": "1",
  171. }
  172. netcons_create_target(config_data, target_name)
  173. logging.debug(
  174. "Created netconsole target: %s on interface %s", target_name, interface_name
  175. )
  176. def netcons_delete_target(name: str) -> None:
  177. """Delete a netconsole dynamic target"""
  178. target_path = f"{NETCONSOLE_CONFIGFS_PATH}/{name}"
  179. try:
  180. if os.path.exists(target_path):
  181. os.rmdir(target_path)
  182. except OSError as exception:
  183. raise KsftFailEx(
  184. f"Failed to delete netconsole target: {exception}"
  185. ) from exception
  186. def netcons_load_module() -> None:
  187. """Try to load the netconsole module"""
  188. os.system("modprobe netconsole")
  189. def bpftrace_call() -> None:
  190. """Call bpftrace to find how many times netpoll_poll_dev() is called.
  191. Output is saved in the global variable `maps`"""
  192. # This is going to update the global variable, that will be seen by the
  193. # main function
  194. global MAPS # pylint: disable=W0603
  195. # This will be passed to bpftrace as in bpftrace -e "expr"
  196. expr = "kprobe:netpoll_poll_dev { @hits = count(); }"
  197. MAPS = bpftrace(expr, timeout=BPFTRACE_TIMEOUT, json=True)
  198. logging.debug("BPFtrace output: %s", MAPS)
  199. def bpftrace_start():
  200. """Start a thread to call `call_bpf` in a parallel thread"""
  201. global BPF_THREAD # pylint: disable=W0603
  202. BPF_THREAD = threading.Thread(target=bpftrace_call)
  203. BPF_THREAD.start()
  204. if not BPF_THREAD.is_alive():
  205. raise KsftSkipEx("BPFtrace thread is not alive. Skipping test")
  206. def bpftrace_stop() -> None:
  207. """Stop the bpftrace thread"""
  208. if BPF_THREAD:
  209. BPF_THREAD.join()
  210. def bpftrace_any_hit(join: bool) -> bool:
  211. """Check if netpoll_poll_dev() was called by checking the global variable `maps`"""
  212. if not BPF_THREAD:
  213. raise KsftFailEx("BPFtrace didn't start")
  214. if BPF_THREAD.is_alive():
  215. if join:
  216. # Wait for bpftrace to finish
  217. BPF_THREAD.join()
  218. else:
  219. # bpftrace is still running, so, we will not check the result yet
  220. return False
  221. logging.debug("MAPS coming from bpftrace = %s", MAPS)
  222. if "hits" not in MAPS.keys():
  223. raise KsftFailEx(f"bpftrace failed to run!?: {MAPS}")
  224. logging.debug("Got a total of %d hits", MAPS["hits"])
  225. return MAPS["hits"] > 0
  226. def do_netpoll_flush_monitored(cfg: NetDrvEpEnv, ifname: str, target_name: str) -> None:
  227. """Print messages to the console, trying to trigger a netpoll poll"""
  228. # Start bpftrace in parallel, so, it is watching
  229. # netpoll_poll_dev() while we are sending netconsole messages
  230. bpftrace_start()
  231. defer(bpftrace_stop)
  232. do_netpoll_flush(cfg, ifname, target_name)
  233. if bpftrace_any_hit(join=True):
  234. ksft_pr("netpoll_poll_dev() was called. Success")
  235. return
  236. raise KsftXfailEx("netpoll_poll_dev() was not called during the test...")
  237. def do_netpoll_flush(cfg: NetDrvEpEnv, ifname: str, target_name: str) -> None:
  238. """Print messages to the console, trying to trigger a netpoll poll"""
  239. netcons_configure_target(cfg, ifname, target_name)
  240. retry = 0
  241. for i in range(int(ITERATIONS)):
  242. if not BPF_THREAD.is_alive() or bpftrace_any_hit(join=False):
  243. # bpftrace is done, stop sending messages
  244. break
  245. msg = f"netcons test #{i}"
  246. with open("/dev/kmsg", "w", encoding="utf-8") as kmsg:
  247. for j in range(MAX_WRITES):
  248. try:
  249. kmsg.write(f"{msg}-{j}\n")
  250. except OSError as exception:
  251. # in some cases, kmsg can be busy, so, we will retry
  252. time.sleep(1)
  253. retry += 1
  254. if retry < 5:
  255. logging.info("Failed to write to kmsg. Retrying")
  256. # Just retry a few times
  257. continue
  258. raise KsftFailEx(
  259. f"Failed to write to kmsg: {exception}"
  260. ) from exception
  261. netcons_delete_target(target_name)
  262. netcons_configure_target(cfg, ifname, target_name)
  263. # If we sleep here, we will have a better chance of triggering
  264. # This number is based on a few tests I ran while developing this test
  265. time.sleep(0.4)
  266. def configure_network(ifname: str) -> None:
  267. """Configure ring size and queue numbers"""
  268. # Set defined queues to 1 to force congestion
  269. prev_queues = ethtool_get_queues_cnt(ifname)
  270. logging.debug("RX/TX/combined queues: %s", prev_queues)
  271. # Only set the queues to 1 if they exists in the device. I.e, they are > 0
  272. ethtool_set_queues_cnt(ifname, tuple(1 if x > 0 else x for x in prev_queues))
  273. defer(ethtool_set_queues_cnt, ifname, prev_queues)
  274. # Try to set the ring size to some low value.
  275. # Do not fail if the hardware do not accepted desired values
  276. prev_ring_size = ethtool_get_ringsize(ifname)
  277. for size in [(1, 1), (128, 128), (256, 256)]:
  278. if ethtool_set_ringsize(ifname, size):
  279. # hardware accepted the desired ringsize
  280. logging.debug("Set RX/TX ringsize to: %s from %s", size, prev_ring_size)
  281. break
  282. defer(ethtool_set_ringsize, ifname, prev_ring_size)
  283. def test_netpoll(cfg: NetDrvEpEnv) -> None:
  284. """
  285. Test netpoll by sending traffic to the interface and then sending
  286. netconsole messages to trigger a poll
  287. """
  288. ifname = cfg.ifname
  289. configure_network(ifname)
  290. target_name = netcons_generate_random_target_name()
  291. traffic = None
  292. try:
  293. traffic = GenerateTraffic(cfg)
  294. do_netpoll_flush_monitored(cfg, ifname, target_name)
  295. finally:
  296. if traffic:
  297. traffic.stop()
  298. # Revert RX/TX queues
  299. netcons_delete_target(target_name)
  300. def test_check_dependencies() -> None:
  301. """Check if the dependencies are met"""
  302. if not os.path.exists(NETCONSOLE_CONFIGFS_PATH):
  303. raise KsftSkipEx(
  304. f"Directory {NETCONSOLE_CONFIGFS_PATH} does not exist. CONFIG_NETCONSOLE_DYNAMIC might not be set." # pylint: disable=C0301
  305. )
  306. def main() -> None:
  307. """Main function to run the test"""
  308. netcons_load_module()
  309. test_check_dependencies()
  310. with NetDrvEpEnv(__file__) as cfg:
  311. ksft_run(
  312. [test_netpoll],
  313. args=(cfg,),
  314. )
  315. ksft_exit()
  316. if __name__ == "__main__":
  317. main()