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