xref: /linux/tools/net/ynl/pyynl/ethtool.py (revision d8e0e25406a1208a836b476418c7a85903d047ac)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
3
4import argparse
5import json
6import pathlib
7import pprint
8import sys
9import re
10import os
11
12sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())
13from lib import YnlFamily
14from cli import schema_dir, spec_dir
15
16def args_to_req(ynl, op_name, args, req):
17    """
18    Verify and convert command-line arguments to the ynl-compatible request.
19    """
20    valid_attrs = ynl.operation_do_attributes(op_name)
21    valid_attrs.remove('header') # not user-provided
22
23    if len(args) == 0:
24        print(f'no attributes, expected: {valid_attrs}')
25        sys.exit(1)
26
27    i = 0
28    while i < len(args):
29        attr = args[i]
30        if i + 1 >= len(args):
31            print(f'expected value for \'{attr}\'')
32            sys.exit(1)
33
34        if attr not in valid_attrs:
35            print(f'invalid attribute \'{attr}\', expected: {valid_attrs}')
36            sys.exit(1)
37
38        val = args[i+1]
39        i += 2
40
41        req[attr] = val
42
43def print_field(reply, *desc):
44    """
45    Pretty-print a set of fields from the reply. desc specifies the
46    fields and the optional type (bool/yn).
47    """
48    if len(desc) == 0:
49        return print_field(reply, *zip(reply.keys(), reply.keys()))
50
51    for spec in desc:
52        try:
53            field, name, tp = spec
54        except ValueError:
55            field, name = spec
56            tp = 'int'
57
58        value = reply.get(field, None)
59        if tp == 'yn':
60            value = 'yes' if value else 'no'
61        elif tp == 'bool' or isinstance(value, bool):
62            value = 'on' if value else 'off'
63        else:
64            value = 'n/a' if value is None else value
65
66        print(f'{name}: {value}')
67
68def print_speed(name, value):
69    """
70    Print out the speed-like strings from the value dict.
71    """
72    speed_re = re.compile(r'[0-9]+base[^/]+/.+')
73    speed = [ k for k, v in value.items() if v and speed_re.match(k) ]
74    print(f'{name}: {" ".join(speed)}')
75
76def doit(ynl, args, op_name):
77    """
78    Prepare request header, parse arguments and doit.
79    """
80    req = {
81        'header': {
82          'dev-name': args.device,
83        },
84    }
85
86    args_to_req(ynl, op_name, args.args, req)
87    ynl.do(op_name, req)
88
89def dumpit(ynl, args, op_name, extra = {}):
90    """
91    Prepare request header, parse arguments and dumpit (filtering out the
92    devices we're not interested in).
93    """
94    reply = ynl.dump(op_name, { 'header': {} } | extra)
95    if not reply:
96        return {}
97
98    for msg in reply:
99        if msg['header']['dev-name'] == args.device:
100            if args.json:
101                pprint.PrettyPrinter().pprint(msg)
102                sys.exit(0)
103            msg.pop('header', None)
104            return msg
105
106    print(f"Not supported for device {args.device}")
107    sys.exit(1)
108
109def bits_to_dict(attr):
110    """
111    Convert ynl-formatted bitmask to a dict of bit=value.
112    """
113    ret = {}
114    if 'bits' not in attr:
115        return dict()
116    if 'bit' not in attr['bits']:
117        return dict()
118    for bit in attr['bits']['bit']:
119        if bit['name'] == '':
120            continue
121        name = bit['name']
122        value = bit.get('value', False)
123        ret[name] = value
124    return ret
125
126def main():
127    parser = argparse.ArgumentParser(description='ethtool wannabe')
128    parser.add_argument('--json', action=argparse.BooleanOptionalAction)
129    parser.add_argument('--show-priv-flags', action=argparse.BooleanOptionalAction)
130    parser.add_argument('--set-priv-flags', action=argparse.BooleanOptionalAction)
131    parser.add_argument('--show-eee', action=argparse.BooleanOptionalAction)
132    parser.add_argument('--set-eee', action=argparse.BooleanOptionalAction)
133    parser.add_argument('-a', '--show-pause', action=argparse.BooleanOptionalAction)
134    parser.add_argument('-A', '--set-pause', action=argparse.BooleanOptionalAction)
135    parser.add_argument('-c', '--show-coalesce', action=argparse.BooleanOptionalAction)
136    parser.add_argument('-C', '--set-coalesce', action=argparse.BooleanOptionalAction)
137    parser.add_argument('-g', '--show-ring', action=argparse.BooleanOptionalAction)
138    parser.add_argument('-G', '--set-ring', action=argparse.BooleanOptionalAction)
139    parser.add_argument('-k', '--show-features', action=argparse.BooleanOptionalAction)
140    parser.add_argument('-K', '--set-features', action=argparse.BooleanOptionalAction)
141    parser.add_argument('-l', '--show-channels', action=argparse.BooleanOptionalAction)
142    parser.add_argument('-L', '--set-channels', action=argparse.BooleanOptionalAction)
143    parser.add_argument('-T', '--show-time-stamping', action=argparse.BooleanOptionalAction)
144    parser.add_argument('-S', '--statistics', action=argparse.BooleanOptionalAction)
145    # TODO: --show-tunnels        tunnel-info-get
146    # TODO: --show-module         module-get
147    # TODO: --get-plca-cfg        plca-get
148    # TODO: --get-plca-status     plca-get-status
149    # TODO: --show-mm             mm-get
150    # TODO: --show-fec            fec-get
151    # TODO: --dump-module-eerpom  module-eeprom-get
152    # TODO:                       pse-get
153    # TODO:                       rss-get
154    parser.add_argument('device', metavar='device', type=str)
155    parser.add_argument('args', metavar='args', type=str, nargs='*')
156    global args
157    args = parser.parse_args()
158
159    spec = os.path.join(spec_dir(), 'ethtool.yaml')
160    schema = os.path.join(schema_dir(), 'genetlink-legacy.yaml')
161
162    ynl = YnlFamily(spec, schema)
163
164    if args.set_priv_flags:
165        # TODO: parse the bitmask
166        print("not implemented")
167        return
168
169    if args.set_eee:
170        return doit(ynl, args, 'eee-set')
171
172    if args.set_pause:
173        return doit(ynl, args, 'pause-set')
174
175    if args.set_coalesce:
176        return doit(ynl, args, 'coalesce-set')
177
178    if args.set_features:
179        # TODO: parse the bitmask
180        print("not implemented")
181        return
182
183    if args.set_channels:
184        return doit(ynl, args, 'channels-set')
185
186    if args.set_ring:
187        return doit(ynl, args, 'rings-set')
188
189    if args.show_priv_flags:
190        flags = bits_to_dict(dumpit(ynl, args, 'privflags-get')['flags'])
191        print_field(flags)
192        return
193
194    if args.show_eee:
195        eee = dumpit(ynl, args, 'eee-get')
196        ours = bits_to_dict(eee['modes-ours'])
197        peer = bits_to_dict(eee['modes-peer'])
198
199        if 'enabled' in eee:
200            status = 'enabled' if eee['enabled'] else 'disabled'
201            if 'active' in eee and eee['active']:
202                status = status + ' - active'
203            else:
204                status = status + ' - inactive'
205        else:
206            status = 'not supported'
207
208        print(f'EEE status: {status}')
209        print_field(eee, ('tx-lpi-timer', 'Tx LPI'))
210        print_speed('Advertised EEE link modes', ours)
211        print_speed('Link partner advertised EEE link modes', peer)
212
213        return
214
215    if args.show_pause:
216        print_field(dumpit(ynl, args, 'pause-get'),
217                ('autoneg', 'Autonegotiate', 'bool'),
218                ('rx', 'RX', 'bool'),
219                ('tx', 'TX', 'bool'))
220        return
221
222    if args.show_coalesce:
223        print_field(dumpit(ynl, args, 'coalesce-get'))
224        return
225
226    if args.show_features:
227        reply = dumpit(ynl, args, 'features-get')
228        available = bits_to_dict(reply['hw'])
229        requested = bits_to_dict(reply['wanted']).keys()
230        active = bits_to_dict(reply['active']).keys()
231        never_changed = bits_to_dict(reply['nochange']).keys()
232
233        for f in sorted(available):
234            value = "off"
235            if f in active:
236                value = "on"
237
238            fixed = ""
239            if f not in available or f in never_changed:
240                fixed = " [fixed]"
241
242            req = ""
243            if f in requested:
244                if f in active:
245                    req = " [requested on]"
246                else:
247                    req = " [requested off]"
248
249            print(f'{f}: {value}{fixed}{req}')
250
251        return
252
253    if args.show_channels:
254        reply = dumpit(ynl, args, 'channels-get')
255        print(f'Channel parameters for {args.device}:')
256
257        print('Pre-set maximums:')
258        print_field(reply,
259            ('rx-max', 'RX'),
260            ('tx-max', 'TX'),
261            ('other-max', 'Other'),
262            ('combined-max', 'Combined'))
263
264        print('Current hardware settings:')
265        print_field(reply,
266            ('rx-count', 'RX'),
267            ('tx-count', 'TX'),
268            ('other-count', 'Other'),
269            ('combined-count', 'Combined'))
270
271        return
272
273    if args.show_ring:
274        reply = dumpit(ynl, args, 'channels-get')
275
276        print(f'Ring parameters for {args.device}:')
277
278        print('Pre-set maximums:')
279        print_field(reply,
280            ('rx-max', 'RX'),
281            ('rx-mini-max', 'RX Mini'),
282            ('rx-jumbo-max', 'RX Jumbo'),
283            ('tx-max', 'TX'))
284
285        print('Current hardware settings:')
286        print_field(reply,
287            ('rx', 'RX'),
288            ('rx-mini', 'RX Mini'),
289            ('rx-jumbo', 'RX Jumbo'),
290            ('tx', 'TX'))
291
292        print_field(reply,
293            ('rx-buf-len', 'RX Buf Len'),
294            ('cqe-size', 'CQE Size'),
295            ('tx-push', 'TX Push', 'bool'))
296
297        return
298
299    if args.statistics:
300        print('NIC statistics:')
301
302        # TODO: pass id?
303        strset = dumpit(ynl, args, 'strset-get')
304        pprint.PrettyPrinter().pprint(strset)
305
306        req = {
307          'groups': {
308            'size': 1,
309            'bits': {
310              'bit':
311                # TODO: support passing the bitmask
312                #[
313                  #{ 'name': 'eth-phy', 'value': True },
314                  { 'name': 'eth-mac', 'value': True },
315                  #{ 'name': 'eth-ctrl', 'value': True },
316                  #{ 'name': 'rmon', 'value': True },
317                #],
318            },
319          },
320        }
321
322        rsp = dumpit(ynl, args, 'stats-get', req)
323        pprint.PrettyPrinter().pprint(rsp)
324        return
325
326    if args.show_time_stamping:
327        req = {
328          'header': {
329            'flags': 'stats',
330          },
331        }
332
333        tsinfo = dumpit(ynl, args, 'tsinfo-get', req)
334
335        print(f'Time stamping parameters for {args.device}:')
336
337        print('Capabilities:')
338        [print(f'\t{v}') for v in bits_to_dict(tsinfo['timestamping'])]
339
340        print(f'PTP Hardware Clock: {tsinfo.get("phc-index", "none")}')
341
342        if 'tx-types' in tsinfo:
343            print('Hardware Transmit Timestamp Modes:')
344            [print(f'\t{v}') for v in bits_to_dict(tsinfo['tx-types'])]
345        else:
346            print('Hardware Transmit Timestamp Modes: none')
347
348        if 'rx-filters' in tsinfo:
349            print('Hardware Receive Filter Modes:')
350            [print(f'\t{v}') for v in bits_to_dict(tsinfo['rx-filters'])]
351        else:
352            print('Hardware Receive Filter Modes: none')
353
354        if 'stats' in tsinfo and tsinfo['stats']:
355            print('Statistics:')
356            [print(f'\t{k}: {v}') for k, v in tsinfo['stats'].items()]
357
358        return
359
360    print(f'Settings for {args.device}:')
361    linkmodes = dumpit(ynl, args, 'linkmodes-get')
362    ours = bits_to_dict(linkmodes['ours'])
363
364    supported_ports = ('TP',  'AUI', 'BNC', 'MII', 'FIBRE', 'Backplane')
365    ports = [ p for p in supported_ports if ours.get(p, False)]
366    print(f'Supported ports: [ {" ".join(ports)} ]')
367
368    print_speed('Supported link modes', ours)
369
370    print_field(ours, ('Pause', 'Supported pause frame use', 'yn'))
371    print_field(ours, ('Autoneg', 'Supports auto-negotiation', 'yn'))
372
373    supported_fec = ('None',  'PS', 'BASER', 'LLRS')
374    fec = [ p for p in supported_fec if ours.get(p, False)]
375    fec_str = " ".join(fec)
376    if len(fec) == 0:
377        fec_str = "Not reported"
378
379    print(f'Supported FEC modes: {fec_str}')
380
381    speed = 'Unknown!'
382    if linkmodes['speed'] > 0 and linkmodes['speed'] < 0xffffffff:
383        speed = f'{linkmodes["speed"]}Mb/s'
384    print(f'Speed: {speed}')
385
386    duplex_modes = {
387            0: 'Half',
388            1: 'Full',
389    }
390    duplex = duplex_modes.get(linkmodes["duplex"], None)
391    if not duplex:
392        duplex = f'Unknown! ({linkmodes["duplex"]})'
393    print(f'Duplex: {duplex}')
394
395    autoneg = "off"
396    if linkmodes.get("autoneg", 0) != 0:
397        autoneg = "on"
398    print(f'Auto-negotiation: {autoneg}')
399
400    ports = {
401            0: 'Twisted Pair',
402            1: 'AUI',
403            2: 'MII',
404            3: 'FIBRE',
405            4: 'BNC',
406            5: 'Directly Attached Copper',
407            0xef: 'None',
408    }
409    linkinfo = dumpit(ynl, args, 'linkinfo-get')
410    print(f'Port: {ports.get(linkinfo["port"], "Other")}')
411
412    print_field(linkinfo, ('phyaddr', 'PHYAD'))
413
414    transceiver = {
415            0: 'Internal',
416            1: 'External',
417    }
418    print(f'Transceiver: {transceiver.get(linkinfo["transceiver"], "Unknown")}')
419
420    mdix_ctrl = {
421            1: 'off',
422            2: 'on',
423    }
424    mdix = mdix_ctrl.get(linkinfo['tp-mdix-ctrl'], None)
425    if mdix:
426        mdix = mdix + ' (forced)'
427    else:
428        mdix = mdix_ctrl.get(linkinfo['tp-mdix'], 'Unknown (auto)')
429    print(f'MDI-X: {mdix}')
430
431    debug = dumpit(ynl, args, 'debug-get')
432    msgmask = bits_to_dict(debug.get("msgmask", [])).keys()
433    print(f'Current message level: {" ".join(msgmask)}')
434
435    linkstate = dumpit(ynl, args, 'linkstate-get')
436    detected_states = {
437            0: 'no',
438            1: 'yes',
439    }
440    # TODO: wol-get
441    detected = detected_states.get(linkstate['link'], 'unknown')
442    print(f'Link detected: {detected}')
443
444if __name__ == '__main__':
445    main()
446