xref: /dpdk/usertools/dpdk-devbind.py (revision cf0556f4a11c1de87f94ed9ba0c14267cb034217)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: BSD-3-Clause
3# Copyright(c) 2010-2014 Intel Corporation
4#
5
6import sys
7import os
8import subprocess
9import argparse
10import platform
11
12from glob import glob
13from os.path import exists, basename
14from os.path import join as path_join
15
16# The PCI base class for all devices
17network_class = {'Class': '02', 'Vendor': None, 'Device': None,
18                 'SVendor': None, 'SDevice': None}
19acceleration_class = {'Class': '12', 'Vendor': None, 'Device': None,
20                      'SVendor': None, 'SDevice': None}
21ifpga_class = {'Class': '12', 'Vendor': '8086', 'Device': '0b30',
22               'SVendor': None, 'SDevice': None}
23encryption_class = {'Class': '10', 'Vendor': None, 'Device': None,
24                    'SVendor': None, 'SDevice': None}
25intel_processor_class = {'Class': '0b', 'Vendor': '8086', 'Device': None,
26                         'SVendor': None, 'SDevice': None}
27cavium_sso = {'Class': '08', 'Vendor': '177d', 'Device': 'a04b,a04d',
28              'SVendor': None, 'SDevice': None}
29cavium_fpa = {'Class': '08', 'Vendor': '177d', 'Device': 'a053',
30              'SVendor': None, 'SDevice': None}
31cavium_pkx = {'Class': '08', 'Vendor': '177d', 'Device': 'a0dd,a049',
32              'SVendor': None, 'SDevice': None}
33cavium_tim = {'Class': '08', 'Vendor': '177d', 'Device': 'a051',
34              'SVendor': None, 'SDevice': None}
35cavium_zip = {'Class': '12', 'Vendor': '177d', 'Device': 'a037',
36              'SVendor': None, 'SDevice': None}
37avp_vnic = {'Class': '05', 'Vendor': '1af4', 'Device': '1110',
38            'SVendor': None, 'SDevice': None}
39
40cnxk_bphy = {'Class': '08', 'Vendor': '177d', 'Device': 'a089',
41             'SVendor': None, 'SDevice': None}
42cnxk_bphy_cgx = {'Class': '08', 'Vendor': '177d', 'Device': 'a059,a060',
43                 'SVendor': None, 'SDevice': None}
44cnxk_dma = {'Class': '08', 'Vendor': '177d', 'Device': 'a081',
45            'SVendor': None, 'SDevice': None}
46cnxk_inl_dev = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f0,a0f1',
47                'SVendor': None, 'SDevice': None}
48
49hisilicon_dma = {'Class': '08', 'Vendor': '19e5', 'Device': 'a122',
50                 'SVendor': None, 'SDevice': None}
51odm_dma = {'Class': '08', 'Vendor': '177d', 'Device': 'a08c',
52           'SVendor': None, 'SDevice': None}
53
54intel_dlb = {'Class': '0b', 'Vendor': '8086', 'Device': '270b,2710,2714',
55             'SVendor': None, 'SDevice': None}
56intel_ioat_bdw = {'Class': '08', 'Vendor': '8086',
57                  'Device': '6f20,6f21,6f22,6f23,6f24,6f25,6f26,6f27,6f2e,6f2f',
58                  'SVendor': None, 'SDevice': None}
59intel_ioat_skx = {'Class': '08', 'Vendor': '8086', 'Device': '2021',
60                  'SVendor': None, 'SDevice': None}
61intel_ioat_icx = {'Class': '08', 'Vendor': '8086', 'Device': '0b00',
62                  'SVendor': None, 'SDevice': None}
63intel_idxd_spr = {'Class': '08', 'Vendor': '8086', 'Device': '0b25',
64                  'SVendor': None, 'SDevice': None}
65intel_ntb_skx = {'Class': '06', 'Vendor': '8086', 'Device': '201c',
66                 'SVendor': None, 'SDevice': None}
67intel_ntb_icx = {'Class': '06', 'Vendor': '8086', 'Device': '347e',
68                 'SVendor': None, 'SDevice': None}
69
70cnxk_sso = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f9,a0fa',
71            'SVendor': None, 'SDevice': None}
72cnxk_npa = {'Class': '08', 'Vendor': '177d', 'Device': 'a0fb,a0fc',
73            'SVendor': None, 'SDevice': None}
74cn9k_ree = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f4',
75            'SVendor': None, 'SDevice': None}
76
77virtio_blk = {'Class': '01', 'Vendor': "1af4", 'Device': '1001,1042',
78              'SVendor': None, 'SDevice': None}
79
80cnxk_ml = {'Class': '08', 'Vendor': '177d', 'Device': 'a092',
81           'SVendor': None, 'SDevice': None}
82
83network_devices = [network_class, cavium_pkx, avp_vnic, ifpga_class]
84baseband_devices = [acceleration_class]
85crypto_devices = [encryption_class, intel_processor_class]
86dma_devices = [cnxk_dma, hisilicon_dma,
87               intel_idxd_spr, intel_ioat_bdw, intel_ioat_icx, intel_ioat_skx,
88               odm_dma]
89eventdev_devices = [cavium_sso, cavium_tim, intel_dlb, cnxk_sso]
90mempool_devices = [cavium_fpa, cnxk_npa]
91compress_devices = [cavium_zip]
92regex_devices = [cn9k_ree]
93ml_devices = [cnxk_ml]
94misc_devices = [cnxk_bphy, cnxk_bphy_cgx, cnxk_inl_dev,
95                intel_ntb_skx, intel_ntb_icx,
96                virtio_blk]
97
98# global dict ethernet devices present. Dictionary indexed by PCI address.
99# Each device within this is itself a dictionary of device properties
100devices = {}
101# list of supported DPDK drivers
102dpdk_drivers = ["igb_uio", "vfio-pci", "uio_pci_generic"]
103# list of currently loaded kernel modules
104loaded_modules = None
105
106# command-line arg flags
107b_flag = None
108status_flag = False
109force_flag = False
110args = []
111
112
113# check if a specific kernel module is loaded
114def module_is_loaded(module):
115    global loaded_modules
116
117    if module == 'vfio_pci':
118        module = 'vfio-pci'
119
120    if loaded_modules:
121        return module in loaded_modules
122
123    # Get list of sysfs modules (both built-in and dynamically loaded)
124    sysfs_path = '/sys/module/'
125
126    # Get the list of directories in sysfs_path
127    sysfs_mods = [m for m in os.listdir(sysfs_path)
128                  if os.path.isdir(os.path.join(sysfs_path, m))]
129
130    # special case for vfio_pci (module is named vfio-pci,
131    # but its .ko is named vfio_pci)
132    sysfs_mods = [a if a != 'vfio_pci' else 'vfio-pci' for a in sysfs_mods]
133
134    loaded_modules = sysfs_mods
135
136    # add built-in modules as loaded
137    release = platform.uname().release
138    filename = os.path.join("/lib/modules/", release, "modules.builtin")
139    if os.path.exists(filename):
140        try:
141            with open(filename) as f:
142                loaded_modules += [os.path.splitext(os.path.basename(mod))[0] for mod in f]
143        except IOError:
144            print("Warning: cannot read list of built-in kernel modules")
145
146    return module in loaded_modules
147
148
149def check_modules():
150    '''Checks that igb_uio is loaded'''
151    global dpdk_drivers
152
153    # list of supported modules
154    mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers]
155
156    # first check if module is loaded
157    for mod in mods:
158        if module_is_loaded(mod["Name"]):
159            mod["Found"] = True
160
161    # check if we have at least one loaded module
162    if True not in [mod["Found"] for mod in mods] and b_flag is not None:
163        print("Warning: no supported DPDK kernel modules are loaded", file=sys.stderr)
164
165    # change DPDK driver list to only contain drivers that are loaded
166    dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
167
168
169def has_driver(dev_id):
170    '''return true if a device is assigned to a driver. False otherwise'''
171    return "Driver_str" in devices[dev_id]
172
173
174def get_pci_device_details(dev_id, probe_lspci):
175    '''This function gets additional details for a PCI device'''
176    device = {}
177
178    if probe_lspci:
179        extra_info = subprocess.check_output(["lspci", "-vmmks", dev_id]).splitlines()
180        # parse lspci details
181        for line in extra_info:
182            if not line:
183                continue
184            name, value = line.decode("utf8").split("\t", 1)
185            name = name.strip(":") + "_str"
186            device[name] = value
187    # check for a unix interface name
188    device["Interface"] = ""
189    for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
190        if "net" in dirs:
191            device["Interface"] = \
192                ",".join(os.listdir(os.path.join(base, "net")))
193            break
194    # check if a port is used for ssh connection
195    device["Ssh_if"] = False
196    device["Active"] = ""
197
198    return device
199
200
201def clear_data():
202    '''This function clears any old data'''
203    global devices
204    devices = {}
205
206
207def get_device_details(devices_type):
208    '''This function populates the "devices" dictionary. The keys used are
209    the pci addresses (domain:bus:slot.func). The values are themselves
210    dictionaries - one for each NIC.'''
211    global devices
212    global dpdk_drivers
213
214    # first loop through and read details for all devices
215    # request machine readable format, with numeric IDs and String
216    dev = {}
217    dev_lines = subprocess.check_output(["lspci", "-Dvmmnnk"]).splitlines()
218    for dev_line in dev_lines:
219        if not dev_line:
220            if device_type_match(dev, devices_type):
221                # Replace "Driver" with "Driver_str" to have consistency of
222                # of dictionary key names
223                if "Driver" in dev.keys():
224                    dev["Driver_str"] = dev.pop("Driver")
225                if "Module" in dev.keys():
226                    dev["Module_str"] = dev.pop("Module")
227                # use dict to make copy of dev
228                devices[dev["Slot"]] = dict(dev)
229            # Clear previous device's data
230            dev = {}
231        else:
232            name, value = dev_line.decode("utf8").split("\t", 1)
233            value_list = value.rsplit(' ', 1)
234            if value_list:
235                # String stored in <name>_str
236                dev[name.rstrip(":") + '_str'] = value_list[0]
237            # Numeric IDs
238            dev[name.rstrip(":")] = value_list[len(value_list) - 1] \
239                .rstrip("]").lstrip("[")
240
241    if devices_type == network_devices:
242        # check what is the interface if any for an ssh connection if
243        # any to this host, so we can mark it later.
244        ssh_if = []
245        route = subprocess.check_output(["ip", "-o", "route"])
246        # filter out all lines for 169.254 routes
247        route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
248                                 route.decode().splitlines()))
249        rt_info = route.split()
250        for i in range(len(rt_info) - 1):
251            if rt_info[i] == "dev":
252                ssh_if.append(rt_info[i + 1])
253
254    # based on the basic info, get extended text details
255    for d in devices.keys():
256        if not device_type_match(devices[d], devices_type):
257            continue
258
259        # get additional info and add it to existing data
260        devices[d] = devices[d].copy()
261        # No need to probe lspci
262        devices[d].update(get_pci_device_details(d, False).items())
263
264        if devices_type == network_devices:
265            for _if in ssh_if:
266                if _if in devices[d]["Interface"].split(","):
267                    devices[d]["Ssh_if"] = True
268                    devices[d]["Active"] = "*Active*"
269                    break
270
271        # add igb_uio to list of supporting modules if needed
272        if "Module_str" in devices[d]:
273            for driver in dpdk_drivers:
274                if driver not in devices[d]["Module_str"]:
275                    devices[d]["Module_str"] = \
276                        devices[d]["Module_str"] + ",%s" % driver
277        else:
278            devices[d]["Module_str"] = ",".join(dpdk_drivers)
279
280        # make sure the driver and module strings do not have any duplicates
281        if has_driver(d):
282            modules = devices[d]["Module_str"].split(",")
283            if devices[d]["Driver_str"] in modules:
284                modules.remove(devices[d]["Driver_str"])
285                devices[d]["Module_str"] = ",".join(modules)
286
287
288def device_type_match(dev, devices_type):
289    for i in range(len(devices_type)):
290        param_count = len(
291            [x for x in devices_type[i].values() if x is not None])
292        match_count = 0
293        if dev["Class"][0:2] == devices_type[i]["Class"]:
294            match_count = match_count + 1
295            for key in devices_type[i].keys():
296                if key != 'Class' and devices_type[i][key]:
297                    value_list = devices_type[i][key].split(',')
298                    for value in value_list:
299                        if value.strip(' ') == dev[key]:
300                            match_count = match_count + 1
301            # count must be the number of non None parameters to match
302            if match_count == param_count:
303                return True
304    return False
305
306
307def dev_id_from_dev_name(dev_name):
308    '''Take a device "name" - a string passed in by user to identify a NIC
309    device, and determine the device id - i.e. the domain:bus:slot.func - for
310    it, which can then be used to index into the devices array'''
311
312    # check if it's already a suitable index
313    if dev_name in devices:
314        return dev_name
315    # check if it's an index just missing the domain part
316    if "0000:" + dev_name in devices:
317        return "0000:" + dev_name
318
319    # check if it's an interface name, e.g. eth1
320    for d in devices.keys():
321        if dev_name in devices[d]["Interface"].split(","):
322            return devices[d]["Slot"]
323    # if nothing else matches - error
324    raise ValueError("Unknown device: %s. "
325                     "Please specify device in \"bus:slot.func\" format" % dev_name)
326
327
328def unbind_one(dev_id, force):
329    '''Unbind the device identified by "dev_id" from its current driver'''
330    dev = devices[dev_id]
331    if not has_driver(dev_id):
332        print("Notice: %s %s %s is not currently managed by any driver" %
333              (dev["Slot"], dev["Device_str"], dev["Interface"]), file=sys.stderr)
334        return
335
336    # prevent us disconnecting ourselves
337    if dev["Ssh_if"] and not force:
338        print("Warning: routing table indicates that interface %s is active. "
339              "Skipping unbind" % dev_id, file=sys.stderr)
340        return
341
342    # write to /sys to unbind
343    filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
344    try:
345        f = open(filename, "a")
346    except OSError as err:
347        sys.exit("Error: unbind failed for %s - Cannot open %s: %s" %
348                 (dev_id, filename, err))
349    f.write(dev_id)
350    f.close()
351
352
353def bind_one(dev_id, driver, force):
354    '''Bind the device given by "dev_id" to the driver "driver". If the device
355    is already bound to a different driver, it will be unbound first'''
356    dev = devices[dev_id]
357    saved_driver = None  # used to rollback any unbind in case of failure
358
359    # prevent disconnection of our ssh session
360    if dev["Ssh_if"] and not force:
361        print("Warning: routing table indicates that interface %s is active. "
362              "Not modifying" % dev_id, file=sys.stderr)
363        return
364
365    # unbind any existing drivers we don't want
366    if has_driver(dev_id):
367        if dev["Driver_str"] == driver:
368            print("Notice: %s already bound to driver %s, skipping" %
369                  (dev_id, driver), file=sys.stderr)
370            return
371        saved_driver = dev["Driver_str"]
372        unbind_one(dev_id, force)
373        dev["Driver_str"] = ""  # clear driver string
374
375    # For kernels >= 3.15 driver_override can be used to specify the driver
376    # for a device rather than relying on the driver to provide a positive
377    # match of the device.  The existing process of looking up
378    # the vendor and device ID, adding them to the driver new_id,
379    # will erroneously bind other devices too which has the additional burden
380    # of unbinding those devices
381    if driver in dpdk_drivers:
382        filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
383        if exists(filename):
384            try:
385                f = open(filename, "w")
386            except OSError as err:
387                print("Error: bind failed for %s - Cannot open %s: %s"
388                      % (dev_id, filename, err), file=sys.stderr)
389                return
390            try:
391                f.write("%s" % driver)
392                f.close()
393            except OSError as err:
394                print("Error: bind failed for %s - Cannot write driver %s to "
395                      "PCI ID: %s" % (dev_id, driver, err), file=sys.stderr)
396                return
397        # For kernels < 3.15 use new_id to add PCI id's to the driver
398        else:
399            filename = "/sys/bus/pci/drivers/%s/new_id" % driver
400            try:
401                f = open(filename, "w")
402            except OSError as err:
403                print("Error: bind failed for %s - Cannot open %s: %s"
404                      % (dev_id, filename, err), file=sys.stderr)
405                return
406            try:
407                # Convert Device and Vendor Id to int to write to new_id
408                f.write("%04x %04x" % (int(dev["Vendor"], 16),
409                                       int(dev["Device"], 16)))
410                f.close()
411            except OSError as err:
412                print("Error: bind failed for %s - Cannot write new PCI ID to "
413                      "driver %s: %s" % (dev_id, driver, err), file=sys.stderr)
414                return
415
416    # do the bind by writing to /sys
417    filename = "/sys/bus/pci/drivers/%s/bind" % driver
418    try:
419        f = open(filename, "a")
420    except OSError as err:
421        print("Error: bind failed for %s - Cannot open %s: %s"
422              % (dev_id, filename, err), file=sys.stderr)
423        if saved_driver is not None:  # restore any previous driver
424            bind_one(dev_id, saved_driver, force)
425        return
426    try:
427        f.write(dev_id)
428        f.close()
429    except OSError as err:
430        # for some reason, closing dev_id after adding a new PCI ID to new_id
431        # results in IOError. however, if the device was successfully bound,
432        # we don't care for any errors and can safely ignore IOError
433        tmp = get_pci_device_details(dev_id, True)
434        if "Driver_str" in tmp and tmp["Driver_str"] == driver:
435            return
436        print("Error: bind failed for %s - Cannot bind to driver %s: %s"
437              % (dev_id, driver, err), file=sys.stderr)
438        if saved_driver is not None:  # restore any previous driver
439            bind_one(dev_id, saved_driver, force)
440        return
441
442    # For kernels > 3.15 driver_override is used to bind a device to a driver.
443    # Before unbinding it, overwrite driver_override with empty string so that
444    # the device can be bound to any other driver
445    filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
446    if exists(filename):
447        try:
448            f = open(filename, "w")
449        except OSError as err:
450            sys.exit("Error: unbind failed for %s - Cannot open %s: %s"
451                     % (dev_id, filename, err))
452        try:
453            f.write("\00")
454            f.close()
455        except OSError as err:
456            sys.exit("Error: unbind failed for %s - Cannot write %s: %s"
457                     % (dev_id, filename, err))
458
459
460def unbind_all(dev_list, force=False):
461    """Unbind method, takes a list of device locations"""
462
463    if dev_list[0] == "dpdk":
464        for d in devices.keys():
465            if "Driver_str" in devices[d]:
466                if devices[d]["Driver_str"] in dpdk_drivers:
467                    unbind_one(devices[d]["Slot"], force)
468        return
469
470    try:
471        dev_list = map(dev_id_from_dev_name, dev_list)
472    except ValueError as ex:
473        print(ex)
474        sys.exit(1)
475
476    for d in dev_list:
477        unbind_one(d, force)
478
479
480def bind_all(dev_list, driver, force=False):
481    """Bind method, takes a list of device locations"""
482    global devices
483
484    # a common user error is to forget to specify the driver the devices need to
485    # be bound to. check if the driver is a valid device, and if it is, show
486    # a meaningful error.
487    try:
488        dev_id_from_dev_name(driver)
489        # if we've made it this far, this means that the "driver" was a valid
490        # device string, so it's probably not a valid driver name.
491        sys.exit("Error: Driver '%s' does not look like a valid driver. "
492                 "Did you forget to specify the driver to bind devices to?" % driver)
493    except ValueError:
494        # driver generated error - it's not a valid device ID, so all is well
495        pass
496
497    # check if we're attempting to bind to a driver that isn't loaded
498    if not module_is_loaded(driver.replace('-', '_')):
499        sys.exit("Error: Driver '%s' is not loaded." % driver)
500
501    try:
502        dev_list = map(dev_id_from_dev_name, dev_list)
503    except ValueError as ex:
504        sys.exit(ex)
505
506    for d in dev_list:
507        bind_one(d, driver, force)
508
509    # For kernels < 3.15 when binding devices to a generic driver
510    # (i.e. one that doesn't have a PCI ID table) using new_id, some devices
511    # that are not bound to any other driver could be bound even if no one has
512    # asked them to. hence, we check the list of drivers again, and see if
513    # some of the previously-unbound devices were erroneously bound.
514    if not exists("/sys/bus/pci/devices/%s/driver_override" % d):
515        for d in devices.keys():
516            # skip devices that were already bound or that we know should be bound
517            if "Driver_str" in devices[d] or d in dev_list:
518                continue
519
520            # update information about this device
521            devices[d] = dict(devices[d].items()
522                              + get_pci_device_details(d, True).items())
523
524            # check if updated information indicates that the device was bound
525            if "Driver_str" in devices[d]:
526                unbind_one(d, force)
527
528
529def display_devices(title, dev_list, extra_params=None):
530    '''Displays to the user the details of a list of devices given in
531    "dev_list". The "extra_params" parameter, if given, should contain a string
532     with %()s fields in it for replacement by the named fields in each
533     device's dictionary.'''
534    strings = []  # this holds the strings to print. We sort before printing
535    print("\n%s" % title)
536    print("=" * len(title))
537    if not dev_list:
538        strings.append("<none>")
539    else:
540        for dev in dev_list:
541            if extra_params is not None:
542                strings.append("%s '%s %s' %s" % (dev["Slot"],
543                                                  dev["Device_str"],
544                                                  dev["Device"],
545                                                  extra_params % dev))
546            else:
547                strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
548    # sort before printing, so that the entries appear in PCI order
549    strings.sort()
550    print("\n".join(strings))  # print one per line
551
552
553def show_device_status(devices_type, device_name, if_field=False):
554    global dpdk_drivers
555    kernel_drv = []
556    dpdk_drv = []
557    no_drv = []
558
559    # split our list of network devices into the three categories above
560    for d in devices.keys():
561        if device_type_match(devices[d], devices_type):
562            if not has_driver(d):
563                no_drv.append(devices[d])
564                continue
565            if devices[d]["Driver_str"] in dpdk_drivers:
566                dpdk_drv.append(devices[d])
567            else:
568                kernel_drv.append(devices[d])
569
570    n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv)
571
572    # don't bother displaying anything if there are no devices
573    if n_devs == 0:
574        msg = "No '%s' devices detected" % device_name
575        print("")
576        print(msg)
577        print("".join('=' * len(msg)))
578        return
579
580    # print each category separately, so we can clearly see what's used by DPDK
581    if dpdk_drv:
582        display_devices("%s devices using DPDK-compatible driver" % device_name,
583                        dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s")
584    if kernel_drv:
585        if_text = ""
586        if if_field:
587            if_text = "if=%(Interface)s "
588        display_devices("%s devices using kernel driver" % device_name, kernel_drv,
589                        if_text + "drv=%(Driver_str)s "
590                        "unused=%(Module_str)s %(Active)s")
591    if no_drv:
592        display_devices("Other %s devices" % device_name, no_drv,
593                        "unused=%(Module_str)s")
594
595
596def show_status():
597    '''Function called when the script is passed the "--status" option.
598    Displays to the user what devices are bound to the igb_uio driver, the
599    kernel driver or to no driver'''
600
601    if status_dev in ["net", "all"]:
602        show_device_status(network_devices, "Network", if_field=True)
603
604    if status_dev in ["baseband", "all"]:
605        show_device_status(baseband_devices, "Baseband")
606
607    if status_dev in ["crypto", "all"]:
608        show_device_status(crypto_devices, "Crypto")
609
610    if status_dev in ["dma", "all"]:
611        show_device_status(dma_devices, "DMA")
612
613    if status_dev in ["event", "all"]:
614        show_device_status(eventdev_devices, "Eventdev")
615
616    if status_dev in ["mempool", "all"]:
617        show_device_status(mempool_devices, "Mempool")
618
619    if status_dev in ["compress", "all"]:
620        show_device_status(compress_devices, "Compress")
621
622    if status_dev in ["misc", "all"]:
623        show_device_status(misc_devices, "Misc (rawdev)")
624
625    if status_dev in ["regex", "all"]:
626        show_device_status(regex_devices, "Regex")
627
628    if status_dev in ["ml", "all"]:
629        show_device_status(ml_devices, "ML")
630
631
632def pci_glob(arg):
633    '''Returns a list containing either:
634    * List of PCI B:D:F matching arg, using shell wildcards e.g. 80:04.*
635    * Only the passed arg if matching list is empty'''
636    sysfs_path = "/sys/bus/pci/devices"
637    for _glob in [arg, '0000:' + arg]:
638        paths = [basename(path) for path in glob(path_join(sysfs_path, _glob))]
639        if paths:
640            return paths
641    return [arg]
642
643
644def parse_args():
645    '''Parses the command-line arguments given by the user and takes the
646    appropriate action for each'''
647    global b_flag
648    global status_flag
649    global status_dev
650    global force_flag
651    global args
652
653    parser = argparse.ArgumentParser(
654        description='Utility to bind and unbind devices from Linux kernel',
655        formatter_class=argparse.RawDescriptionHelpFormatter,
656        epilog="""
657Examples:
658---------
659
660To display current device status:
661        %(prog)s --status
662
663To display current network device status:
664        %(prog)s --status-dev net
665
666To bind eth1 from the current driver and move to use vfio-pci
667        %(prog)s --bind=vfio-pci eth1
668
669To unbind 0000:01:00.0 from using any driver
670        %(prog)s -u 0000:01:00.0
671
672To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
673        %(prog)s -b ixgbe 02:00.0 02:00.1
674""")
675
676    parser.add_argument(
677        '-s',
678        '--status',
679        action='store_true',
680        help="Print the current status of all known devices.")
681    parser.add_argument(
682        '--status-dev',
683        help="Print the status of given device group.",
684        choices=['baseband', 'compress', 'crypto', 'dma', 'event',
685                 'mempool', 'misc', 'net', 'regex', 'ml'])
686    bind_group = parser.add_mutually_exclusive_group()
687    bind_group.add_argument(
688        '-b',
689        '--bind',
690        metavar='DRIVER',
691        help="Select the driver to use or \"none\" to unbind the device")
692    bind_group.add_argument(
693        '-u',
694        '--unbind',
695        action='store_true',
696        help="Unbind a device (equivalent to \"-b none\")")
697    parser.add_argument(
698        '--force',
699        action='store_true',
700        help="""
701Override restriction on binding devices in use by Linux"
702WARNING: This can lead to loss of network connection and should be used with caution.
703""")
704    parser.add_argument(
705        'devices',
706        metavar='DEVICE',
707        nargs='*',
708        help="""
709Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax.
710For devices bound to Linux kernel drivers, they may be referred to by interface name.
711""")
712
713    opt = parser.parse_args()
714
715    if opt.status_dev:
716        status_flag = True
717        status_dev = opt.status_dev
718    if opt.status:
719        status_flag = True
720        status_dev = "all"
721    if opt.force:
722        force_flag = True
723    if opt.bind:
724        b_flag = opt.bind
725    elif opt.unbind:
726        b_flag = "none"
727    args = opt.devices
728
729    if not b_flag and not status_flag:
730        print("Error: No action specified for devices. "
731              "Please give a --bind, --ubind or --status option",
732              file=sys.stderr)
733        parser.print_usage()
734        sys.exit(1)
735
736    if b_flag and not args:
737        print("Error: No devices specified.", file=sys.stderr)
738        parser.print_usage()
739        sys.exit(1)
740
741    # resolve any PCI globs in the args
742    new_args = []
743    for arg in args:
744        new_args.extend(pci_glob(arg))
745    args = new_args
746
747
748def do_arg_actions():
749    '''do the actual action requested by the user'''
750    global b_flag
751    global status_flag
752    global force_flag
753    global args
754
755    if b_flag in ["none", "None"]:
756        unbind_all(args, force_flag)
757    elif b_flag is not None:
758        bind_all(args, b_flag, force_flag)
759    if status_flag:
760        if b_flag is not None:
761            clear_data()
762            # refresh if we have changed anything
763            get_device_details(network_devices)
764            get_device_details(baseband_devices)
765            get_device_details(crypto_devices)
766            get_device_details(dma_devices)
767            get_device_details(eventdev_devices)
768            get_device_details(mempool_devices)
769            get_device_details(compress_devices)
770            get_device_details(regex_devices)
771            get_device_details(ml_devices)
772            get_device_details(misc_devices)
773        show_status()
774
775
776def main():
777    '''program main function'''
778    # check if lspci is installed, suppress any output
779    with open(os.devnull, 'w') as devnull:
780        ret = subprocess.call(['which', 'lspci'],
781                              stdout=devnull, stderr=devnull)
782        if ret != 0:
783            sys.exit("'lspci' not found - please install 'pciutils'")
784    parse_args()
785    check_modules()
786    clear_data()
787    get_device_details(network_devices)
788    get_device_details(baseband_devices)
789    get_device_details(crypto_devices)
790    get_device_details(dma_devices)
791    get_device_details(eventdev_devices)
792    get_device_details(mempool_devices)
793    get_device_details(compress_devices)
794    get_device_details(regex_devices)
795    get_device_details(ml_devices)
796    get_device_details(misc_devices)
797    do_arg_actions()
798
799
800if __name__ == "__main__":
801    main()
802