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]
74 eventdev_devices = [cavium_sso, cavium_tim, intel_dlb, octeontx2_sso]
75 mempool_devices = [cavium_fpa, octeontx2_npa]
76 compress_devices = [cavium_zip]
77 regex_devices = [octeontx2_ree]
78 misc_devices = [cnxk_bphy, cnxk_bphy_cgx, cnxk_inl_dev, intel_ioat_bdw,
79 intel_ioat_skx, intel_ioat_icx, intel_idxd_spr, intel_ntb_skx,
80 intel_ntb_icx, octeontx2_dma]
82 # global dict ethernet devices present. Dictionary indexed by PCI address.
83 # Each device within this is itself a dictionary of device properties
85 # list of supported DPDK drivers
86 dpdk_drivers = ["igb_uio", "vfio-pci", "uio_pci_generic"]
87 # list of currently loaded kernel modules
90 # command-line arg flags
96 # check if a specific kernel module is loaded
97 def module_is_loaded(module):
100 if module == 'vfio_pci':
104 return module in loaded_modules
106 # Get list of sysfs modules (both built-in and dynamically loaded)
107 sysfs_path = '/sys/module/'
109 # Get the list of directories in sysfs_path
110 sysfs_mods = [m for m in os.listdir(sysfs_path)
111 if os.path.isdir(os.path.join(sysfs_path, m))]
113 # special case for vfio_pci (module is named vfio-pci,
114 # but its .ko is named vfio_pci)
115 sysfs_mods = [a if a != 'vfio_pci' else 'vfio-pci' for a in sysfs_mods]
117 loaded_modules = sysfs_mods
119 # add built-in modules as loaded
120 release = platform.uname().release
121 filename = os.path.join("/lib/modules/", release, "modules.builtin")
122 if os.path.exists(filename):
124 with open(filename) as f:
125 loaded_modules += [os.path.splitext(os.path.basename(mod))[0] for mod in f]
127 print("Warning: cannot read list of built-in kernel modules")
129 return module in loaded_modules
133 '''Checks that igb_uio is loaded'''
136 # list of supported modules
137 mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers]
139 # first check if module is loaded
141 if module_is_loaded(mod["Name"]):
144 # check if we have at least one loaded module
145 if True not in [mod["Found"] for mod in mods] and b_flag is not None:
146 print("Warning: no supported DPDK kernel modules are loaded", file=sys.stderr)
148 # change DPDK driver list to only contain drivers that are loaded
149 dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
152 def has_driver(dev_id):
153 '''return true if a device is assigned to a driver. False otherwise'''
154 return "Driver_str" in devices[dev_id]
157 def get_pci_device_details(dev_id, probe_lspci):
158 '''This function gets additional details for a PCI device'''
162 extra_info = subprocess.check_output(["lspci", "-vmmks", dev_id]).splitlines()
163 # parse lspci details
164 for line in extra_info:
167 name, value = line.decode("utf8").split("\t", 1)
168 name = name.strip(":") + "_str"
170 # check for a unix interface name
171 device["Interface"] = ""
172 for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
174 device["Interface"] = \
175 ",".join(os.listdir(os.path.join(base, "net")))
177 # check if a port is used for ssh connection
178 device["Ssh_if"] = False
179 device["Active"] = ""
184 '''This function clears any old data'''
188 def get_device_details(devices_type):
189 '''This function populates the "devices" dictionary. The keys used are
190 the pci addresses (domain:bus:slot.func). The values are themselves
191 dictionaries - one for each NIC.'''
195 # first loop through and read details for all devices
196 # request machine readable format, with numeric IDs and String
198 dev_lines = subprocess.check_output(["lspci", "-Dvmmnnk"]).splitlines()
199 for dev_line in dev_lines:
201 if device_type_match(dev, devices_type):
202 # Replace "Driver" with "Driver_str" to have consistency of
203 # of dictionary key names
204 if "Driver" in dev.keys():
205 dev["Driver_str"] = dev.pop("Driver")
206 if "Module" in dev.keys():
207 dev["Module_str"] = dev.pop("Module")
208 # use dict to make copy of dev
209 devices[dev["Slot"]] = dict(dev)
210 # Clear previous device's data
213 name, value = dev_line.decode("utf8").split("\t", 1)
214 value_list = value.rsplit(' ', 1)
216 # String stored in <name>_str
217 dev[name.rstrip(":") + '_str'] = value_list[0]
219 dev[name.rstrip(":")] = value_list[len(value_list) - 1] \
220 .rstrip("]").lstrip("[")
222 if devices_type == network_devices:
223 # check what is the interface if any for an ssh connection if
224 # any to this host, so we can mark it later.
226 route = subprocess.check_output(["ip", "-o", "route"])
227 # filter out all lines for 169.254 routes
228 route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
229 route.decode().splitlines()))
230 rt_info = route.split()
231 for i in range(len(rt_info) - 1):
232 if rt_info[i] == "dev":
233 ssh_if.append(rt_info[i+1])
235 # based on the basic info, get extended text details
236 for d in devices.keys():
237 if not device_type_match(devices[d], devices_type):
240 # get additional info and add it to existing data
241 devices[d] = devices[d].copy()
242 # No need to probe lspci
243 devices[d].update(get_pci_device_details(d, False).items())
245 if devices_type == network_devices:
247 if _if in devices[d]["Interface"].split(","):
248 devices[d]["Ssh_if"] = True
249 devices[d]["Active"] = "*Active*"
252 # add igb_uio to list of supporting modules if needed
253 if "Module_str" in devices[d]:
254 for driver in dpdk_drivers:
255 if driver not in devices[d]["Module_str"]:
256 devices[d]["Module_str"] = \
257 devices[d]["Module_str"] + ",%s" % driver
259 devices[d]["Module_str"] = ",".join(dpdk_drivers)
261 # make sure the driver and module strings do not have any duplicates
263 modules = devices[d]["Module_str"].split(",")
264 if devices[d]["Driver_str"] in modules:
265 modules.remove(devices[d]["Driver_str"])
266 devices[d]["Module_str"] = ",".join(modules)
269 def device_type_match(dev, devices_type):
270 for i in range(len(devices_type)):
272 [x for x in devices_type[i].values() if x is not None])
274 if dev["Class"][0:2] == devices_type[i]["Class"]:
275 match_count = match_count + 1
276 for key in devices_type[i].keys():
277 if key != 'Class' and devices_type[i][key]:
278 value_list = devices_type[i][key].split(',')
279 for value in value_list:
280 if value.strip(' ') == dev[key]:
281 match_count = match_count + 1
282 # count must be the number of non None parameters to match
283 if match_count == param_count:
287 def dev_id_from_dev_name(dev_name):
288 '''Take a device "name" - a string passed in by user to identify a NIC
289 device, and determine the device id - i.e. the domain:bus:slot.func - for
290 it, which can then be used to index into the devices array'''
292 # check if it's already a suitable index
293 if dev_name in devices:
295 # check if it's an index just missing the domain part
296 if "0000:" + dev_name in devices:
297 return "0000:" + dev_name
299 # check if it's an interface name, e.g. eth1
300 for d in devices.keys():
301 if dev_name in devices[d]["Interface"].split(","):
302 return devices[d]["Slot"]
303 # if nothing else matches - error
304 raise ValueError("Unknown device: %s. "
305 "Please specify device in \"bus:slot.func\" format" % dev_name)
308 def unbind_one(dev_id, force):
309 '''Unbind the device identified by "dev_id" from its current driver'''
310 dev = devices[dev_id]
311 if not has_driver(dev_id):
312 print("Notice: %s %s %s is not currently managed by any driver" %
313 (dev["Slot"], dev["Device_str"], dev["Interface"]), file=sys.stderr)
316 # prevent us disconnecting ourselves
317 if dev["Ssh_if"] and not force:
318 print("Warning: routing table indicates that interface %s is active. "
319 "Skipping unbind" % dev_id, file=sys.stderr)
322 # write to /sys to unbind
323 filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
325 f = open(filename, "a")
327 sys.exit("Error: unbind failed for %s - Cannot open %s" %
333 def bind_one(dev_id, driver, force):
334 '''Bind the device given by "dev_id" to the driver "driver". If the device
335 is already bound to a different driver, it will be unbound first'''
336 dev = devices[dev_id]
337 saved_driver = None # used to rollback any unbind in case of failure
339 # prevent disconnection of our ssh session
340 if dev["Ssh_if"] and not force:
341 print("Warning: routing table indicates that interface %s is active. "
342 "Not modifying" % dev_id, file=sys.stderr)
345 # unbind any existing drivers we don't want
346 if has_driver(dev_id):
347 if dev["Driver_str"] == driver:
348 print("Notice: %s already bound to driver %s, skipping" %
349 (dev_id, driver), file=sys.stderr)
351 saved_driver = dev["Driver_str"]
352 unbind_one(dev_id, force)
353 dev["Driver_str"] = "" # clear driver string
355 # For kernels >= 3.15 driver_override can be used to specify the driver
356 # for a device rather than relying on the driver to provide a positive
357 # match of the device. The existing process of looking up
358 # the vendor and device ID, adding them to the driver new_id,
359 # will erroneously bind other devices too which has the additional burden
360 # of unbinding those devices
361 if driver in dpdk_drivers:
362 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
365 f = open(filename, "w")
367 print("Error: bind failed for %s - Cannot open %s"
368 % (dev_id, filename), file=sys.stderr)
371 f.write("%s" % driver)
374 print("Error: bind failed for %s - Cannot write driver %s to "
375 "PCI ID " % (dev_id, driver), file=sys.stderr)
377 # For kernels < 3.15 use new_id to add PCI id's to the driver
379 filename = "/sys/bus/pci/drivers/%s/new_id" % driver
381 f = open(filename, "w")
383 print("Error: bind failed for %s - Cannot open %s"
384 % (dev_id, filename), file=sys.stderr)
387 # Convert Device and Vendor Id to int to write to new_id
388 f.write("%04x %04x" % (int(dev["Vendor"], 16),
389 int(dev["Device"], 16)))
392 print("Error: bind failed for %s - Cannot write new PCI ID to "
393 "driver %s" % (dev_id, driver), file=sys.stderr)
396 # do the bind by writing to /sys
397 filename = "/sys/bus/pci/drivers/%s/bind" % driver
399 f = open(filename, "a")
401 print("Error: bind failed for %s - Cannot open %s"
402 % (dev_id, filename), file=sys.stderr)
403 if saved_driver is not None: # restore any previous driver
404 bind_one(dev_id, saved_driver, force)
410 # for some reason, closing dev_id after adding a new PCI ID to new_id
411 # results in IOError. however, if the device was successfully bound,
412 # we don't care for any errors and can safely ignore IOError
413 tmp = get_pci_device_details(dev_id, True)
414 if "Driver_str" in tmp and tmp["Driver_str"] == driver:
416 print("Error: bind failed for %s - Cannot bind to driver %s"
417 % (dev_id, driver), file=sys.stderr)
418 if saved_driver is not None: # restore any previous driver
419 bind_one(dev_id, saved_driver, force)
422 # For kernels > 3.15 driver_override is used to bind a device to a driver.
423 # Before unbinding it, overwrite driver_override with empty string so that
424 # the device can be bound to any other driver
425 filename = "/sys/bus/pci/devices/%s/driver_override" % dev_id
428 f = open(filename, "w")
430 sys.exit("Error: unbind failed for %s - Cannot open %s"
431 % (dev_id, filename))
436 sys.exit("Error: unbind failed for %s - Cannot open %s"
437 % (dev_id, filename))
440 def unbind_all(dev_list, force=False):
441 """Unbind method, takes a list of device locations"""
443 if dev_list[0] == "dpdk":
444 for d in devices.keys():
445 if "Driver_str" in devices[d]:
446 if devices[d]["Driver_str"] in dpdk_drivers:
447 unbind_one(devices[d]["Slot"], force)
451 dev_list = map(dev_id_from_dev_name, dev_list)
452 except ValueError as ex:
460 def bind_all(dev_list, driver, force=False):
461 """Bind method, takes a list of device locations"""
464 # a common user error is to forget to specify the driver the devices need to
465 # be bound to. check if the driver is a valid device, and if it is, show
466 # a meaningful error.
468 dev_id_from_dev_name(driver)
469 # if we've made it this far, this means that the "driver" was a valid
470 # device string, so it's probably not a valid driver name.
471 sys.exit("Error: Driver '%s' does not look like a valid driver. " \
472 "Did you forget to specify the driver to bind devices to?" % driver)
474 # driver generated error - it's not a valid device ID, so all is well
477 # check if we're attempting to bind to a driver that isn't loaded
478 if not module_is_loaded(driver.replace('-', '_')):
479 sys.exit("Error: Driver '%s' is not loaded." % driver)
482 dev_list = map(dev_id_from_dev_name, dev_list)
483 except ValueError as ex:
487 bind_one(d, driver, force)
489 # For kernels < 3.15 when binding devices to a generic driver
490 # (i.e. one that doesn't have a PCI ID table) using new_id, some devices
491 # that are not bound to any other driver could be bound even if no one has
492 # asked them to. hence, we check the list of drivers again, and see if
493 # some of the previously-unbound devices were erroneously bound.
494 if not exists("/sys/bus/pci/devices/%s/driver_override" % d):
495 for d in devices.keys():
496 # skip devices that were already bound or that we know should be bound
497 if "Driver_str" in devices[d] or d in dev_list:
500 # update information about this device
501 devices[d] = dict(devices[d].items() +
502 get_pci_device_details(d, True).items())
504 # check if updated information indicates that the device was bound
505 if "Driver_str" in devices[d]:
509 def display_devices(title, dev_list, extra_params=None):
510 '''Displays to the user the details of a list of devices given in
511 "dev_list". The "extra_params" parameter, if given, should contain a string
512 with %()s fields in it for replacement by the named fields in each
513 device's dictionary.'''
514 strings = [] # this holds the strings to print. We sort before printing
515 print("\n%s" % title)
516 print("="*len(title))
518 strings.append("<none>")
521 if extra_params is not None:
522 strings.append("%s '%s %s' %s" % (dev["Slot"],
527 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
528 # sort before printing, so that the entries appear in PCI order
530 print("\n".join(strings)) # print one per line
532 def show_device_status(devices_type, device_name, if_field=False):
538 # split our list of network devices into the three categories above
539 for d in devices.keys():
540 if device_type_match(devices[d], devices_type):
541 if not has_driver(d):
542 no_drv.append(devices[d])
544 if devices[d]["Driver_str"] in dpdk_drivers:
545 dpdk_drv.append(devices[d])
547 kernel_drv.append(devices[d])
549 n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv)
551 # don't bother displaying anything if there are no devices
553 msg = "No '%s' devices detected" % device_name
556 print("".join('=' * len(msg)))
559 # print each category separately, so we can clearly see what's used by DPDK
561 display_devices("%s devices using DPDK-compatible driver" % device_name,
562 dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s")
566 if_text = "if=%(Interface)s "
567 display_devices("%s devices using kernel driver" % device_name, kernel_drv,
568 if_text + "drv=%(Driver_str)s "
569 "unused=%(Module_str)s %(Active)s")
571 display_devices("Other %s devices" % device_name, no_drv,
572 "unused=%(Module_str)s")
575 '''Function called when the script is passed the "--status" option.
576 Displays to the user what devices are bound to the igb_uio driver, the
577 kernel driver or to no driver'''
579 if status_dev in ["net", "all"]:
580 show_device_status(network_devices, "Network", if_field=True)
582 if status_dev in ["baseband", "all"]:
583 show_device_status(baseband_devices, "Baseband")
585 if status_dev in ["crypto", "all"]:
586 show_device_status(crypto_devices, "Crypto")
588 if status_dev in ["event", "all"]:
589 show_device_status(eventdev_devices, "Eventdev")
591 if status_dev in ["mempool", "all"]:
592 show_device_status(mempool_devices, "Mempool")
594 if status_dev in ["compress", "all"]:
595 show_device_status(compress_devices, "Compress")
597 if status_dev in ["misc", "all"]:
598 show_device_status(misc_devices, "Misc (rawdev)")
600 if status_dev in ["regex", "all"]:
601 show_device_status(regex_devices, "Regex")
605 '''Returns a list containing either:
606 * List of PCI B:D:F matching arg, using shell wildcards e.g. 80:04.*
607 * Only the passed arg if matching list is empty'''
608 sysfs_path = "/sys/bus/pci/devices"
609 for _glob in [arg, '0000:' + arg]:
610 paths = [basename(path) for path in glob(path_join(sysfs_path, _glob))]
617 '''Parses the command-line arguments given by the user and takes the
618 appropriate action for each'''
625 parser = argparse.ArgumentParser(
626 description='Utility to bind and unbind devices from Linux kernel',
627 formatter_class=argparse.RawDescriptionHelpFormatter,
632 To display current device status:
635 To display current network device status:
636 %(prog)s --status-dev net
638 To bind eth1 from the current driver and move to use vfio-pci
639 %(prog)s --bind=vfio-pci eth1
641 To unbind 0000:01:00.0 from using any driver
642 %(prog)s -u 0000:01:00.0
644 To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
645 %(prog)s -b ixgbe 02:00.0 02:00.1
652 help="Print the current status of all known devices.")
655 help="Print the status of given device group.",
656 choices=['baseband', 'compress', 'crypto', 'event',
657 'mempool', 'misc', 'net', 'regex'])
658 bind_group = parser.add_mutually_exclusive_group()
659 bind_group.add_argument(
663 help="Select the driver to use or \"none\" to unbind the device")
664 bind_group.add_argument(
668 help="Unbind a device (equivalent to \"-b none\")")
673 Override restriction on binding devices in use by Linux"
674 WARNING: This can lead to loss of network connection and should be used with caution.
681 Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax.
682 For devices bound to Linux kernel drivers, they may be referred to by interface name.
685 opt = parser.parse_args()
689 status_dev = opt.status_dev
701 if not b_flag and not status_flag:
702 print("Error: No action specified for devices. "
703 "Please give a --bind, --ubind or --status option",
708 if b_flag and not args:
709 print("Error: No devices specified.", file=sys.stderr)
713 # resolve any PCI globs in the args
716 new_args.extend(pci_glob(arg))
719 def do_arg_actions():
720 '''do the actual action requested by the user'''
726 if b_flag in ["none", "None"]:
727 unbind_all(args, force_flag)
728 elif b_flag is not None:
729 bind_all(args, b_flag, force_flag)
731 if b_flag is not None:
733 # refresh if we have changed anything
734 get_device_details(network_devices)
735 get_device_details(baseband_devices)
736 get_device_details(crypto_devices)
737 get_device_details(eventdev_devices)
738 get_device_details(mempool_devices)
739 get_device_details(compress_devices)
740 get_device_details(regex_devices)
741 get_device_details(misc_devices)
746 '''program main function'''
747 # check if lspci is installed, suppress any output
748 with open(os.devnull, 'w') as devnull:
749 ret = subprocess.call(['which', 'lspci'],
750 stdout=devnull, stderr=devnull)
752 sys.exit("'lspci' not found - please install 'pciutils'")
756 get_device_details(network_devices)
757 get_device_details(baseband_devices)
758 get_device_details(crypto_devices)
759 get_device_details(eventdev_devices)
760 get_device_details(mempool_devices)
761 get_device_details(compress_devices)
762 get_device_details(regex_devices)
763 get_device_details(misc_devices)
766 if __name__ == "__main__":