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