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