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