xref: /linux/tools/testing/selftests/drivers/net/hw/pause.py (revision aca2542b886dc64c4f7c7fe67647ca971d3f0794)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3
4"""
5Driver-related behavior tests for Pause-based Flow Control.
6"""
7
8import errno
9import json
10import os
11
12from lib.py import KsftFailEx, KsftNamedVariant, KsftSkipEx
13from lib.py import NetDrvEpEnv
14from lib.py import cmd, defer, ethtool, ip, wait_file
15from lib.py import ksft_disruptive, ksft_variants, ksft_run
16from lib.py import ksft_eq, ksft_exit, ksft_in, ksft_not_in, ksft_pr
17
18# Linkmodes to Pause params :
19# Pause bit is set if rx == 1
20# Asym_Pause bit is set if rx != tx
21pauseparams_to_linkmodes = {
22    0: {0: {"rx": 0, "tx": 0, "linkmodes": []},
23        1: {"rx": 0, "tx": 1, "linkmodes": ["Asym_Pause"]}},
24    1: {0: {"rx": 1, "tx": 0, "linkmodes": ["Pause", "Asym_Pause"]},
25        1: {"rx": 1, "tx": 1, "linkmodes": ["Pause"]}},
26}
27
28def onoff(val):
29    """ Convert a bool to on/off """
30    return "on" if val else "off"
31
32pauseparams_variants = [
33    KsftNamedVariant(f"RX {onoff(p['rx'])} TX {onoff(p['tx'])}", p)
34    for by_tx in pauseparams_to_linkmodes.values() for p in by_tx.values()
35]
36
37_strerrors = {os.strerror(e): e for e in errno.errorcode}
38
39def ethtool_ret(command, is_get=True, host=None):
40    """ Execute an ethtool command, returns the return code and JSON content
41
42    :param command: the ethtool arguments
43    :param is_get: Is the command a get or a set. Get commands return the loaded
44                   JSON attributes
45    :param host: The host on which to run the command on. None means local host.
46    """
47    json_flag = "--json" if is_get else ""
48    cmd_res = cmd(f"ethtool {json_flag} {command}", host=host, fail=False)
49
50    if cmd_res.ret != 0:
51        # ethtool returns 1 upon error, not the netlink errcode. Try to get it
52        # by parsing the stderr output, which looks like :
53        # "netlink error: Operation not supported"
54        for line in cmd_res.stderr.splitlines():
55            err = _strerrors.get(line.rsplit(": ", 1)[-1].strip())
56            if err:
57                return err, None
58        return cmd_res.ret, None
59
60    # Not a get operation, we don't have any JSON output to parse
61    if not is_get:
62        return 0, None
63
64    return 0, json.loads(cmd_res.stdout)[0]
65
66def wait_for_link(cfg, timeout=15):
67    """ Wait for the link to come up """
68
69    wait_file(f"/sys/class/net/{cfg.ifname}/carrier",
70              lambda x: x.strip() == "1", deadline=timeout)
71
72def wait_for_aneg(cfg, link_drop=False, timeout=15):
73    """ Wait for a renegotiation to complete
74
75    :param link_drop: Set to true if the link HAS to flap.
76    """
77    try:
78        wait_file(f"/sys/class/net/{cfg.ifname}/carrier",
79                  lambda x: x.strip() == "0",
80                  deadline=timeout if link_drop else 2)
81    except TimeoutError:
82        if link_drop:
83            raise
84
85    wait_for_link(cfg, timeout)
86
87def controllable_lp(cfg):
88    """ Whether the remote interface is the link partner of the local one.
89
90    For low level ethtool tests, we need to have the remote directly connected
91    to the local host (i.e. not through a switch).
92
93    This is tested by taking triggering a link renegotiation and checking the
94    carrier_changes counter on the partner.
95
96    :returns: True if the remote is our link partner
97    """
98    controllable = getattr(cfg, "lp_controllable", None)
99    if controllable is not None:
100        return controllable
101
102    before = int(cmd(f"cat /sys/class/net/{cfg.remote_ifname}/carrier_changes",
103                     host=cfg.remote).stdout)
104
105    ret, _ = ethtool_ret(f"-r {cfg.ifname}", is_get=False)
106    if ret != 0:
107        raise KsftSkipEx(f"ethtool -r {cfg.ifname} failed: {errno.errorcode.get(ret, ret)}")
108
109    wait_for_aneg(cfg, link_drop=True)
110
111    cfg.lp_controllable = int(cmd(f"cat /sys/class/net/{cfg.remote_ifname}/carrier_changes",
112                                  host=cfg.remote).stdout) > before
113    return cfg.lp_controllable
114
115def require_controllable_lp(cfg):
116    """ Skip if the remote isn't directly controllable, e.g. accessed through
117        a switch
118    """
119    if not controllable_lp(cfg):
120        raise KsftSkipEx(f"{cfg.remote_ifname} is not directly connected to {cfg.ifname}")
121
122def require_link_autoneg(cfg):
123    """ Skip if local or remote device don't support link aneg """
124    # Does local device support link aneg
125    if not ethtool(f"{cfg.ifname}", json=True)[0]["supports-auto-negotiation"]:
126        raise KsftSkipEx(f"{cfg.ifname} doesn't support link autoneg")
127
128    # Does remote device support link aneg
129    if not ethtool(f"{cfg.remote_ifname}",
130                   json=True, host=cfg.remote)[0]["supports-auto-negotiation"]:
131        raise KsftSkipEx(f"Remote {cfg.remote_ifname} doesn't support link autoneg")
132
133def forced_link_settings(cfg):
134    """ Returns a string to pass to ethtool -s with speed/duplex corresponding
135        to the current settings.
136
137        Note that some devices don't return duplex info, so assume full duplex
138        in that case.
139    """
140    link = ethtool(f"{cfg.ifname}", json=True)[0]
141    if "speed" not in link:
142        return ""
143
144    return f"speed {link['speed']} duplex {link.get('duplex', 'Full').lower()}"
145
146def _ethtool_pause_use_to_linkmodes(use):
147    """ Convert the ethtool output for pause modes into pause linkmodes """
148    if use == "Symmetric":
149        return ["Pause"]
150    elif use == "Symmetric Receive-only":
151        return ["Pause", "Asym_Pause"]
152    elif use == "Transmit-only":
153        return ["Asym_Pause"]
154    else:
155        return []
156
157def pause_to_linkmodes(rx, tx):
158    """ Convert the bool rx/tx pause into Pause/Asym """
159    return pauseparams_to_linkmodes[rx][tx]["linkmodes"]
160
161def set_local_pauseparams(cfg, rx, tx, aneg):
162    """ set pauseparams : ethtool -A """
163    rx_param = onoff(rx)
164    tx_param = onoff(tx)
165    aneg_param = onoff(aneg)
166
167    ret, _ = ethtool_ret(f"-A {cfg.ifname} rx {rx_param} tx {tx_param}"
168                         f" autoneg {aneg_param}",
169                         is_get = False)
170
171    if ret != 0 and ret != errno.EOPNOTSUPP:
172        raise KsftFailEx(f"ethtool -A {cfg.ifname} failed: {ret}")
173
174    return ret
175
176def get_local_pauseparams(cfg):
177    """ get pauseparams : ethtool -a """
178    return ethtool_ret(f"-a {cfg.ifname}", is_get=True)
179
180def set_peer_pauseparams(cfg, rx, tx, aneg):
181    """ set pauseparams on peer : ethtool -A """
182    rx_param = onoff(rx)
183    tx_param = onoff(tx)
184    aneg_param = onoff(aneg)
185
186    ret, _ = ethtool_ret(f"-A {cfg.remote_ifname} rx {rx_param} tx {tx_param}"
187                         f" autoneg {aneg_param}",
188                         is_get = False, host=cfg.remote)
189
190    if ret != 0:
191        raise KsftSkipEx(f"Can't set pauseparams on peer: {errno.errorcode.get(ret, ret)}")
192
193    return ret
194
195def get_peer_pauseparams(cfg):
196    """ get pauseparams on peer : ethtool -a """
197
198    return ethtool_ret(f"-a {cfg.remote_ifname}", is_get=True,
199                       host=cfg.remote)
200
201def get_local_pause_supported(cfg):
202    """ Return the errcode and the local pause supported linkmodes """
203
204    ret, data = ethtool_ret(f"{cfg.ifname}")
205    if ret != 0:
206        raise KsftFailEx(f"ethtool {cfg.ifname} failed: {ret}")
207
208    if "supported-pause-frame-use" not in data:
209        raise KsftSkipEx(f"{cfg.ifname} doesn't report its link modes")
210
211    return ret, _ethtool_pause_use_to_linkmodes(data["supported-pause-frame-use"])
212
213def get_local_pause_advertising(cfg):
214    """ Return the errcode and the local pause advertised linkmodes """
215
216    ret, data = ethtool_ret(f"{cfg.ifname}")
217    if ret != 0:
218        raise KsftFailEx(f"ethtool {cfg.ifname} failed: {ret}")
219
220    if "advertised-pause-frame-use" not in data:
221        raise KsftSkipEx(f"{cfg.ifname} doesn't report its link modes")
222
223    return ret, _ethtool_pause_use_to_linkmodes(data["advertised-pause-frame-use"])
224
225def get_local_pause_lp_advertising(cfg):
226    """ Return the errcode and the local pause lp_advertised linkmodes,
227        if any.
228    """
229
230    ret, data = ethtool_ret(f"{cfg.ifname}")
231    if ret != 0:
232        raise KsftFailEx(f"ethtool {cfg.ifname} failed: {errno.errorcode.get(ret, ret)}")
233
234    if "link-partner-advertised-pause-frame-use" in data:
235        return ret, _ethtool_pause_use_to_linkmodes(data["link-partner-advertised-pause-frame-use"])
236    else:
237        ksft_pr(f"Warning: {cfg.ifname} does not report the LP's advertising")
238        return errno.EOPNOTSUPP, None
239
240def get_peer_pause_supported(cfg):
241    """ Return the errcode and the remote pause supported linkmodes """
242
243    ret, data = ethtool_ret(f"{cfg.remote_ifname}", host = cfg.remote)
244    if ret != 0:
245        raise KsftFailEx(f"ethtool {cfg.remote_ifname} failed: {errno.errorcode.get(ret, ret)}")
246
247    if "supported-pause-frame-use" not in data:
248        raise KsftSkipEx(f"{cfg.remote_ifname} doesn't report its link modes")
249
250    return ret, _ethtool_pause_use_to_linkmodes(data["supported-pause-frame-use"])
251
252
253def get_peer_pause_advertising(cfg):
254    """ Return the errcode and the remote pause advertised linkmodes """
255
256    ret, data = ethtool_ret(f"{cfg.remote_ifname}", host = cfg.remote)
257    if ret != 0:
258        raise KsftFailEx(f"ethtool {cfg.remote_ifname} failed: {errno.errorcode.get(ret, ret)}")
259
260    if "advertised-pause-frame-use" not in data:
261        raise KsftSkipEx(f"{cfg.remote_ifname} doesn't report its link modes")
262
263    return ret, _ethtool_pause_use_to_linkmodes(data["advertised-pause-frame-use"])
264
265def get_peer_pause_lp_advertising(cfg):
266    """ Return the errcode and the peer pause lp_advertised linkmodes,
267        if any.
268    """
269
270    ret, data = ethtool_ret(f"{cfg.remote_ifname}", host = cfg.remote)
271    if ret != 0:
272        raise KsftFailEx(f"ethtool {cfg.remote_ifname} failed: {errno.errorcode.get(ret, ret)}")
273
274    if "link-partner-advertised-pause-frame-use" in data:
275        return ret, _ethtool_pause_use_to_linkmodes(data["link-partner-advertised-pause-frame-use"])
276    else:
277        ksft_pr(f"Warning: {cfg.remote_ifname} does not report the LP's advertising")
278        return errno.EOPNOTSUPP, None
279
280def require_pause_supported_anyof(cfg, linkmodes):
281    """ Skip if local device doesn't support any of the passed modes """
282
283    ret, _ = get_local_pauseparams(cfg)
284    if ret != 0:
285        raise KsftSkipEx("device doesn't allow getting pauseparams")
286
287    _, pause_support = get_local_pause_supported(cfg)
288    for lm in linkmodes:
289        if lm in pause_support:
290            return
291
292    raise KsftSkipEx(f"Local device doesn't support any of {linkmodes}")
293
294def require_pause_supported_allof(cfg, linkmodes):
295    """ Skip if local device doesn't support all of the passed modes """
296
297    ret, _ = get_local_pauseparams(cfg)
298    if ret != 0:
299        raise KsftSkipEx("device doesn't allow getting pauseparams")
300
301    _, pause_support = get_local_pause_supported(cfg)
302    for lm in linkmodes:
303        if lm not in pause_support:
304            raise KsftSkipEx(f"Local device doesn't support {lm}")
305
306def require_peer_pause_supported_allof(cfg, linkmodes):
307    """ Skip if local device doesn't support all of the passed modes """
308
309    ret, _ = get_peer_pauseparams(cfg)
310    if ret != 0:
311        raise KsftSkipEx("Remote device doesn't allow getting pauseparams")
312
313    _, pause_support = get_peer_pause_supported(cfg)
314    for lm in linkmodes:
315        if lm not in pause_support:
316            raise KsftSkipEx(f"Remote device doesn't support {lm}")
317
318def supported_pauseparams(cfg):
319    """ The rx/tx params covering every mode the local device supports """
320
321    _, pause_support = get_local_pause_supported(cfg)
322    if "Pause" in pause_support:
323        return 1, 1
324    if "Asym_Pause" in pause_support:
325        return 0, 1
326
327    raise KsftSkipEx("Local device doesn't support pause")
328
329def set_local_pause_autoneg(cfg, aneg):
330    """ Enable/Disable local pause autoneg """
331
332    ret, _ = ethtool_ret(f"-A {cfg.ifname} autoneg {onoff(aneg)}",
333                         is_get=False)
334    return ret
335
336def check_local_pauseparams(cfg, aneg, rx, tx):
337    """ Check that the local pauseparams are the passed parameters """
338
339    ret, params = get_local_pauseparams(cfg)
340    ksft_eq(ret, 0)
341    if ret != 0:
342        return
343
344    ksft_eq(params["autonegotiate"], bool(aneg), "pause autoneg")
345    ksft_eq(params["rx"], bool(rx), "rx pause")
346    ksft_eq(params["tx"], bool(tx), "tx pause")
347
348def check_local_advertising(cfg, linkmodes):
349    """ Check that the local advertised modes are the passed parameters """
350
351    _, adv = get_local_pause_advertising(cfg)
352    ksft_eq(adv, linkmodes, "advertised pause modes")
353
354def check_local_lp_advertising(cfg, linkmodes):
355    """ Check that the local lp_advertised modes are the passed parameters """
356
357    ret, adv = get_local_pause_lp_advertising(cfg)
358    if ret == 0:
359        ksft_eq(adv, linkmodes, "link partner advertised pause modes")
360
361def expect_pauseparams_set(cfg, pauseparams, aneg, supported, note):
362    """ Whether ethtool -A had to work or to be refused, given what the local
363        device supports
364    """
365    rx = pauseparams["rx"]
366    tx = pauseparams["tx"]
367
368    # Measure current pauseparams, re-setting the same params as the current
369    # ones returns 0 even if unsupported.
370    _, cur = get_local_pauseparams(cfg)
371    noop = cur and (cur["rx"], cur["tx"], cur["autonegotiate"]) == \
372           (bool(rx), bool(tx), aneg)
373
374    ret, _ = ethtool_ret(f"-A {cfg.ifname} rx {onoff(rx)} tx {onoff(tx)}"
375                         f" autoneg {onoff(aneg)}", is_get = False)
376
377    if noop:
378        ksft_eq(ret, 0, note)
379    elif not supported:
380        ksft_eq(ret, errno.EOPNOTSUPP, note)
381    elif set(pauseparams["linkmodes"]).issubset(set(supported)):
382        ksft_eq(ret, 0, note)
383    else:
384        ksft_in(ret, (errno.EOPNOTSUPP, errno.EINVAL), note)
385
386def pause_setup(cfg):
387    """ The starting conditions every test counts on, restored on exit:
388        - both ports admin up
389        - link autoneg on on both sides ifsupported
390        - carrier on
391    """
392
393    # Get init pause parameters
394    ret, params = ethtool_ret(f"-a {cfg.ifname}")
395    if ret == 0:
396        defer(cmd, f"ethtool -A {cfg.ifname} rx {onoff(params['rx'])} "
397                   f"tx {onoff(params['tx'])} "
398                   f"autoneg {onoff(params['autonegotiate'])}")
399
400    # Get init link parameters
401    link = ethtool(f"{cfg.ifname}", json=True)[0]
402    if "auto-negotiation" not in link:
403        raise KsftSkipEx(f"{cfg.ifname} doesn't report its link modes")
404
405    if link["auto-negotiation"]:
406        defer(cmd, f"ethtool -s {cfg.ifname} autoneg on")
407    elif "speed" in link and "duplex" in link:
408        defer(cmd, f"ethtool -s {cfg.ifname} autoneg off speed {link['speed']} "
409                   f"duplex {link['duplex'].lower()}")
410
411    # Local interface admin up, link aneg on
412    ip(f"link set {cfg.ifname} up")
413    if link["supports-auto-negotiation"] and not link["auto-negotiation"]:
414        ethtool(f"-s {cfg.ifname} autoneg on")
415
416    # Get remote pause params
417    ret, params = ethtool_ret(f"-a {cfg.remote_ifname}", host=cfg.remote)
418    if ret == 0:
419        defer(cmd, f"ethtool -A {cfg.remote_ifname} rx {onoff(params['rx'])} "
420                   f"tx {onoff(params['tx'])} "
421                   f"autoneg {onoff(params['autonegotiate'])}",
422                   host=cfg.remote)
423
424    # Get remote link params
425    link = ethtool(f"{cfg.remote_ifname}", json=True, host=cfg.remote)[0]
426    if "auto-negotiation" not in link:
427        raise KsftSkipEx(f"{cfg.remote_ifname} doesn't report its link modes")
428
429    if link["auto-negotiation"]:
430        defer(cmd, f"ethtool -s {cfg.remote_ifname} autoneg on",
431              host=cfg.remote)
432    elif "speed" in link and "duplex" in link:
433        defer(cmd, f"ethtool -s {cfg.remote_ifname} autoneg off "
434                   f"speed {link['speed']} duplex {link['duplex'].lower()}",
435                   host=cfg.remote)
436
437    # Remote interface admin up, link aneg on
438    ip(f"link set {cfg.remote_ifname} up", host=cfg.remote)
439    if link["supports-auto-negotiation"] and not link["auto-negotiation"]:
440        ethtool(f"-s {cfg.remote_ifname} autoneg on", host=cfg.remote)
441
442    wait_for_link(cfg)
443
444# Pause support : Supported linkmodes vs ability to set/get pauseparams
445@ksft_variants(pauseparams_variants)
446@ksft_disruptive
447def pause_test_support(cfg, pauseparams):
448    """ Verify that the supported linkmodes Pause and Asym_Pause match the
449        ability to configure the rx and tx pauseparams.
450
451    Drivers are expected to reject pauseparams they don't support, and
452    accept the ones they support. The supported modes are exposed by
453    the MAC to the PHY layer through phylink mac_capabilities MAC_SYM_PAUSE
454    and MAC_ASYM_PAUSE, or through phylib directly with the
455    phy_support_sym_pause() and phy_support_asym_pause() helpers.
456
457    The expectation is for drivers to refuse setting pauseparams that don't
458    match the Pause and Asym_Pause bits in the supported linkmodes with a
459    -EOPNOTSUPP return value. Unsupported pause params must be rejected.
460
461    Failing this test likely means the MAC driver doesn't implement the
462    set/get_pauseparam, but still sets flow control as supported through
463    phylink mac_capabilities or phylib's pause API. Conversely, the MAC driver
464    may have omitted to indicate its supported Pause modes. Finally, the PHY
465    driver may incorrectly override the Pause and Asym_Pause bits in its
466    supported fields.
467    """
468
469    pause_setup(cfg)
470
471    forced = forced_link_settings(cfg)
472    _, supported = get_local_pause_supported(cfg)
473
474    # We check that what we can configure in the pause params matches what we
475    # support under various contditions : Link aneg on/off, pause aneg on/off
476    ret, _ = ethtool_ret(f"-s {cfg.ifname} autoneg on", is_get = False)
477    if ret != 0:
478        ksft_pr("link autoneg on refused, not tested")
479    else:
480        expect_pauseparams_set(cfg, pauseparams, False, supported,
481                               "link autoneg on")
482        expect_pauseparams_set(cfg, pauseparams, True, supported,
483                               "link autoneg on")
484
485    if not forced:
486        ksft_pr("link speed unknown, the forced link is not tested")
487        return
488
489    ret, _ = ethtool_ret(f"-s {cfg.ifname} autoneg off {forced}", is_get = False)
490    if ret != 0:
491        ksft_pr(f"link autoneg off {forced} refused, not tested")
492        return
493
494    expect_pauseparams_set(cfg, pauseparams, False, supported, "link autoneg off")
495    expect_pauseparams_set(cfg, pauseparams, True, supported, "link autoneg off")
496
497@ksft_variants(pauseparams_variants)
498@ksft_disruptive
499def pause_advertising_test(cfg, pauseparams):
500    """Pause advertisement
501
502    Validate that changing pause params through the ETHTOOL_MSG_PAUSE command
503    translates to a change in the advertised pause params, and that these
504    parameters are correct w.r.t the supported pause params and requested pause
505    params.
506
507    This exercises the .set_pauseparam() ethtool ops for MAC configuration,
508    as well as the reconfiguration of the PHY's advertising and negotiation.
509
510    On non-phylink MACs, the MAC should call phy_set_sym_pause() to update the
511    PHY's advertising, and restart a negotiation with phy_start_aneg() if
512    need be. Failure to do so will result in the wrong advertising parameters.
513
514    On phylink-enabled MACs, phylink deals with the PHY reconfiguration provided
515    the MAC driver calls phylink_ethtool_set_pauseparam().
516
517    Failing this test likely means that the PHY driver is not correctly
518    advertising pause settings, either due to the MAC not triggering a PHY
519    reconfiguration, a misconfiguration of the advertising registers by the PHY,
520    or by mis-handling the phydev->advertising bitmap in the PHY driver directly.
521
522    The validation is made by looking at the advertised modes locally, as well
523    as what the peer's 'lp_advertising' values report.
524    """
525
526    require_pause_supported_allof(cfg, pauseparams["linkmodes"])
527    pause_setup(cfg)
528    lp = controllable_lp(cfg)
529
530    tx = pauseparams["tx"]
531    rx = pauseparams["rx"]
532    adv = pauseparams["linkmodes"]
533    not_adv = [ l for l in ["Pause", "Asym_Pause"] if l not in adv]
534
535    # It's OK to skip here, we're already validating the EOPNOTSUPP behaviour
536    # the pause_test_support test.
537    ret = set_local_pauseparams(cfg, rx, tx, True)
538    if ret == errno.EOPNOTSUPP:
539        raise KsftSkipEx(f"RX {rx} TX {tx} not supported")
540
541    # Wait for link parameters to re-negotiate and link to come back up. It must
542    # come back up, otherwise that means changing pauseparams can bring the
543    # link down.
544    wait_for_aneg(cfg)
545
546    _, linkmodes = get_local_pause_advertising(cfg)
547    for mode in adv:
548        ksft_in(mode, linkmodes,
549                f"rx {rx} tx {tx} aneg on must advertise {adv}")
550
551    for mode in not_adv:
552        ksft_not_in(mode, linkmodes,
553                    f"rx {rx} tx {tx} aneg on must not advertise {not_adv}")
554
555    if not lp:
556        return
557
558    returncode, remote_linkmodes = get_peer_pause_lp_advertising(cfg)
559    if returncode == errno.EOPNOTSUPP:
560        return
561
562    for mode in adv:
563        ksft_in(mode, remote_linkmodes, f"PHY does not advertise {adv}")
564
565    for mode in not_adv:
566        ksft_not_in(mode, remote_linkmodes,
567                    f"PHY incorrectly advertises {not_adv}")
568
569
570# Pause autonegotiation resolution : Resolved pause settings vs configured
571# pauseparams on local device and link partner
572@ksft_variants([
573    # We advertise nothing, all off
574    KsftNamedVariant("local rx off tx off, remote rx off tx off",
575        {"rx": 0, "tx": 0, "lp_rx": 0, "lp_tx": 0, "neg_rx": 0, "neg_tx": 0}),
576
577    # We advertise nothing, all off
578    KsftNamedVariant("local rx off tx off, remote rx off tx on",
579        {"rx": 0, "tx": 0, "lp_rx": 0, "lp_tx": 1, "neg_rx": 0, "neg_tx": 0}),
580
581    # We advertise nothing, all off
582    KsftNamedVariant("local rx off tx off, remote rx on tx off",
583        {"rx": 0, "tx": 0, "lp_rx": 1, "lp_tx": 0, "neg_rx": 0, "neg_tx": 0}),
584
585    # We advertise nothing, all off
586    KsftNamedVariant("local rx off tx off, remote rx on tx on",
587        {"rx": 0, "tx": 0, "lp_rx": 1, "lp_tx": 1, "neg_rx": 0, "neg_tx": 0}),
588
589    # LP advertises nothing, all off
590    KsftNamedVariant("local rx off tx on, remote rx off tx off",
591        {"rx": 0, "tx": 1, "lp_rx": 0, "lp_tx": 0, "neg_rx": 0, "neg_tx": 0}),
592
593    # We advertise Asym, LP advertises Asym, all off
594    KsftNamedVariant("local rx off tx on, remote rx off tx on",
595        {"rx": 0, "tx": 1, "lp_rx": 0, "lp_tx": 1, "neg_rx": 0, "neg_tx": 0}),
596
597    # We advertise Asym, LP advertises Pause + Asym, tx on
598    KsftNamedVariant("local rx off tx on, remote rx on tx off",
599        {"rx": 0, "tx": 1, "lp_rx": 1, "lp_tx": 0, "neg_rx": 0, "neg_tx": 1}),
600
601    # Tricky case :
602    # We advertise Asym, LP advertises Pause, resolves to all off
603    KsftNamedVariant("local rx off tx on, remote rx on tx on",
604        {"rx": 0, "tx": 1, "lp_rx": 1, "lp_tx": 1, "neg_rx": 0, "neg_tx": 0}),
605
606    # LP advertises nothing, all off
607    KsftNamedVariant("local rx on tx off, remote rx off tx off",
608        {"rx": 1, "tx": 0, "lp_rx": 0, "lp_tx": 0, "neg_rx": 0, "neg_tx": 0}),
609
610    # We advertise Pause + Asym , LP advertises Asym, rx on
611    KsftNamedVariant("local rx on tx off, remote rx off tx on",
612        {"rx": 1, "tx": 0, "lp_rx": 0, "lp_tx": 1, "neg_rx": 1, "neg_tx": 0}),
613
614    # Also tricky: Only rx enabled on both ends, but we negotiate rx/tx
615    # We advertise Pause + Asym, LP advertises Pause + Asym, all on
616    KsftNamedVariant("local rx on tx off, remote rx on tx off",
617        {"rx": 1, "tx": 0, "lp_rx": 1, "lp_tx": 0, "neg_rx": 1, "neg_tx": 1}),
618
619    # We advertise Pause + Asym, LP advertises Pause, all on
620    KsftNamedVariant("local rx on tx off, remote rx on tx on",
621        {"rx": 1, "tx": 0, "lp_rx": 1, "lp_tx": 1, "neg_rx": 1, "neg_tx": 1}),
622
623    # LP advertises nothing, all off
624    KsftNamedVariant("local rx on tx on, remote rx off tx off",
625        {"rx": 1, "tx": 1, "lp_rx": 0, "lp_tx": 0, "neg_rx": 0, "neg_tx": 0}),
626
627    # Tricky case :
628    # We advertise Pause, LP advertises Asym, resolves to all off
629    KsftNamedVariant("local rx on tx on, remote rx off tx on",
630        {"rx": 1, "tx": 1, "lp_rx": 0, "lp_tx": 1, "neg_rx": 0, "neg_tx": 0}),
631
632    # We advertise Pause, LP advertises Pause + Asym, all on
633    KsftNamedVariant("local rx on tx on, remote rx on tx off",
634        {"rx": 1, "tx": 1, "lp_rx": 1, "lp_tx": 0, "neg_rx": 1, "neg_tx": 1}),
635
636    # We advertise Pause, LP advertises Pause, all on
637    KsftNamedVariant("local rx on tx on, remote rx on tx on",
638        {"rx": 1, "tx": 1, "lp_rx": 1, "lp_tx": 1, "neg_rx": 1, "neg_tx": 1}),
639])
640@ksft_disruptive
641def pause_aneg_resolution(cfg, settings):
642    """ Verify that rx and tx pause parameters are negotiated according to 802.3
643
644    802.3 dictates the rules for pause negotiation, all 16 cases are tested, one
645    for each combination of Pause and Asym_Pause advertising on the local device
646    and the link-partner.
647
648    This test also verifies that the peer resolved the parameters correctly,
649    to ensure the negotiation is triggered correctly.
650
651    Failing this test can happen if :
652     - The MAC accepts the pause parameters but doesn't trigger a link
653       renegotiation
654     - that the PHY driver manually overwrites the Pause negotiation result
655     - that the MAC driver ignores the Pause resolution and sets its own
656       pause parameters regardless
657    """
658
659    expected_local_rx = settings["neg_rx"]
660    expected_local_tx = settings["neg_tx"]
661
662    required_local_linkmodes = pause_to_linkmodes(settings["rx"],
663                                                  settings["tx"])
664    required_remote_linkmodes = pause_to_linkmodes(settings["lp_rx"],
665                                                   settings["lp_tx"])
666
667    require_pause_supported_allof(cfg, required_local_linkmodes)
668    require_peer_pause_supported_allof(cfg, required_remote_linkmodes)
669    pause_setup(cfg)
670    require_controllable_lp(cfg)
671
672    # There's symmetry between local device and LP on pause negotiation:
673    # - if local resolves all off or all on, LP must resolve the same
674    # - if local resolves RX only, remote must resolve to TX only
675    # - if local resolves TX only, remote must resolve to RX only
676    if expected_local_rx == expected_local_tx:
677        expected_lp_rx = expected_local_rx
678        expected_lp_tx = expected_local_tx
679    else:
680        expected_lp_rx = expected_local_tx
681        expected_lp_tx = expected_local_rx
682
683    # Set pauseparams
684    ret = set_local_pauseparams(cfg, settings["rx"], settings["tx"], True)
685    if ret == errno.EOPNOTSUPP:
686        raise KsftSkipEx(f"RX {settings['rx']} TX {settings['tx']} not supported")
687
688    wait_for_aneg(cfg)
689
690    set_peer_pauseparams(cfg, settings["lp_rx"], settings["lp_tx"], True)
691
692    # Wait for link to re-negotiate
693    wait_for_aneg(cfg)
694
695    if get_local_pause_lp_advertising(cfg)[0] != 0:
696        raise KsftSkipEx("Local device doesn't report the LP's advertising")
697
698    ret, local_pauseparams = get_local_pauseparams(cfg)
699    if ret != 0 or "negotiated" not in local_pauseparams:
700        raise KsftSkipEx("Local device doesn't report the negotiated pause params")
701
702    # check adv
703    _, linkmodes = get_local_pause_advertising(cfg)
704    ksft_eq(linkmodes, required_local_linkmodes,
705            f"local rx {settings['rx']} tx {settings['tx']} must advertise "
706            f"{required_local_linkmodes}")
707
708    _, linkmodes = get_peer_pause_advertising(cfg)
709    ksft_eq(linkmodes, required_remote_linkmodes,
710            f"remote rx {settings['lp_rx']} tx {settings['lp_tx']} must advertise "
711            f"{required_remote_linkmodes}")
712
713    # check lp_adv if available
714    _, linkmodes = get_local_pause_lp_advertising(cfg)
715    ksft_eq(linkmodes, required_remote_linkmodes,
716            f"local lp_adv must show the remote's {required_remote_linkmodes}")
717
718    # check lp_adv on remote
719    ret, linkmodes = get_peer_pause_lp_advertising(cfg)
720    if ret == 0:
721        ksft_eq(linkmodes, required_local_linkmodes,
722                f"remote lp_adv must show our {required_local_linkmodes}")
723
724    # Check resolution
725    _, local_pauseparams = get_local_pauseparams(cfg)
726    ksft_eq(local_pauseparams["negotiated"]["rx"], expected_local_rx)
727    ksft_eq(local_pauseparams["negotiated"]["tx"], expected_local_tx)
728
729    ret, remote_pauseparams = get_peer_pauseparams(cfg)
730    if ret == 0 and "negotiated" in remote_pauseparams:
731        ksft_eq(remote_pauseparams["negotiated"]["rx"], expected_lp_rx)
732        ksft_eq(remote_pauseparams["negotiated"]["tx"], expected_lp_tx)
733
734@ksft_disruptive
735def pause_autoneg_state_adv(cfg):
736    """Validate that disabling pause autoneg keeps the advertised linkmodes
737
738    With pause autoneg disabled, the pause params are enforced as what the user
739    intended, but the advertising still follows the rx and tx pause params so
740    that the link partner resolves its own pause settings consistently.
741
742    Failing this test means that the MAC or PHY driver changes the
743    Pause / Asym_Pause advertising when pause autoneg is disabled.
744    """
745
746    require_pause_supported_anyof(cfg, ["Pause", "Asym_Pause"])
747    require_link_autoneg(cfg)
748
749    pause_setup(cfg)
750    require_controllable_lp(cfg)
751
752    set_peer_pauseparams(cfg, True, True, True)
753    wait_for_aneg(cfg)
754
755    rx, tx = supported_pauseparams(cfg)
756
757    # Enable all possible pauseparams with pause autoneg
758    ret = set_local_pauseparams(cfg, rx, tx, True)
759    ksft_eq(ret, 0)
760    wait_for_aneg(cfg)
761
762    # Make sure we advertise them
763    ret, adv = get_local_pause_advertising(cfg)
764    ksft_eq(ret, 0)
765    ksft_eq(adv, pause_to_linkmodes(rx, tx))
766
767    # Disable pause autoneg
768    ret = set_local_pauseparams(cfg, rx, tx, False)
769    ksft_eq(ret, 0)
770
771    # This may trigger a link renegociation
772    wait_for_aneg(cfg)
773
774    ret, adv = get_local_pause_advertising(cfg)
775    ksft_eq(ret, 0)
776    ksft_eq(adv, pause_to_linkmodes(rx, tx))
777
778    ret, adv = get_peer_pause_lp_advertising(cfg)
779    if ret == errno.EOPNOTSUPP:
780        return
781
782    ksft_eq(ret, 0)
783    ksft_eq(adv, pause_to_linkmodes(rx, tx))
784
785@ksft_disruptive
786def pause_autoneg_state_params(cfg):
787    """Validate the pause params when transitioning between fixed pause
788       params and negotiated ones. The goal is to make sure that user
789       intent on the RX and TX pause params are stored when user decides
790       to use negotiated parameters instead. The main gotcha lies on the
791       fact that when pause autoneg is used, the autoneg result may differ
792       from the user intent.
793
794    Failing this test means the MAC driver is overwriting the user intent
795    when switching to forced pause.
796    """
797
798    require_pause_supported_allof(cfg, ["Pause", "Asym_Pause"])
799    require_peer_pause_supported_allof(cfg, ["Pause"])
800    require_link_autoneg(cfg)
801    pause_setup(cfg)
802    require_controllable_lp(cfg)
803
804    # Set peer user intent to RX on TX on, with Pause autoneg on
805    set_peer_pauseparams(cfg, 1, 1, True)
806    wait_for_aneg(cfg)
807
808    # Set the local intent to RX on TX off with pause autoneg
809    ksft_eq(set_local_pauseparams(cfg, 1, 0, True), 0)
810    wait_for_aneg(cfg)
811
812    check_local_pauseparams(cfg, True, 1, 0)
813    check_local_advertising(cfg, ["Pause", "Asym_Pause"])
814    check_local_lp_advertising(cfg, ["Pause"])
815
816    # Disable pause autoneg
817    ksft_eq(set_local_pause_autoneg(cfg, False), 0)
818    wait_for_aneg(cfg)
819
820    # The pauseparams must still be what we configured before, and not the
821    # previously negotiated ones
822    check_local_pauseparams(cfg, False, 1, 0)
823
824    # Re-enable autoneg
825    ksft_eq(set_local_pause_autoneg(cfg, True), 0)
826    wait_for_aneg(cfg)
827
828    check_local_pauseparams(cfg, True, 1, 0)
829    # We must be advertising our intent again, and not RX on TX on, which would
830    # be "Pause" only.
831    check_local_advertising(cfg, ["Pause", "Asym_Pause"])
832    check_local_lp_advertising(cfg, ["Pause"])
833
834@ksft_disruptive
835def pause_autoneg_off_while_link_autoneg_on(cfg):
836    """ Validate that when link autoneg is on but pause autoneg is off, we do
837        not use negotiated pause parameters.
838
839        Failing this test means the MAC driver incorrectly accounts for the
840        negotiated pause parameters even with pause aneg off, likely due to
841        confusion between link autoneg and pause autoneg.
842    """
843
844    require_pause_supported_anyof(cfg, ["Pause", "Asym_Pause"])
845    require_peer_pause_supported_allof(cfg, ["Pause"])
846    require_link_autoneg(cfg)
847    pause_setup(cfg)
848    require_controllable_lp(cfg)
849
850    rx, tx = supported_pauseparams(cfg)
851
852    # Enable pause autoneg with all the locally supported modes enabled
853    set_peer_pauseparams(cfg, 1, 1, True)
854    ksft_eq(set_local_pauseparams(cfg, rx, tx, True), 0)
855    wait_for_aneg(cfg)
856
857    # Disable Pause autoneg
858    ksft_eq(set_local_pauseparams(cfg, rx, tx, False), 0)
859    wait_for_aneg(cfg)
860    # Pause autoneg must read "disabled"
861    check_local_pauseparams(cfg, False, rx, tx)
862
863    set_peer_pauseparams(cfg, 0, 0, True)
864    wait_for_aneg(cfg)
865
866    ethtool(f"-r {cfg.ifname}")
867    wait_for_aneg(cfg, link_drop=True)
868
869    # Pause autoneg must still be off even after a link renegotiation
870    check_local_pauseparams(cfg, False, rx, tx)
871
872@ksft_disruptive
873def pause_autoneg_link_autoneg(cfg):
874    """Validate pause autoneg and link autoneg interactions. The link autoneg's
875       admin status (i.e. do we autoneg link parameters or force them) must not
876       impact the pause autoneg status. While link autoneg is disabled, we don't
877       negotiate the pause params, however we must keep pause autoneg on as this
878       is the user intent. When link autoneg is re-enabled, pause params must be
879       derived from the negotiation.
880    """
881
882    require_pause_supported_anyof(cfg, ["Pause", "Asym_Pause"])
883    require_peer_pause_supported_allof(cfg, ["Pause"])
884    require_link_autoneg(cfg)
885    pause_setup(cfg)
886    require_controllable_lp(cfg)
887
888    rx, tx = supported_pauseparams(cfg)
889    adv = pause_to_linkmodes(rx, tx)
890
891    # Enable all possible pause modes and autoneg
892    set_peer_pauseparams(cfg, 1, 1, True)
893    ksft_eq(set_local_pauseparams(cfg, rx, tx, True), 0)
894    wait_for_aneg(cfg)
895
896    # Disable link autoneg, at the speed and duplex the link runs at
897    forced = forced_link_settings(cfg)
898    if not forced:
899        raise KsftSkipEx("Can't tell what to force the link at")
900
901    ret, _ = ethtool_ret(f"-s {cfg.remote_ifname} autoneg off {forced}",
902                         is_get=False, host=cfg.remote)
903    if ret != 0:
904        raise KsftSkipEx(f"Can't force the peer's link at {forced}")
905
906    ret, _ = ethtool_ret(f"-s {cfg.ifname} autoneg off {forced}",
907                         is_get=False)
908    if ret != 0:
909        raise KsftSkipEx(f"Can't force the link at {forced}")
910
911    try:
912        wait_for_aneg(cfg)
913    except TimeoutError:
914        raise KsftSkipEx(f"No link when forced at {forced}")
915
916    # We must have pause autoneg still enabled, even if we don't negotiate pause
917    check_local_pauseparams(cfg, True, rx, tx)
918
919    # Re-enable autoneg
920    ethtool(f"-s {cfg.remote_ifname} autoneg on", host=cfg.remote)
921    ethtool(f"-s {cfg.ifname} autoneg on")
922    wait_for_aneg(cfg)
923
924    # Pause autoneg must still be on
925    check_local_pauseparams(cfg, True, rx, tx)
926    check_local_advertising(cfg, adv)
927    check_local_lp_advertising(cfg, ["Pause"])
928
929def main():
930    """ Entry point """
931    with NetDrvEpEnv(__file__, nsim_test=False) as cfg:
932        ksft_run([pause_test_support,
933                  pause_advertising_test,
934                  pause_aneg_resolution,
935                  pause_autoneg_state_adv,
936                  pause_autoneg_state_params,
937                  pause_autoneg_off_while_link_autoneg_on,
938                  pause_autoneg_link_autoneg,
939                  ],
940                 args=(cfg, ))
941    ksft_exit()
942
943if __name__ == "__main__":
944    main()
945