2 # SPDX-License-Identifier: BSD-3-Clause
3 # Copyright(c) 2010-2014 Intel Corporation
13 from os.path import exists, basename
14 from os.path import join as path_join
16 # The PCI base class for all devices
17 network_class = {'Class': '02', 'Vendor': None, 'Device': None,
18 'SVendor': None, 'SDevice': None}
19 acceleration_class = {'Class': '12', 'Vendor': None, 'Device': None,
20 'SVendor': None, 'SDevice': None}
21 ifpga_class = {'Class': '12', 'Vendor': '8086', 'Device': '0b30',
22 'SVendor': None, 'SDevice': None}
23 encryption_class = {'Class': '10', 'Vendor': None, 'Device': None,
24 'SVendor': None, 'SDevice': None}
25 intel_processor_class = {'Class': '0b', 'Vendor': '8086', 'Device': None,
26 'SVendor': None, 'SDevice': None}
27 cavium_sso = {'Class': '08', 'Vendor': '177d', 'Device': 'a04b,a04d',
28 'SVendor': None, 'SDevice': None}
29 cavium_fpa = {'Class': '08', 'Vendor': '177d', 'Device': 'a053',
30 'SVendor': None, 'SDevice': None}
31 cavium_pkx = {'Class': '08', 'Vendor': '177d', 'Device': 'a0dd,a049',
32 'SVendor': None, 'SDevice': None}
33 cavium_tim = {'Class': '08', 'Vendor': '177d', 'Device': 'a051',
34 'SVendor': None, 'SDevice': None}
35 cavium_zip = {'Class': '12', 'Vendor': '177d', 'Device': 'a037',
36 'SVendor': None, 'SDevice': None}
37 avp_vnic = {'Class': '05', 'Vendor': '1af4', 'Device': '1110',
38 'SVendor': None, 'SDevice': None}
40 octeontx2_sso = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f9,a0fa',
41 'SVendor': None, 'SDevice': None}
42 octeontx2_npa = {'Class': '08', 'Vendor': '177d', 'Device': 'a0fb,a0fc',
43 'SVendor': None, 'SDevice': None}
44 octeontx2_dma = {'Class': '08', 'Vendor': '177d', 'Device': 'a081',
45 'SVendor': None, 'SDevice': None}
46 octeontx2_ree = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f4',
47 'SVendor': None, 'SDevice': None}
49 intel_dlb = {'Class': '0b', 'Vendor': '8086', 'Device': '270b,2710,2714',
50 'SVendor': None, 'SDevice': None}
51 intel_ioat_bdw = {'Class': '08', 'Vendor': '8086',
52 'Device': '6f20,6f21,6f22,6f23,6f24,6f25,6f26,6f27,6f2e,6f2f',
53 'SVendor': None, 'SDevice': None}
54 intel_ioat_skx = {'Class': '08', 'Vendor': '8086', 'Device': '2021',
55 'SVendor': None, 'SDevice': None}
56 intel_ioat_icx = {'Class': '08', 'Vendor': '8086', 'Device': '0b00',
57 'SVendor': None, 'SDevice': None}
58 intel_idxd_spr = {'Class': '08', 'Vendor': '8086', 'Device': '0b25',
59 'SVendor': None, 'SDevice': None}
60 intel_ntb_skx = {'Class': '06', 'Vendor': '8086', 'Device': '201c',
61 'SVendor': None, 'SDevice': None}
62 intel_ntb_icx = {'Class': '06', 'Vendor': '8086', 'Device': '347e',
63 'SVendor': None, 'SDevice': None}
65 network_devices = [network_class, cavium_pkx, avp_vnic, ifpga_class]
66 baseband_devices = [acceleration_class]
67 crypto_devices = [encryption_class, intel_processor_class]
68 eventdev_devices = [cavium_sso, cavium_tim, intel_dlb, octeontx2_sso]
69 mempool_devices = [cavium_fpa, octeontx2_npa]
70 compress_devices = [cavium_zip]
71 regex_devices = [octeontx2_ree]
72 misc_devices = [intel_ioat_bdw, intel_ioat_skx, intel_ioat_icx, intel_idxd_spr,
73 intel_ntb_skx, intel_ntb_icx,
76 # global dict ethernet devices present. Dictionary indexed by PCI address.
77 # Each device within this is itself a dictionary of device properties
79 # list of supported DPDK drivers
80 dpdk_drivers = ["igb_uio", "vfio-pci", "uio_pci_generic"]
81 # list of currently loaded kernel modules
84 # command-line arg flags
90 # check if a specific kernel module is loaded
91 def module_is_loaded(module):
94 if module == 'vfio_pci':
98 return module in loaded_modules
100 # Get list of sysfs modules (both built-in and dynamically loaded)
101 sysfs_path = '/sys/module/'
103 # Get the list of directories in sysfs_path
104 sysfs_mods = [m for m in os.listdir(sysfs_path)
105 if os.path.isdir(os.path.join(sysfs_path, m))]
107 # special case for vfio_pci (module is named vfio-pci,
108 # but its .ko is named vfio_pci)
109 sysfs_mods = [a if a != 'vfio_pci' else 'vfio-pci' for a in sysfs_mods]
111 loaded_modules = sysfs_mods
113 # add built-in modules as loaded
114 release = platform.uname().release
115 filename = os.path.join("/lib/modules/", release, "modules.builtin")
116 if os.path.exists(filename):
118 with open(filename) as f:
119 loaded_modules += [os.path.splitext(os.path.basename(mod))[0] for mod in f]
121 print("Warning: cannot read list of built-in kernel modules")
123 return module in loaded_modules
127 '''Checks that igb_uio is loaded'''
130 # list of supported modules
131 mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers]
133 # first check if module is loaded
135 if module_is_loaded(mod["Name"]):
138 # check if we have at least one loaded module
139 if True not in [mod["Found"] for mod in mods] and b_flag is not None:
140 print("Warning: no supported DPDK kernel modules are loaded", file=sys.stderr)
142 # change DPDK driver list to only contain drivers that are loaded
143 dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
146 def has_driver(dev_id):
147 '''return true if a device is assigned to a driver. False otherwise'''
148 return "Driver_str" in devices[dev_id]
151 def get_pci_device_details(dev_id, probe_lspci):
152 '''This function gets additional details for a PCI device'''
156 extra_info = subprocess.check_output(["lspci", "-vmmks", dev_id]).splitlines()
157 # parse lspci details
158 for line in extra_info:
161 name, value = line.decode("utf8").split("\t", 1)
162 name = name.strip(":") + "_str"
164 # check for a unix interface name
165 device["Interface"] = ""
166 for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
168 device["Interface"] = \
169 ",".join(os.listdir(os.path.join(base, "net")))
171 # check if a port is used for ssh connection
172 device["Ssh_if"] = False
173 device["Active"] = ""
178 '''This function clears any old data'''
182 def get_device_details(devices_type):
183 '''This function populates the "devices" dictionary. The keys used are
184 the pci addresses (domain:bus:slot.func). The values are themselves
185 dictionaries - one for each NIC.'''
189 # first loop through and read details for all devices
190 # request machine readable format, with numeric IDs and String
192 dev_lines = subprocess.check_output(["lspci", "-Dvmmnnk"]).splitlines()
193 for dev_line in dev_lines:
195 if device_type_match(dev, devices_type):
196 # Replace "Driver" with "Driver_str" to have consistency of
197 # of dictionary key names
198 if "Driver" in dev.keys():
199 dev["Driver_str"] = dev.pop("Driver")
200 if "Module" in dev.keys():
201 dev["Module_str"] = dev.pop("Module")
202 # use dict to make copy of dev
203 devices[dev["Slot"]] = dict(dev)
204 # Clear previous device's data
207 name, value = dev_line.decode("utf8").split("\t", 1)
208 value_list = value.rsplit(' ', 1)
210 # String stored in <name>_str
211 dev[name.rstrip(":") + '_str'] = value_list[0]
213 dev[name.rstrip(":")] = value_list[len(value_list) - 1] \
214 .rstrip("]").lstrip("[")
216 if devices_type == network_devices:
217 # check what is the interface if any for an ssh connection if
218 # any to this host, so we can mark it later.
220 route = subprocess.check_output(["ip", "-o", "route"])
221 # filter out all lines for 169.254 routes
222 route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
223 route.decode().splitlines()))
224 rt_info = route.split()
225 for i in range(len(rt_info) - 1):
226 if rt_info[i] == "dev":
227 ssh_if.append(rt_info[i+1])
229 # based on the basic info, get extended text details
230 for d in devices.keys():
231 if not device_type_match(devices[d], devices_type):
234 # get additional info and add it to existing data
235 devices[d] = devices[d].copy()
236 # No need to probe lspci
237 devices[d].update(get_pci_device_details(d, False).items())
239 if devices_type == network_devices:
241 if _if in devices[d]["Interface"].split(","):
242 devices[d]["Ssh_if"] = True
243 devices[d]["Active"] = "*Active*"
246 # add igb_uio to list of supporting modules if needed
247 if "Module_str" in devices[d]:
248 for driver in dpdk_drivers:
249 if driver not in devices[d]["Module_str"]:
250 devices[d]["Module_str"] = \
251 devices[d]["Module_str"] + ",%s" % driver
253 devices[d]["Module_str"] = ",".join(dpdk_drivers)
255 # make sure the driver and module strings do not have any duplicates
257 modules = devices[d]["Module_str"].split(",")
258 if devices[d]["Driver_str"] in modules:
259 modules.remove(devices[d]["Driver_str"])
260 devices[d]["Module_str"] = ",".join(modules)
263 def device_type_match(dev, devices_type):
264 for i in range(len(devices_type)):
266 [x for x in devices_type[i].values() if x is not None])
268 if dev["Class"][0:2] == devices_type[i]["Class"]:
269 match_count = match_count + 1
270 for key in devices_type[i].keys():
271 if key != 'Class' and devices_type[i][key]:
272 value_list = devices_type[i][key].split(',')
273 for value in value_list:
274 if value.strip(' ') == dev[key]:
275 match_count = match_count + 1
276 # count must be the number of non None parameters to match
277 if match_count == param_count:
281 def dev_id_from_dev_name(dev_name):
282 '''Take a device "name" - a string passed in by user to identify a NIC
283 device, and determine the device id - i.e. the domain:bus:slot.func - for
284 it, which can then be used to index into the devices array'''
286 # check if it's already a suitable index
287 if dev_name in devices:
289 # check if it's an index just missing the domain part
290 if "0000:" + dev_name in devices:
291 return "0000:" + dev_name
293 # check if it's an interface name, e.g. eth1
294 for d in devices.keys():
295 if dev_name in devices[d]["Interface"].split(","):
296 return devices[d]["Slot"]
297 # if nothing else matches - error
298 raise ValueError("Unknown device: %s. "
299 "Please specify device in \"bus:slot.func\" format" % dev_name)
302 def unbind_one(dev_id, force):
303 '''Unbind the device identified by "dev_id" from its current driver'''
304 dev = devices[dev_id]
305 if not has_driver(dev_id):
306 print("Notice: %s %s %s is not currently managed by any driver" %
307 (dev["Slot"], dev["Device_str"], dev["Interface"]), file=sys.stderr)
310 # prevent us disconnecting ourselves
311 if dev["Ssh_if"] and not force:
312 print("Warning: routing table indicates that interface %s is active. "
313 "Skipping unbind" % dev_id, file=sys.stderr)
316 # write to /sys to unbind
317 filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
319 f = open(filename, "a")
321 sys.exit("Error: unbind failed for %s - Cannot open %s" %
327 def bind_one(dev_id, driver, force):
328 '''Bind the device given by "dev_id" to the driver "driver". If the device
329 is already bound to a different driver, it will be unbound first'''
330 dev = devices[dev_id]
331 saved_driver = None # used to rollback any unbind in case of failure
333 # prevent disconnection of our ssh session
334 if dev["Ssh_if"] and not force:
335 print("Warning: routing table indicates that interface %s is active. "
336 "Not modifying" % dev_id, file=sys.stderr)
339 # unbind any existing drivers we don't want
340 if has_driver(dev_id):
341 if dev["Driver_str"] == driver:
342 print("Notice: %s already bound to driver %s, skipping" %
343 (dev_id, driver), file=sys.stderr)
345 saved_driver = dev["Driver_str"]
346 unbind_one(dev_id, force)
347 dev["Driver_str"] = "" # clear driver string
349 # For kernels >= 3.15 driver_override can be used to specify the driver
350 # for a device rather than relying on the driver to provide a positive
351 # match of the device. The existing process of looking up
352 # the vendor and device ID, adding them to the driver new_id,
353 # will erroneously bind other devices too which has the additional burden
354 # of unbinding those devices
355 if driver in dpdk_drivers:
356 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
359 f = open(filename, "w")
361 print("Error: bind failed for %s - Cannot open %s"
362 % (dev_id, filename), file=sys.stderr)
365 f.write("%s" % driver)
368 print("Error: bind failed for %s - Cannot write driver %s to "
369 "PCI ID " % (dev_id, driver), file=sys.stderr)
371 # For kernels < 3.15 use new_id to add PCI id's to the driver
373 filename = "/sys/bus/pci/drivers/%s/new_id" % driver
375 f = open(filename, "w")
377 print("Error: bind failed for %s - Cannot open %s"
378 % (dev_id, filename), file=sys.stderr)
381 # Convert Device and Vendor Id to int to write to new_id
382 f.write("%04x %04x" % (int(dev["Vendor"], 16),
383 int(dev["Device"], 16)))
386 print("Error: bind failed for %s - Cannot write new PCI ID to "
387 "driver %s" % (dev_id, driver), file=sys.stderr)
390 # do the bind by writing to /sys
391 filename = "/sys/bus/pci/drivers/%s/bind" % driver
393 f = open(filename, "a")
395 print("Error: bind failed for %s - Cannot open %s"
396 % (dev_id, filename), file=sys.stderr)
397 if saved_driver is not None: # restore any previous driver
398 bind_one(dev_id, saved_driver, force)
404 # for some reason, closing dev_id after adding a new PCI ID to new_id
405 # results in IOError. however, if the device was successfully bound,
406 # we don't care for any errors and can safely ignore IOError
407 tmp = get_pci_device_details(dev_id, True)
408 if "Driver_str" in tmp and tmp["Driver_str"] == driver:
410 print("Error: bind failed for %s - Cannot bind to driver %s"
411 % (dev_id, driver), file=sys.stderr)
412 if saved_driver is not None: # restore any previous driver
413 bind_one(dev_id, saved_driver, force)
416 # For kernels > 3.15 driver_override is used to bind a device to a driver.
417 # Before unbinding it, overwrite driver_override with empty string so that
418 # the device can be bound to any other driver
419 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
422 f = open(filename, "w")
424 sys.exit("Error: unbind failed for %s - Cannot open %s"
425 % (dev_id, filename))
430 sys.exit("Error: unbind failed for %s - Cannot open %s"
431 % (dev_id, filename))
434 def unbind_all(dev_list, force=False):
435 """Unbind method, takes a list of device locations"""
437 if dev_list[0] == "dpdk":
438 for d in devices.keys():
439 if "Driver_str" in devices[d]:
440 if devices[d]["Driver_str"] in dpdk_drivers:
441 unbind_one(devices[d]["Slot"], force)
445 dev_list = map(dev_id_from_dev_name, dev_list)
446 except ValueError as ex:
454 def bind_all(dev_list, driver, force=False):
455 """Bind method, takes a list of device locations"""
458 # a common user error is to forget to specify the driver the devices need to
459 # be bound to. check if the driver is a valid device, and if it is, show
460 # a meaningful error.
462 dev_id_from_dev_name(driver)
463 # if we've made it this far, this means that the "driver" was a valid
464 # device string, so it's probably not a valid driver name.
465 sys.exit("Error: Driver '%s' does not look like a valid driver. " \
466 "Did you forget to specify the driver to bind devices to?" % driver)
468 # driver generated error - it's not a valid device ID, so all is well
471 # check if we're attempting to bind to a driver that isn't loaded
472 if not module_is_loaded(driver.replace('-', '_')):
473 sys.exit("Error: Driver '%s' is not loaded." % driver)
476 dev_list = map(dev_id_from_dev_name, dev_list)
477 except ValueError as ex:
481 bind_one(d, driver, force)
483 # For kernels < 3.15 when binding devices to a generic driver
484 # (i.e. one that doesn't have a PCI ID table) using new_id, some devices
485 # that are not bound to any other driver could be bound even if no one has
486 # asked them to. hence, we check the list of drivers again, and see if
487 # some of the previously-unbound devices were erroneously bound.
488 if not exists("/sys/bus/pci/devices/%s/driver_override" % d):
489 for d in devices.keys():
490 # skip devices that were already bound or that we know should be bound
491 if "Driver_str" in devices[d] or d in dev_list:
494 # update information about this device
495 devices[d] = dict(devices[d].items() +
496 get_pci_device_details(d, True).items())
498 # check if updated information indicates that the device was bound
499 if "Driver_str" in devices[d]:
503 def display_devices(title, dev_list, extra_params=None):
504 '''Displays to the user the details of a list of devices given in
505 "dev_list". The "extra_params" parameter, if given, should contain a string
506 with %()s fields in it for replacement by the named fields in each
507 device's dictionary.'''
508 strings = [] # this holds the strings to print. We sort before printing
509 print("\n%s" % title)
510 print("="*len(title))
512 strings.append("<none>")
515 if extra_params is not None:
516 strings.append("%s '%s %s' %s" % (dev["Slot"],
521 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
522 # sort before printing, so that the entries appear in PCI order
524 print("\n".join(strings)) # print one per line
526 def show_device_status(devices_type, device_name, if_field=False):
532 # split our list of network devices into the three categories above
533 for d in devices.keys():
534 if device_type_match(devices[d], devices_type):
535 if not has_driver(d):
536 no_drv.append(devices[d])
538 if devices[d]["Driver_str"] in dpdk_drivers:
539 dpdk_drv.append(devices[d])
541 kernel_drv.append(devices[d])
543 n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv)
545 # don't bother displaying anything if there are no devices
547 msg = "No '%s' devices detected" % device_name
550 print("".join('=' * len(msg)))
553 # print each category separately, so we can clearly see what's used by DPDK
555 display_devices("%s devices using DPDK-compatible driver" % device_name,
556 dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s")
560 if_text = "if=%(Interface)s "
561 display_devices("%s devices using kernel driver" % device_name, kernel_drv,
562 if_text + "drv=%(Driver_str)s "
563 "unused=%(Module_str)s %(Active)s")
565 display_devices("Other %s devices" % device_name, no_drv,
566 "unused=%(Module_str)s")
569 '''Function called when the script is passed the "--status" option.
570 Displays to the user what devices are bound to the igb_uio driver, the
571 kernel driver or to no driver'''
573 if status_dev in ["net", "all"]:
574 show_device_status(network_devices, "Network", if_field=True)
576 if status_dev in ["baseband", "all"]:
577 show_device_status(baseband_devices, "Baseband")
579 if status_dev in ["crypto", "all"]:
580 show_device_status(crypto_devices, "Crypto")
582 if status_dev in ["event", "all"]:
583 show_device_status(eventdev_devices, "Eventdev")
585 if status_dev in ["mempool", "all"]:
586 show_device_status(mempool_devices, "Mempool")
588 if status_dev in ["compress", "all"]:
589 show_device_status(compress_devices, "Compress")
591 if status_dev in ["misc", "all"]:
592 show_device_status(misc_devices, "Misc (rawdev)")
594 if status_dev in ["regex", "all"]:
595 show_device_status(regex_devices, "Regex")
599 '''Returns a list containing either:
600 * List of PCI B:D:F matching arg, using shell wildcards e.g. 80:04.*
601 * Only the passed arg if matching list is empty'''
602 sysfs_path = "/sys/bus/pci/devices"
603 for _glob in [arg, '0000:' + arg]:
604 paths = [basename(path) for path in glob(path_join(sysfs_path, _glob))]
611 '''Parses the command-line arguments given by the user and takes the
612 appropriate action for each'''
619 parser = argparse.ArgumentParser(
620 description='Utility to bind and unbind devices from Linux kernel',
621 formatter_class=argparse.RawDescriptionHelpFormatter,
626 To display current device status:
629 To display current network device status:
630 %(prog)s --status-dev net
632 To bind eth1 from the current driver and move to use vfio-pci
633 %(prog)s --bind=vfio-pci eth1
635 To unbind 0000:01:00.0 from using any driver
636 %(prog)s -u 0000:01:00.0
638 To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
639 %(prog)s -b ixgbe 02:00.0 02:00.1
646 help="Print the current status of all known devices.")
649 help="Print the status of given device group.",
650 choices=['baseband', 'compress', 'crypto', 'event',
651 'mempool', 'misc', 'net', 'regex'])
652 bind_group = parser.add_mutually_exclusive_group()
653 bind_group.add_argument(
657 help="Select the driver to use or \"none\" to unbind the device")
658 bind_group.add_argument(
662 help="Unbind a device (equivalent to \"-b none\")")
667 Override restriction on binding devices in use by Linux"
668 WARNING: This can lead to loss of network connection and should be used with caution.
675 Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax.
676 For devices bound to Linux kernel drivers, they may be referred to by interface name.
679 opt = parser.parse_args()
683 status_dev = opt.status_dev
695 if not b_flag and not status_flag:
696 print("Error: No action specified for devices. "
697 "Please give a --bind, --ubind or --status option",
702 if b_flag and not args:
703 print("Error: No devices specified.", file=sys.stderr)
707 # resolve any PCI globs in the args
710 new_args.extend(pci_glob(arg))
713 def do_arg_actions():
714 '''do the actual action requested by the user'''
720 if b_flag in ["none", "None"]:
721 unbind_all(args, force_flag)
722 elif b_flag is not None:
723 bind_all(args, b_flag, force_flag)
725 if b_flag is not None:
727 # refresh if we have changed anything
728 get_device_details(network_devices)
729 get_device_details(baseband_devices)
730 get_device_details(crypto_devices)
731 get_device_details(eventdev_devices)
732 get_device_details(mempool_devices)
733 get_device_details(compress_devices)
734 get_device_details(regex_devices)
735 get_device_details(misc_devices)
740 '''program main function'''
741 # check if lspci is installed, suppress any output
742 with open(os.devnull, 'w') as devnull:
743 ret = subprocess.call(['which', 'lspci'],
744 stdout=devnull, stderr=devnull)
746 sys.exit("'lspci' not found - please install 'pciutils'")
750 get_device_details(network_devices)
751 get_device_details(baseband_devices)
752 get_device_details(crypto_devices)
753 get_device_details(eventdev_devices)
754 get_device_details(mempool_devices)
755 get_device_details(compress_devices)
756 get_device_details(regex_devices)
757 get_device_details(misc_devices)
760 if __name__ == "__main__":