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] 74eventdev_devices = [cavium_sso, cavium_tim, intel_dlb, octeontx2_sso] 75mempool_devices = [cavium_fpa, octeontx2_npa] 76compress_devices = [cavium_zip] 77regex_devices = [octeontx2_ree] 78misc_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] 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# check if a specific kernel module is loaded 97def module_is_loaded(module): 98 global loaded_modules 99 100 if module == 'vfio_pci': 101 module = 'vfio-pci' 102 103 if loaded_modules: 104 return module in loaded_modules 105 106 # Get list of sysfs modules (both built-in and dynamically loaded) 107 sysfs_path = '/sys/module/' 108 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))] 112 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] 116 117 loaded_modules = sysfs_mods 118 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): 123 try: 124 with open(filename) as f: 125 loaded_modules += [os.path.splitext(os.path.basename(mod))[0] for mod in f] 126 except IOError: 127 print("Warning: cannot read list of built-in kernel modules") 128 129 return module in loaded_modules 130 131 132def check_modules(): 133 '''Checks that igb_uio is loaded''' 134 global dpdk_drivers 135 136 # list of supported modules 137 mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers] 138 139 # first check if module is loaded 140 for mod in mods: 141 if module_is_loaded(mod["Name"]): 142 mod["Found"] = True 143 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) 147 148 # change DPDK driver list to only contain drivers that are loaded 149 dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]] 150 151 152def 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] 155 156 157def get_pci_device_details(dev_id, probe_lspci): 158 '''This function gets additional details for a PCI device''' 159 device = {} 160 161 if probe_lspci: 162 extra_info = subprocess.check_output(["lspci", "-vmmks", dev_id]).splitlines() 163 # parse lspci details 164 for line in extra_info: 165 if not line: 166 continue 167 name, value = line.decode("utf8").split("\t", 1) 168 name = name.strip(":") + "_str" 169 device[name] = value 170 # check for a unix interface name 171 device["Interface"] = "" 172 for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id): 173 if "net" in dirs: 174 device["Interface"] = \ 175 ",".join(os.listdir(os.path.join(base, "net"))) 176 break 177 # check if a port is used for ssh connection 178 device["Ssh_if"] = False 179 device["Active"] = "" 180 181 return device 182 183def clear_data(): 184 '''This function clears any old data''' 185 global devices 186 devices = {} 187 188def 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.''' 192 global devices 193 global dpdk_drivers 194 195 # first loop through and read details for all devices 196 # request machine readable format, with numeric IDs and String 197 dev = {} 198 dev_lines = subprocess.check_output(["lspci", "-Dvmmnnk"]).splitlines() 199 for dev_line in dev_lines: 200 if not dev_line: 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 211 dev = {} 212 else: 213 name, value = dev_line.decode("utf8").split("\t", 1) 214 value_list = value.rsplit(' ', 1) 215 if value_list: 216 # String stored in <name>_str 217 dev[name.rstrip(":") + '_str'] = value_list[0] 218 # Numeric IDs 219 dev[name.rstrip(":")] = value_list[len(value_list) - 1] \ 220 .rstrip("]").lstrip("[") 221 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. 225 ssh_if = [] 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]) 234 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): 238 continue 239 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()) 244 245 if devices_type == network_devices: 246 for _if in ssh_if: 247 if _if in devices[d]["Interface"].split(","): 248 devices[d]["Ssh_if"] = True 249 devices[d]["Active"] = "*Active*" 250 break 251 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 258 else: 259 devices[d]["Module_str"] = ",".join(dpdk_drivers) 260 261 # make sure the driver and module strings do not have any duplicates 262 if has_driver(d): 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) 267 268 269def device_type_match(dev, devices_type): 270 for i in range(len(devices_type)): 271 param_count = len( 272 [x for x in devices_type[i].values() if x is not None]) 273 match_count = 0 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: 284 return True 285 return False 286 287def 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''' 291 292 # check if it's already a suitable index 293 if dev_name in devices: 294 return dev_name 295 # check if it's an index just missing the domain part 296 if "0000:" + dev_name in devices: 297 return "0000:" + dev_name 298 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) 306 307 308def 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) 314 return 315 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) 320 return 321 322 # write to /sys to unbind 323 filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"] 324 try: 325 f = open(filename, "a") 326 except: 327 sys.exit("Error: unbind failed for %s - Cannot open %s" % 328 (dev_id, filename)) 329 f.write(dev_id) 330 f.close() 331 332 333def 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 338 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) 343 return 344 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) 350 return 351 saved_driver = dev["Driver_str"] 352 unbind_one(dev_id, force) 353 dev["Driver_str"] = "" # clear driver string 354 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 363 if exists(filename): 364 try: 365 f = open(filename, "w") 366 except: 367 print("Error: bind failed for %s - Cannot open %s" 368 % (dev_id, filename), file=sys.stderr) 369 return 370 try: 371 f.write("%s" % driver) 372 f.close() 373 except: 374 print("Error: bind failed for %s - Cannot write driver %s to " 375 "PCI ID " % (dev_id, driver), file=sys.stderr) 376 return 377 # For kernels < 3.15 use new_id to add PCI id's to the driver 378 else: 379 filename = "/sys/bus/pci/drivers/%s/new_id" % driver 380 try: 381 f = open(filename, "w") 382 except: 383 print("Error: bind failed for %s - Cannot open %s" 384 % (dev_id, filename), file=sys.stderr) 385 return 386 try: 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))) 390 f.close() 391 except: 392 print("Error: bind failed for %s - Cannot write new PCI ID to " 393 "driver %s" % (dev_id, driver), file=sys.stderr) 394 return 395 396 # do the bind by writing to /sys 397 filename = "/sys/bus/pci/drivers/%s/bind" % driver 398 try: 399 f = open(filename, "a") 400 except: 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) 405 return 406 try: 407 f.write(dev_id) 408 f.close() 409 except: 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: 415 return 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) 420 return 421 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 426 if exists(filename): 427 try: 428 f = open(filename, "w") 429 except: 430 sys.exit("Error: unbind failed for %s - Cannot open %s" 431 % (dev_id, filename)) 432 try: 433 f.write("\00") 434 f.close() 435 except: 436 sys.exit("Error: unbind failed for %s - Cannot open %s" 437 % (dev_id, filename)) 438 439 440def unbind_all(dev_list, force=False): 441 """Unbind method, takes a list of device locations""" 442 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) 448 return 449 450 try: 451 dev_list = map(dev_id_from_dev_name, dev_list) 452 except ValueError as ex: 453 print(ex) 454 sys.exit(1) 455 456 for d in dev_list: 457 unbind_one(d, force) 458 459 460def bind_all(dev_list, driver, force=False): 461 """Bind method, takes a list of device locations""" 462 global devices 463 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. 467 try: 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) 473 except ValueError: 474 # driver generated error - it's not a valid device ID, so all is well 475 pass 476 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) 480 481 try: 482 dev_list = map(dev_id_from_dev_name, dev_list) 483 except ValueError as ex: 484 sys.exit(ex) 485 486 for d in dev_list: 487 bind_one(d, driver, force) 488 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: 498 continue 499 500 # update information about this device 501 devices[d] = dict(devices[d].items() + 502 get_pci_device_details(d, True).items()) 503 504 # check if updated information indicates that the device was bound 505 if "Driver_str" in devices[d]: 506 unbind_one(d, force) 507 508 509def 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)) 517 if not dev_list: 518 strings.append("<none>") 519 else: 520 for dev in dev_list: 521 if extra_params is not None: 522 strings.append("%s '%s %s' %s" % (dev["Slot"], 523 dev["Device_str"], 524 dev["Device"], 525 extra_params % dev)) 526 else: 527 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"])) 528 # sort before printing, so that the entries appear in PCI order 529 strings.sort() 530 print("\n".join(strings)) # print one per line 531 532def show_device_status(devices_type, device_name, if_field=False): 533 global dpdk_drivers 534 kernel_drv = [] 535 dpdk_drv = [] 536 no_drv = [] 537 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]) 543 continue 544 if devices[d]["Driver_str"] in dpdk_drivers: 545 dpdk_drv.append(devices[d]) 546 else: 547 kernel_drv.append(devices[d]) 548 549 n_devs = len(dpdk_drv) + len(kernel_drv) + len(no_drv) 550 551 # don't bother displaying anything if there are no devices 552 if n_devs == 0: 553 msg = "No '%s' devices detected" % device_name 554 print("") 555 print(msg) 556 print("".join('=' * len(msg))) 557 return 558 559 # print each category separately, so we can clearly see what's used by DPDK 560 if dpdk_drv: 561 display_devices("%s devices using DPDK-compatible driver" % device_name, 562 dpdk_drv, "drv=%(Driver_str)s unused=%(Module_str)s") 563 if kernel_drv: 564 if_text = "" 565 if if_field: 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") 570 if no_drv: 571 display_devices("Other %s devices" % device_name, no_drv, 572 "unused=%(Module_str)s") 573 574def show_status(): 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''' 578 579 if status_dev in ["net", "all"]: 580 show_device_status(network_devices, "Network", if_field=True) 581 582 if status_dev in ["baseband", "all"]: 583 show_device_status(baseband_devices, "Baseband") 584 585 if status_dev in ["crypto", "all"]: 586 show_device_status(crypto_devices, "Crypto") 587 588 if status_dev in ["event", "all"]: 589 show_device_status(eventdev_devices, "Eventdev") 590 591 if status_dev in ["mempool", "all"]: 592 show_device_status(mempool_devices, "Mempool") 593 594 if status_dev in ["compress", "all"]: 595 show_device_status(compress_devices, "Compress") 596 597 if status_dev in ["misc", "all"]: 598 show_device_status(misc_devices, "Misc (rawdev)") 599 600 if status_dev in ["regex", "all"]: 601 show_device_status(regex_devices, "Regex") 602 603 604def pci_glob(arg): 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))] 611 if paths: 612 return paths 613 return [arg] 614 615 616def parse_args(): 617 '''Parses the command-line arguments given by the user and takes the 618 appropriate action for each''' 619 global b_flag 620 global status_flag 621 global status_dev 622 global force_flag 623 global args 624 625 parser = argparse.ArgumentParser( 626 description='Utility to bind and unbind devices from Linux kernel', 627 formatter_class=argparse.RawDescriptionHelpFormatter, 628 epilog=""" 629Examples: 630--------- 631 632To display current device status: 633 %(prog)s --status 634 635To display current network device status: 636 %(prog)s --status-dev net 637 638To bind eth1 from the current driver and move to use vfio-pci 639 %(prog)s --bind=vfio-pci eth1 640 641To unbind 0000:01:00.0 from using any driver 642 %(prog)s -u 0000:01:00.0 643 644To 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 646""") 647 648 parser.add_argument( 649 '-s', 650 '--status', 651 action='store_true', 652 help="Print the current status of all known devices.") 653 parser.add_argument( 654 '--status-dev', 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( 660 '-b', 661 '--bind', 662 metavar='DRIVER', 663 help="Select the driver to use or \"none\" to unbind the device") 664 bind_group.add_argument( 665 '-u', 666 '--unbind', 667 action='store_true', 668 help="Unbind a device (equivalent to \"-b none\")") 669 parser.add_argument( 670 '--force', 671 action='store_true', 672 help=""" 673Override restriction on binding devices in use by Linux" 674WARNING: This can lead to loss of network connection and should be used with caution. 675""") 676 parser.add_argument( 677 'devices', 678 metavar='DEVICE', 679 nargs='*', 680 help=""" 681Device specified as PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax. 682For devices bound to Linux kernel drivers, they may be referred to by interface name. 683""") 684 685 opt = parser.parse_args() 686 687 if opt.status_dev: 688 status_flag = True 689 status_dev = opt.status_dev 690 if opt.status: 691 status_flag = True 692 status_dev = "all" 693 if opt.force: 694 force_flag = True 695 if opt.bind: 696 b_flag = opt.bind 697 elif opt.unbind: 698 b_flag = "none" 699 args = opt.devices 700 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", 704 file=sys.stderr) 705 parser.print_usage() 706 sys.exit(1) 707 708 if b_flag and not args: 709 print("Error: No devices specified.", file=sys.stderr) 710 parser.print_usage() 711 sys.exit(1) 712 713 # resolve any PCI globs in the args 714 new_args = [] 715 for arg in args: 716 new_args.extend(pci_glob(arg)) 717 args = new_args 718 719def do_arg_actions(): 720 '''do the actual action requested by the user''' 721 global b_flag 722 global status_flag 723 global force_flag 724 global args 725 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) 730 if status_flag: 731 if b_flag is not None: 732 clear_data() 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) 742 show_status() 743 744 745def main(): 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) 751 if ret != 0: 752 sys.exit("'lspci' not found - please install 'pciutils'") 753 parse_args() 754 check_modules() 755 clear_data() 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) 764 do_arg_actions() 765 766if __name__ == "__main__": 767 main() 768