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