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