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