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