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