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}
48 cnxk_bphy = {'Class': '08', 'Vendor': '177d', 'Device': 'a089',
49 'SVendor': None, 'SDevice': None}
50 cnxk_bphy_cgx = {'Class': '08', 'Vendor': '177d', 'Device': 'a059,a060',
51 'SVendor': None, 'SDevice': None}
52 cnxk_inl_dev = {'Class': '08', 'Vendor': '177d', 'Device': 'a0f0,a0f1',
53 'SVendor': None, 'SDevice': None}
55 intel_dlb = {'Class': '0b', 'Vendor': '8086', 'Device': '270b,2710,2714',
56 'SVendor': None, 'SDevice': None}
57 intel_ioat_bdw = {'Class': '08', 'Vendor': '8086',
58 'Device': '6f20,6f21,6f22,6f23,6f24,6f25,6f26,6f27,6f2e,6f2f',
59 'SVendor': None, 'SDevice': None}
60 intel_ioat_skx = {'Class': '08', 'Vendor': '8086', 'Device': '2021',
61 'SVendor': None, 'SDevice': None}
62 intel_ioat_icx = {'Class': '08', 'Vendor': '8086', 'Device': '0b00',
63 'SVendor': None, 'SDevice': None}
64 intel_idxd_spr = {'Class': '08', 'Vendor': '8086', 'Device': '0b25',
65 'SVendor': None, 'SDevice': None}
66 intel_ntb_skx = {'Class': '06', 'Vendor': '8086', 'Device': '201c',
67 'SVendor': None, 'SDevice': None}
68 intel_ntb_icx = {'Class': '06', 'Vendor': '8086', 'Device': '347e',
69 'SVendor': None, 'SDevice': None}
71 network_devices = [network_class, cavium_pkx, avp_vnic, ifpga_class]
72 baseband_devices = [acceleration_class]
73 crypto_devices = [encryption_class, intel_processor_class]
75 eventdev_devices = [cavium_sso, cavium_tim, intel_dlb, octeontx2_sso]
76 mempool_devices = [cavium_fpa, octeontx2_npa]
77 compress_devices = [cavium_zip]
78 regex_devices = [octeontx2_ree]
79 misc_devices = [cnxk_bphy, cnxk_bphy_cgx, cnxk_inl_dev, intel_ioat_bdw,
80 intel_ioat_skx, intel_ioat_icx, intel_idxd_spr, intel_ntb_skx,
81 intel_ntb_icx, octeontx2_dma]
83 # global dict ethernet devices present. Dictionary indexed by PCI address.
84 # Each device within this is itself a dictionary of device properties
86 # list of supported DPDK drivers
87 dpdk_drivers = ["igb_uio", "vfio-pci", "uio_pci_generic"]
88 # list of currently loaded kernel modules
91 # command-line arg flags
97 # check if a specific kernel module is loaded
98 def module_is_loaded(module):
101 if module == 'vfio_pci':
105 return module in loaded_modules
107 # Get list of sysfs modules (both built-in and dynamically loaded)
108 sysfs_path = '/sys/module/'
110 # Get the list of directories in sysfs_path
111 sysfs_mods = [m for m in os.listdir(sysfs_path)
112 if os.path.isdir(os.path.join(sysfs_path, m))]
114 # special case for vfio_pci (module is named vfio-pci,
115 # but its .ko is named vfio_pci)
116 sysfs_mods = [a if a != 'vfio_pci' else 'vfio-pci' for a in sysfs_mods]
118 loaded_modules = sysfs_mods
120 # add built-in modules as loaded
121 release = platform.uname().release
122 filename = os.path.join("/lib/modules/", release, "modules.builtin")
123 if os.path.exists(filename):
125 with open(filename) as f:
126 loaded_modules += [os.path.splitext(os.path.basename(mod))[0] for mod in f]
128 print("Warning: cannot read list of built-in kernel modules")
130 return module in loaded_modules
134 '''Checks that igb_uio is loaded'''
137 # list of supported modules
138 mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers]
140 # first check if module is loaded
142 if module_is_loaded(mod["Name"]):
145 # check if we have at least one loaded module
146 if True not in [mod["Found"] for mod in mods] and b_flag is not None:
147 print("Warning: no supported DPDK kernel modules are loaded", file=sys.stderr)
149 # change DPDK driver list to only contain drivers that are loaded
150 dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
153 def has_driver(dev_id):
154 '''return true if a device is assigned to a driver. False otherwise'''
155 return "Driver_str" in devices[dev_id]
158 def get_pci_device_details(dev_id, probe_lspci):
159 '''This function gets additional details for a PCI device'''
163 extra_info = subprocess.check_output(["lspci", "-vmmks", dev_id]).splitlines()
164 # parse lspci details
165 for line in extra_info:
168 name, value = line.decode("utf8").split("\t", 1)
169 name = name.strip(":") + "_str"
171 # check for a unix interface name
172 device["Interface"] = ""
173 for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
175 device["Interface"] = \
176 ",".join(os.listdir(os.path.join(base, "net")))
178 # check if a port is used for ssh connection
179 device["Ssh_if"] = False
180 device["Active"] = ""
185 '''This function clears any old data'''
189 def get_device_details(devices_type):
190 '''This function populates the "devices" dictionary. The keys used are
191 the pci addresses (domain:bus:slot.func). The values are themselves
192 dictionaries - one for each NIC.'''
196 # first loop through and read details for all devices
197 # request machine readable format, with numeric IDs and String
199 dev_lines = subprocess.check_output(["lspci", "-Dvmmnnk"]).splitlines()
200 for dev_line in dev_lines:
202 if device_type_match(dev, devices_type):
203 # Replace "Driver" with "Driver_str" to have consistency of
204 # of dictionary key names
205 if "Driver" in dev.keys():
206 dev["Driver_str"] = dev.pop("Driver")
207 if "Module" in dev.keys():
208 dev["Module_str"] = dev.pop("Module")
209 # use dict to make copy of dev
210 devices[dev["Slot"]] = dict(dev)
211 # Clear previous device's data
214 name, value = dev_line.decode("utf8").split("\t", 1)
215 value_list = value.rsplit(' ', 1)
217 # String stored in <name>_str
218 dev[name.rstrip(":") + '_str'] = value_list[0]
220 dev[name.rstrip(":")] = value_list[len(value_list) - 1] \
221 .rstrip("]").lstrip("[")
223 if devices_type == network_devices:
224 # check what is the interface if any for an ssh connection if
225 # any to this host, so we can mark it later.
227 route = subprocess.check_output(["ip", "-o", "route"])
228 # filter out all lines for 169.254 routes
229 route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
230 route.decode().splitlines()))
231 rt_info = route.split()
232 for i in range(len(rt_info) - 1):
233 if rt_info[i] == "dev":
234 ssh_if.append(rt_info[i+1])
236 # based on the basic info, get extended text details
237 for d in devices.keys():
238 if not device_type_match(devices[d], devices_type):
241 # get additional info and add it to existing data
242 devices[d] = devices[d].copy()
243 # No need to probe lspci
244 devices[d].update(get_pci_device_details(d, False).items())
246 if devices_type == network_devices:
248 if _if in devices[d]["Interface"].split(","):
249 devices[d]["Ssh_if"] = True
250 devices[d]["Active"] = "*Active*"
253 # add igb_uio to list of supporting modules if needed
254 if "Module_str" in devices[d]:
255 for driver in dpdk_drivers:
256 if driver not in devices[d]["Module_str"]:
257 devices[d]["Module_str"] = \
258 devices[d]["Module_str"] + ",%s" % driver
260 devices[d]["Module_str"] = ",".join(dpdk_drivers)
262 # make sure the driver and module strings do not have any duplicates
264 modules = devices[d]["Module_str"].split(",")
265 if devices[d]["Driver_str"] in modules:
266 modules.remove(devices[d]["Driver_str"])
267 devices[d]["Module_str"] = ",".join(modules)
270 def device_type_match(dev, devices_type):
271 for i in range(len(devices_type)):
273 [x for x in devices_type[i].values() if x is not None])
275 if dev["Class"][0:2] == devices_type[i]["Class"]:
276 match_count = match_count + 1
277 for key in devices_type[i].keys():
278 if key != 'Class' and devices_type[i][key]:
279 value_list = devices_type[i][key].split(',')
280 for value in value_list:
281 if value.strip(' ') == dev[key]:
282 match_count = match_count + 1
283 # count must be the number of non None parameters to match
284 if match_count == param_count:
288 def dev_id_from_dev_name(dev_name):
289 '''Take a device "name" - a string passed in by user to identify a NIC
290 device, and determine the device id - i.e. the domain:bus:slot.func - for
291 it, which can then be used to index into the devices array'''
293 # check if it's already a suitable index
294 if dev_name in devices:
296 # check if it's an index just missing the domain part
297 if "0000:" + dev_name in devices:
298 return "0000:" + dev_name
300 # check if it's an interface name, e.g. eth1
301 for d in devices.keys():
302 if dev_name in devices[d]["Interface"].split(","):
303 return devices[d]["Slot"]
304 # if nothing else matches - error
305 raise ValueError("Unknown device: %s. "
306 "Please specify device in \"bus:slot.func\" format" % dev_name)
309 def unbind_one(dev_id, force):
310 '''Unbind the device identified by "dev_id" from its current driver'''
311 dev = devices[dev_id]
312 if not has_driver(dev_id):
313 print("Notice: %s %s %s is not currently managed by any driver" %
314 (dev["Slot"], dev["Device_str"], dev["Interface"]), file=sys.stderr)
317 # prevent us disconnecting ourselves
318 if dev["Ssh_if"] and not force:
319 print("Warning: routing table indicates that interface %s is active. "
320 "Skipping unbind" % dev_id, file=sys.stderr)
323 # write to /sys to unbind
324 filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
326 f = open(filename, "a")
328 sys.exit("Error: unbind failed for %s - Cannot open %s" %
334 def bind_one(dev_id, driver, force):
335 '''Bind the device given by "dev_id" to the driver "driver". If the device
336 is already bound to a different driver, it will be unbound first'''
337 dev = devices[dev_id]
338 saved_driver = None # used to rollback any unbind in case of failure
340 # prevent disconnection of our ssh session
341 if dev["Ssh_if"] and not force:
342 print("Warning: routing table indicates that interface %s is active. "
343 "Not modifying" % dev_id, file=sys.stderr)
346 # unbind any existing drivers we don't want
347 if has_driver(dev_id):
348 if dev["Driver_str"] == driver:
349 print("Notice: %s already bound to driver %s, skipping" %
350 (dev_id, driver), file=sys.stderr)
352 saved_driver = dev["Driver_str"]
353 unbind_one(dev_id, force)
354 dev["Driver_str"] = "" # clear driver string
356 # For kernels >= 3.15 driver_override can be used to specify the driver
357 # for a device rather than relying on the driver to provide a positive
358 # match of the device. The existing process of looking up
359 # the vendor and device ID, adding them to the driver new_id,
360 # will erroneously bind other devices too which has the additional burden
361 # of unbinding those devices
362 if driver in dpdk_drivers:
363 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
366 f = open(filename, "w")
368 print("Error: bind failed for %s - Cannot open %s"
369 % (dev_id, filename), file=sys.stderr)
372 f.write("%s" % driver)
375 print("Error: bind failed for %s - Cannot write driver %s to "
376 "PCI ID " % (dev_id, driver), file=sys.stderr)
378 # For kernels < 3.15 use new_id to add PCI id's to the driver
380 filename = "/sys/bus/pci/drivers/%s/new_id" % driver
382 f = open(filename, "w")
384 print("Error: bind failed for %s - Cannot open %s"
385 % (dev_id, filename), file=sys.stderr)
388 # Convert Device and Vendor Id to int to write to new_id
389 f.write("%04x %04x" % (int(dev["Vendor"], 16),
390 int(dev["Device"], 16)))
393 print("Error: bind failed for %s - Cannot write new PCI ID to "
394 "driver %s" % (dev_id, driver), file=sys.stderr)
397 # do the bind by writing to /sys
398 filename = "/sys/bus/pci/drivers/%s/bind" % driver
400 f = open(filename, "a")
402 print("Error: bind failed for %s - Cannot open %s"
403 % (dev_id, filename), file=sys.stderr)
404 if saved_driver is not None: # restore any previous driver
405 bind_one(dev_id, saved_driver, force)
411 # for some reason, closing dev_id after adding a new PCI ID to new_id
412 # results in IOError. however, if the device was successfully bound,
413 # we don't care for any errors and can safely ignore IOError
414 tmp = get_pci_device_details(dev_id, True)
415 if "Driver_str" in tmp and tmp["Driver_str"] == driver:
417 print("Error: bind failed for %s - Cannot bind to driver %s"
418 % (dev_id, driver), file=sys.stderr)
419 if saved_driver is not None: # restore any previous driver
420 bind_one(dev_id, saved_driver, force)
423 # For kernels > 3.15 driver_override is used to bind a device to a driver.
424 # Before unbinding it, overwrite driver_override with empty string so that
425 # the device can be bound to any other driver
426 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
429 f = open(filename, "w")
431 sys.exit("Error: unbind failed for %s - Cannot open %s"
432 % (dev_id, filename))
437 sys.exit("Error: unbind failed for %s - Cannot open %s"
438 % (dev_id, filename))
441 def unbind_all(dev_list, force=False):
442 """Unbind method, takes a list of device locations"""
444 if dev_list[0] == "dpdk":
445 for d in devices.keys():
446 if "Driver_str" in devices[d]:
447 if devices[d]["Driver_str"] in dpdk_drivers:
448 unbind_one(devices[d]["Slot"], force)
452 dev_list = map(dev_id_from_dev_name, dev_list)
453 except ValueError as ex:
461 def bind_all(dev_list, driver, force=False):
462 """Bind method, takes a list of device locations"""
465 # a common user error is to forget to specify the driver the devices need to
466 # be bound to. check if the driver is a valid device, and if it is, show
467 # a meaningful error.
469 dev_id_from_dev_name(driver)
470 # if we've made it this far, this means that the "driver" was a valid
471 # device string, so it's probably not a valid driver name.
472 sys.exit("Error: Driver '%s' does not look like a valid driver. " \
473 "Did you forget to specify the driver to bind devices to?" % driver)
475 # driver generated error - it's not a valid device ID, so all is well
478 # check if we're attempting to bind to a driver that isn't loaded
479 if not module_is_loaded(driver.replace('-', '_')):
480 sys.exit("Error: Driver '%s' is not loaded." % driver)
483 dev_list = map(dev_id_from_dev_name, dev_list)
484 except ValueError as ex:
488 bind_one(d, driver, force)
490 # For kernels < 3.15 when binding devices to a generic driver
491 # (i.e. one that doesn't have a PCI ID table) using new_id, some devices
492 # that are not bound to any other driver could be bound even if no one has
493 # asked them to. hence, we check the list of drivers again, and see if
494 # some of the previously-unbound devices were erroneously bound.
495 if not exists("/sys/bus/pci/devices/%s/driver_override" % d):
496 for d in devices.keys():
497 # skip devices that were already bound or that we know should be bound
498 if "Driver_str" in devices[d] or d in dev_list:
501 # update information about this device
502 devices[d] = dict(devices[d].items() +
503 get_pci_device_details(d, True).items())
505 # check if updated information indicates that the device was bound
506 if "Driver_str" in devices[d]:
510 def display_devices(title, dev_list, extra_params=None):
511 '''Displays to the user the details of a list of devices given in
512 "dev_list". The "extra_params" parameter, if given, should contain a string
513 with %()s fields in it for replacement by the named fields in each
514 device's dictionary.'''
515 strings = [] # this holds the strings to print. We sort before printing
516 print("\n%s" % title)
517 print("="*len(title))
519 strings.append("<none>")
522 if extra_params is not None:
523 strings.append("%s '%s %s' %s" % (dev["Slot"],
528 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
529 # sort before printing, so that the entries appear in PCI order
531 print("\n".join(strings)) # print one per line
533 def show_device_status(devices_type, device_name, if_field=False):
539 # split our list of network devices into the three categories above
540 for d in devices.keys():
541 if device_type_match(devices[d], devices_type):
542 if not has_driver(d):
543 no_drv.append(devices[d])
545 if devices[d]["Driver_str"] in dpdk_drivers:
546 dpdk_drv.append(devices[d])
548 kernel_drv.append(devices[d])
550 n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv)
552 # don't bother displaying anything if there are no devices
554 msg = "No '%s' devices detected" % device_name
557 print("".join('=' * len(msg)))
560 # print each category separately, so we can clearly see what's used by DPDK
562 display_devices("%s devices using DPDK-compatible driver" % device_name,
563 dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s")
567 if_text = "if=%(Interface)s "
568 display_devices("%s devices using kernel driver" % device_name, kernel_drv,
569 if_text + "drv=%(Driver_str)s "
570 "unused=%(Module_str)s %(Active)s")
572 display_devices("Other %s devices" % device_name, no_drv,
573 "unused=%(Module_str)s")
576 '''Function called when the script is passed the "--status" option.
577 Displays to the user what devices are bound to the igb_uio driver, the
578 kernel driver or to no driver'''
580 if status_dev in ["net", "all"]:
581 show_device_status(network_devices, "Network", if_field=True)
583 if status_dev in ["baseband", "all"]:
584 show_device_status(baseband_devices, "Baseband")
586 if status_dev in ["crypto", "all"]:
587 show_device_status(crypto_devices, "Crypto")
589 if status_dev in ["dma", "all"]:
590 show_device_status(dma_devices, "DMA")
592 if status_dev in ["event", "all"]:
593 show_device_status(eventdev_devices, "Eventdev")
595 if status_dev in ["mempool", "all"]:
596 show_device_status(mempool_devices, "Mempool")
598 if status_dev in ["compress", "all"]:
599 show_device_status(compress_devices, "Compress")
601 if status_dev in ["misc", "all"]:
602 show_device_status(misc_devices, "Misc (rawdev)")
604 if status_dev in ["regex", "all"]:
605 show_device_status(regex_devices, "Regex")
609 '''Returns a list containing either:
610 * List of PCI B:D:F matching arg, using shell wildcards e.g. 80:04.*
611 * Only the passed arg if matching list is empty'''
612 sysfs_path = "/sys/bus/pci/devices"
613 for _glob in [arg, '0000:' + arg]:
614 paths = [basename(path) for path in glob(path_join(sysfs_path, _glob))]
621 '''Parses the command-line arguments given by the user and takes the
622 appropriate action for each'''
629 parser = argparse.ArgumentParser(
630 description='Utility to bind and unbind devices from Linux kernel',
631 formatter_class=argparse.RawDescriptionHelpFormatter,
636 To display current device status:
639 To display current network device status:
640 %(prog)s --status-dev net
642 To bind eth1 from the current driver and move to use vfio-pci
643 %(prog)s --bind=vfio-pci eth1
645 To unbind 0000:01:00.0 from using any driver
646 %(prog)s -u 0000:01:00.0
648 To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
649 %(prog)s -b ixgbe 02:00.0 02:00.1
656 help="Print the current status of all known devices.")
659 help="Print the status of given device group.",
660 choices=['baseband', 'compress', 'crypto', 'dma', 'event',
661 'mempool', 'misc', 'net', 'regex'])
662 bind_group = parser.add_mutually_exclusive_group()
663 bind_group.add_argument(
667 help="Select the driver to use or \"none\" to unbind the device")
668 bind_group.add_argument(
672 help="Unbind a device (equivalent to \"-b none\")")
677 Override restriction on binding devices in use by Linux"
678 WARNING: This can lead to loss of network connection and should be used with caution.
685 Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax.
686 For devices bound to Linux kernel drivers, they may be referred to by interface name.
689 opt = parser.parse_args()
693 status_dev = opt.status_dev
705 if not b_flag and not status_flag:
706 print("Error: No action specified for devices. "
707 "Please give a --bind, --ubind or --status option",
712 if b_flag and not args:
713 print("Error: No devices specified.", file=sys.stderr)
717 # resolve any PCI globs in the args
720 new_args.extend(pci_glob(arg))
723 def do_arg_actions():
724 '''do the actual action requested by the user'''
730 if b_flag in ["none", "None"]:
731 unbind_all(args, force_flag)
732 elif b_flag is not None:
733 bind_all(args, b_flag, force_flag)
735 if b_flag is not None:
737 # refresh if we have changed anything
738 get_device_details(network_devices)
739 get_device_details(baseband_devices)
740 get_device_details(crypto_devices)
741 get_device_details(dma_devices)
742 get_device_details(eventdev_devices)
743 get_device_details(mempool_devices)
744 get_device_details(compress_devices)
745 get_device_details(regex_devices)
746 get_device_details(misc_devices)
751 '''program main function'''
752 # check if lspci is installed, suppress any output
753 with open(os.devnull, 'w') as devnull:
754 ret = subprocess.call(['which', 'lspci'],
755 stdout=devnull, stderr=devnull)
757 sys.exit("'lspci' not found - please install 'pciutils'")
761 get_device_details(network_devices)
762 get_device_details(baseband_devices)
763 get_device_details(crypto_devices)
764 get_device_details(dma_devices)
765 get_device_details(eventdev_devices)
766 get_device_details(mempool_devices)
767 get_device_details(compress_devices)
768 get_device_details(regex_devices)
769 get_device_details(misc_devices)
772 if __name__ == "__main__":