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 if f.read(1) == "1": 494 return 495 except OSError as err: 496 sys.exit(f"Error: failed to check unsafe noiommu mode - Cannot open {filename}: {err}") 497 498 if not noiommu_flag: 499 sys.exit("Error: IOMMU support is disabled, use --noiommu-mode for binding in noiommu mode") 500 501 try: 502 with open(filename, "w") as f: 503 f.write("1") 504 except OSError as err: 505 sys.exit(f"Error: failed to enable unsafe noiommu mode - Cannot open {filename}: {err}") 506 print("Warning: enabling unsafe no IOMMU mode for VFIO drivers") 507 508 509def bind_all(dev_list, driver, force=False): 510 """Bind method, takes a list of device locations""" 511 global devices 512 513 # a common user error is to forget to specify the driver the devices need to 514 # be bound to. check if the driver is a valid device, and if it is, show 515 # a meaningful error. 516 try: 517 dev_id_from_dev_name(driver) 518 # if we've made it this far, this means that the "driver" was a valid 519 # device string, so it's probably not a valid driver name. 520 sys.exit("Error: Driver '%s' does not look like a valid driver. " 521 "Did you forget to specify the driver to bind devices to?" % driver) 522 except ValueError: 523 # driver generated error - it's not a valid device ID, so all is well 524 pass 525 526 # check if we're attempting to bind to a driver that isn't loaded 527 if not module_is_loaded(driver.replace('-', '_')): 528 sys.exit("Error: Driver '%s' is not loaded." % driver) 529 530 try: 531 dev_list = map(dev_id_from_dev_name, dev_list) 532 except ValueError as ex: 533 sys.exit(ex) 534 535 # check for IOMMU support 536 if driver == "vfio-pci" and not has_iommu(): 537 check_noiommu_mode() 538 539 for d in dev_list: 540 bind_one(d, driver, force) 541 542 # For kernels < 3.15 when binding devices to a generic driver 543 # (i.e. one that doesn't have a PCI ID table) using new_id, some devices 544 # that are not bound to any other driver could be bound even if no one has 545 # asked them to. hence, we check the list of drivers again, and see if 546 # some of the previously-unbound devices were erroneously bound. 547 if not exists("/sys/bus/pci/devices/%s/driver_override" % d): 548 for d in devices.keys(): 549 # skip devices that were already bound or that we know should be bound 550 if "Driver_str" in devices[d] or d in dev_list: 551 continue 552 553 # update information about this device 554 devices[d] = dict(devices[d].items() 555 + get_pci_device_details(d, True).items()) 556 557 # check if updated information indicates that the device was bound 558 if "Driver_str" in devices[d]: 559 unbind_one(d, force) 560 561 562def display_devices(title, dev_list, extra_params=None): 563 '''Displays to the user the details of a list of devices given in 564 "dev_list". The "extra_params" parameter, if given, should contain a string 565 with %()s fields in it for replacement by the named fields in each 566 device's dictionary.''' 567 strings = [] # this holds the strings to print. We sort before printing 568 print("\n%s" % title) 569 print("=" * len(title)) 570 if not dev_list: 571 strings.append("<none>") 572 else: 573 for dev in dev_list: 574 if extra_params is not None: 575 strings.append("%s '%s %s' %s" % (dev["Slot"], 576 dev["Device_str"], 577 dev["Device"], 578 extra_params % dev)) 579 else: 580 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"])) 581 # sort before printing, so that the entries appear in PCI order 582 strings.sort() 583 print("\n".join(strings)) # print one per line 584 585 586def show_device_status(devices_type, device_name, if_field=False): 587 global dpdk_drivers 588 kernel_drv = [] 589 dpdk_drv = [] 590 no_drv = [] 591 592 # split our list of network devices into the three categories above 593 for d in devices.keys(): 594 if device_type_match(devices[d], devices_type): 595 if not has_driver(d): 596 no_drv.append(devices[d]) 597 continue 598 if devices[d]["Driver_str"] in dpdk_drivers: 599 dpdk_drv.append(devices[d]) 600 else: 601 kernel_drv.append(devices[d]) 602 603 n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv) 604 605 # don't bother displaying anything if there are no devices 606 if n_devs == 0: 607 msg = "No '%s' devices detected" % device_name 608 print("") 609 print(msg) 610 print("".join('=' * len(msg))) 611 return 612 613 # print each category separately, so we can clearly see what's used by DPDK 614 if dpdk_drv: 615 display_devices("%s devices using DPDK-compatible driver" % device_name, 616 dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s") 617 if kernel_drv: 618 if_text = "" 619 if if_field: 620 if_text = "if=%(Interface)s " 621 display_devices("%s devices using kernel driver" % device_name, kernel_drv, 622 if_text + "drv=%(Driver_str)s " 623 "unused=%(Module_str)s %(Active)s") 624 if no_drv: 625 display_devices("Other %s devices" % device_name, no_drv, 626 "unused=%(Module_str)s") 627 628 629def show_status(): 630 '''Function called when the script is passed the "--status" option. 631 Displays to the user what devices are bound to the igb_uio driver, the 632 kernel driver or to no driver''' 633 634 if status_dev in ["net", "all"]: 635 show_device_status(network_devices, "Network", if_field=True) 636 637 if status_dev in ["baseband", "all"]: 638 show_device_status(baseband_devices, "Baseband") 639 640 if status_dev in ["crypto", "all"]: 641 show_device_status(crypto_devices, "Crypto") 642 643 if status_dev in ["dma", "all"]: 644 show_device_status(dma_devices, "DMA") 645 646 if status_dev in ["event", "all"]: 647 show_device_status(eventdev_devices, "Eventdev") 648 649 if status_dev in ["mempool", "all"]: 650 show_device_status(mempool_devices, "Mempool") 651 652 if status_dev in ["compress", "all"]: 653 show_device_status(compress_devices, "Compress") 654 655 if status_dev in ["misc", "all"]: 656 show_device_status(misc_devices, "Misc (rawdev)") 657 658 if status_dev in ["regex", "all"]: 659 show_device_status(regex_devices, "Regex") 660 661 if status_dev in ["ml", "all"]: 662 show_device_status(ml_devices, "ML") 663 664 665def pci_glob(arg): 666 '''Returns a list containing either: 667 * List of PCI B:D:F matching arg, using shell wildcards e.g. 80:04.* 668 * Only the passed arg if matching list is empty''' 669 sysfs_path = "/sys/bus/pci/devices" 670 for _glob in [arg, '0000:' + arg]: 671 paths = [basename(path) for path in glob(path_join(sysfs_path, _glob))] 672 if paths: 673 return paths 674 return [arg] 675 676 677def parse_args(): 678 '''Parses the command-line arguments given by the user and takes the 679 appropriate action for each''' 680 global b_flag 681 global status_flag 682 global status_dev 683 global force_flag 684 global noiommu_flag 685 global args 686 687 parser = argparse.ArgumentParser( 688 description='Utility to bind and unbind devices from Linux kernel', 689 formatter_class=argparse.RawDescriptionHelpFormatter, 690 epilog=""" 691Examples: 692--------- 693 694To display current device status: 695 %(prog)s --status 696 697To display current network device status: 698 %(prog)s --status-dev net 699 700To bind eth1 from the current driver and move to use vfio-pci 701 %(prog)s --bind=vfio-pci eth1 702 703To unbind 0000:01:00.0 from using any driver 704 %(prog)s -u 0000:01:00.0 705 706To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver 707 %(prog)s -b ixgbe 02:00.0 02:00.1 708""") 709 710 parser.add_argument( 711 '-s', 712 '--status', 713 action='store_true', 714 help="Print the current status of all known devices.") 715 parser.add_argument( 716 '--status-dev', 717 help="Print the status of given device group.", 718 choices=['baseband', 'compress', 'crypto', 'dma', 'event', 719 'mempool', 'misc', 'net', 'regex', 'ml']) 720 bind_group = parser.add_mutually_exclusive_group() 721 bind_group.add_argument( 722 '-b', 723 '--bind', 724 metavar='DRIVER', 725 help="Select the driver to use or \"none\" to unbind the device") 726 bind_group.add_argument( 727 '-u', 728 '--unbind', 729 action='store_true', 730 help="Unbind a device (equivalent to \"-b none\")") 731 parser.add_argument( 732 '--noiommu-mode', 733 action='store_true', 734 help="If IOMMU is not available, enable no IOMMU mode for VFIO drivers") 735 parser.add_argument( 736 '--force', 737 action='store_true', 738 help=""" 739Override restriction on binding devices in use by Linux" 740WARNING: This can lead to loss of network connection and should be used with caution. 741""") 742 parser.add_argument( 743 'devices', 744 metavar='DEVICE', 745 nargs='*', 746 help=""" 747Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax. 748For devices bound to Linux kernel drivers, they may be referred to by interface name. 749""") 750 751 opt = parser.parse_args() 752 753 if opt.status_dev: 754 status_flag = True 755 status_dev = opt.status_dev 756 if opt.status: 757 status_flag = True 758 status_dev = "all" 759 if opt.force: 760 force_flag = True 761 if opt.noiommu_mode: 762 noiommu_flag = True 763 if opt.bind: 764 b_flag = opt.bind 765 elif opt.unbind: 766 b_flag = "none" 767 args = opt.devices 768 769 if not b_flag and not status_flag: 770 print("Error: No action specified for devices. " 771 "Please give a --bind, --ubind or --status option", 772 file=sys.stderr) 773 parser.print_usage() 774 sys.exit(1) 775 776 if b_flag and not args: 777 print("Error: No devices specified.", file=sys.stderr) 778 parser.print_usage() 779 sys.exit(1) 780 781 # resolve any PCI globs in the args 782 new_args = [] 783 for arg in args: 784 new_args.extend(pci_glob(arg)) 785 args = new_args 786 787 788def do_arg_actions(): 789 '''do the actual action requested by the user''' 790 global b_flag 791 global status_flag 792 global force_flag 793 global args 794 795 if b_flag in ["none", "None"]: 796 unbind_all(args, force_flag) 797 elif b_flag is not None: 798 bind_all(args, b_flag, force_flag) 799 if status_flag: 800 if b_flag is not None: 801 clear_data() 802 # refresh if we have changed anything 803 get_device_details(network_devices) 804 get_device_details(baseband_devices) 805 get_device_details(crypto_devices) 806 get_device_details(dma_devices) 807 get_device_details(eventdev_devices) 808 get_device_details(mempool_devices) 809 get_device_details(compress_devices) 810 get_device_details(regex_devices) 811 get_device_details(ml_devices) 812 get_device_details(misc_devices) 813 show_status() 814 815 816def main(): 817 '''program main function''' 818 # check if lspci is installed, suppress any output 819 with open(os.devnull, 'w') as devnull: 820 ret = subprocess.call(['which', 'lspci'], 821 stdout=devnull, stderr=devnull) 822 if ret != 0: 823 sys.exit("'lspci' not found - please install 'pciutils'") 824 parse_args() 825 check_modules() 826 clear_data() 827 get_device_details(network_devices) 828 get_device_details(baseband_devices) 829 get_device_details(crypto_devices) 830 get_device_details(dma_devices) 831 get_device_details(eventdev_devices) 832 get_device_details(mempool_devices) 833 get_device_details(compress_devices) 834 get_device_details(regex_devices) 835 get_device_details(ml_devices) 836 get_device_details(misc_devices) 837 do_arg_actions() 838 839 840if __name__ == "__main__": 841 main() 842