New upstream version 16.11.4
[deb_dpdk.git] / tools / dpdk-devbind.py
1 #! /usr/bin/python
2 #
3 #   BSD LICENSE
4 #
5 #   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
6 #   All rights reserved.
7 #
8 #   Redistribution and use in source and binary forms, with or without
9 #   modification, are permitted provided that the following conditions
10 #   are met:
11 #
12 #     * Redistributions of source code must retain the above copyright
13 #       notice, this list of conditions and the following disclaimer.
14 #     * Redistributions in binary form must reproduce the above copyright
15 #       notice, this list of conditions and the following disclaimer in
16 #       the documentation and/or other materials provided with the
17 #       distribution.
18 #     * Neither the name of Intel Corporation nor the names of its
19 #       contributors may be used to endorse or promote products derived
20 #       from this software without specific prior written permission.
21 #
22 #   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 #   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 #   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 #   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 #   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 #   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 #   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 #   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 #   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #
34
35 import sys
36 import os
37 import getopt
38 import subprocess
39 from os.path import exists, abspath, dirname, basename
40
41 # The PCI base class for NETWORK devices
42 NETWORK_BASE_CLASS = "02"
43 CRYPTO_BASE_CLASS = "0b"
44
45 # global dict ethernet devices present. Dictionary indexed by PCI address.
46 # Each device within this is itself a dictionary of device properties
47 devices = {}
48 # list of supported DPDK drivers
49 dpdk_drivers = ["igb_uio", "vfio-pci", "uio_pci_generic"]
50
51 # command-line arg flags
52 b_flag = None
53 status_flag = False
54 force_flag = False
55 args = []
56
57
58 def usage():
59     '''Print usage information for the program'''
60     argv0 = basename(sys.argv[0])
61     print("""
62 Usage:
63 ------
64
65      %(argv0)s [options] DEVICE1 DEVICE2 ....
66
67 where DEVICE1, DEVICE2 etc, are specified via PCI "domain:bus:slot.func" syntax
68 or "bus:slot.func" syntax. For devices bound to Linux kernel drivers, they may
69 also be referred to by Linux interface name e.g. eth0, eth1, em0, em1, etc.
70
71 Options:
72     --help, --usage:
73         Display usage information and quit
74
75     -s, --status:
76         Print the current status of all known network and crypto devices.
77         For each device, it displays the PCI domain, bus, slot and function,
78         along with a text description of the device. Depending upon whether the
79         device is being used by a kernel driver, the igb_uio driver, or no
80         driver, other relevant information will be displayed:
81         * the Linux interface name e.g. if=eth0
82         * the driver being used e.g. drv=igb_uio
83         * any suitable drivers not currently using that device
84             e.g. unused=igb_uio
85         NOTE: if this flag is passed along with a bind/unbind option, the
86         status display will always occur after the other operations have taken
87         place.
88
89     -b driver, --bind=driver:
90         Select the driver to use or \"none\" to unbind the device
91
92     -u, --unbind:
93         Unbind a device (Equivalent to \"-b none\")
94
95     --force:
96         By default, network devices which are used by Linux - as indicated by having
97         routes in the routing table - cannot be modified. Using the --force
98         flag overrides this behavior, allowing active links to be forcibly
99         unbound.
100         WARNING: This can lead to loss of network connection and should be used
101         with caution.
102
103 Examples:
104 ---------
105
106 To display current device status:
107         %(argv0)s --status
108
109 To bind eth1 from the current driver and move to use igb_uio
110         %(argv0)s --bind=igb_uio eth1
111
112 To unbind 0000:01:00.0 from using any driver
113         %(argv0)s -u 0000:01:00.0
114
115 To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
116         %(argv0)s -b ixgbe 02:00.0 02:00.1
117
118     """ % locals())  # replace items from local variables
119
120
121 # This is roughly compatible with check_output function in subprocess module
122 # which is only available in python 2.7.
123 def check_output(args, stderr=None):
124     '''Run a command and capture its output'''
125     return subprocess.Popen(args, stdout=subprocess.PIPE,
126                             stderr=stderr).communicate()[0]
127
128
129 def find_module(mod):
130     '''find the .ko file for kernel module named mod.
131     Searches the $RTE_SDK/$RTE_TARGET directory, the kernel
132     modules directory and finally under the parent directory of
133     the script '''
134     # check $RTE_SDK/$RTE_TARGET directory
135     if 'RTE_SDK' in os.environ and 'RTE_TARGET' in os.environ:
136         path = "%s/%s/kmod/%s.ko" % (os.environ['RTE_SDK'],
137                                      os.environ['RTE_TARGET'], mod)
138         if exists(path):
139             return path
140
141     # check using depmod
142     try:
143         depmod_out = check_output(["modinfo", "-n", mod],
144                                   stderr=subprocess.STDOUT).lower()
145         if "error" not in depmod_out:
146             path = depmod_out.strip()
147             if exists(path):
148                 return path
149     except:  # if modinfo can't find module, it fails, so continue
150         pass
151
152     # check for a copy based off current path
153     tools_dir = dirname(abspath(sys.argv[0]))
154     if (tools_dir.endswith("tools")):
155         base_dir = dirname(tools_dir)
156         find_out = check_output(["find", base_dir, "-name", mod + ".ko"])
157         if len(find_out) > 0:  # something matched
158             path = find_out.splitlines()[0]
159             if exists(path):
160                 return path
161
162
163 def check_modules():
164     '''Checks that igb_uio is loaded'''
165     global dpdk_drivers
166
167     # list of supported modules
168     mods = [{"Name": driver, "Found": False} for driver in dpdk_drivers]
169
170     # first check if module is loaded
171     try:
172         # Get list of sysfs modules (both built-in and dynamically loaded)
173         sysfs_path = '/sys/module/'
174
175         # Get the list of directories in sysfs_path
176         sysfs_mods = [os.path.join(sysfs_path, o) for o
177                       in os.listdir(sysfs_path)
178                       if os.path.isdir(os.path.join(sysfs_path, o))]
179
180         # Extract the last element of '/sys/module/abc' in the array
181         sysfs_mods = [a.split('/')[-1] for a in sysfs_mods]
182
183         # special case for vfio_pci (module is named vfio-pci,
184         # but its .ko is named vfio_pci)
185         sysfs_mods = [a if a != 'vfio_pci' else 'vfio-pci' for a in sysfs_mods]
186
187         for mod in mods:
188             if mod["Name"] in sysfs_mods:
189                 mod["Found"] = True
190     except:
191         pass
192
193     # check if we have at least one loaded module
194     if True not in [mod["Found"] for mod in mods] and b_flag is not None:
195         if b_flag in dpdk_drivers:
196             print("Error - no supported modules(DPDK driver) are loaded")
197             sys.exit(1)
198         else:
199             print("Warning - no supported modules(DPDK driver) are loaded")
200
201     # change DPDK driver list to only contain drivers that are loaded
202     dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
203
204
205 def has_driver(dev_id):
206     '''return true if a device is assigned to a driver. False otherwise'''
207     return "Driver_str" in devices[dev_id]
208
209
210 def get_pci_device_details(dev_id):
211     '''This function gets additional details for a PCI device'''
212     device = {}
213
214     extra_info = check_output(["lspci", "-vmmks", dev_id]).splitlines()
215
216     # parse lspci details
217     for line in extra_info:
218         if len(line) == 0:
219             continue
220         name, value = line.decode().split("\t", 1)
221         name = name.strip(":") + "_str"
222         device[name] = value
223     # check for a unix interface name
224     device["Interface"] = ""
225     for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
226         if "net" in dirs:
227             device["Interface"] = \
228                 ",".join(os.listdir(os.path.join(base, "net")))
229             break
230     # check if a port is used for ssh connection
231     device["Ssh_if"] = False
232     device["Active"] = ""
233
234     return device
235
236
237 def get_nic_details():
238     '''This function populates the "devices" dictionary. The keys used are
239     the pci addresses (domain:bus:slot.func). The values are themselves
240     dictionaries - one for each NIC.'''
241     global devices
242     global dpdk_drivers
243
244     # clear any old data
245     devices = {}
246     # first loop through and read details for all devices
247     # request machine readable format, with numeric IDs
248     dev = {}
249     dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
250     for dev_line in dev_lines:
251         if (len(dev_line) == 0):
252             if dev["Class"][0:2] == NETWORK_BASE_CLASS:
253                 # convert device and vendor ids to numbers, then add to global
254                 dev["Vendor"] = int(dev["Vendor"], 16)
255                 dev["Device"] = int(dev["Device"], 16)
256                 # use dict to make copy of dev
257                 devices[dev["Slot"]] = dict(dev)
258         else:
259             name, value = dev_line.decode().split("\t", 1)
260             dev[name.rstrip(":")] = value
261
262     # check what is the interface if any for an ssh connection if
263     # any to this host, so we can mark it later.
264     ssh_if = []
265     route = check_output(["ip", "-o", "route"])
266     # filter out all lines for 169.254 routes
267     route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
268                              route.decode().splitlines()))
269     rt_info = route.split()
270     for i in range(len(rt_info) - 1):
271         if rt_info[i] == "dev":
272             ssh_if.append(rt_info[i+1])
273
274     # based on the basic info, get extended text details
275     for d in devices.keys():
276         # get additional info and add it to existing data
277         devices[d] = devices[d].copy()
278         devices[d].update(get_pci_device_details(d).items())
279
280         for _if in ssh_if:
281             if _if in devices[d]["Interface"].split(","):
282                 devices[d]["Ssh_if"] = True
283                 devices[d]["Active"] = "*Active*"
284                 break
285
286         # add igb_uio to list of supporting modules if needed
287         if "Module_str" in devices[d]:
288             for driver in dpdk_drivers:
289                 if driver not in devices[d]["Module_str"]:
290                     devices[d]["Module_str"] = \
291                         devices[d]["Module_str"] + ",%s" % driver
292         else:
293             devices[d]["Module_str"] = ",".join(dpdk_drivers)
294
295         # make sure the driver and module strings do not have any duplicates
296         if has_driver(d):
297             modules = devices[d]["Module_str"].split(",")
298             if devices[d]["Driver_str"] in modules:
299                 modules.remove(devices[d]["Driver_str"])
300                 devices[d]["Module_str"] = ",".join(modules)
301
302
303 def get_crypto_details():
304     '''This function populates the "devices" dictionary. The keys used are
305     the pci addresses (domain:bus:slot.func). The values are themselves
306     dictionaries - one for each NIC.'''
307     global devices
308     global dpdk_drivers
309
310     # clear any old data
311     # devices = {}
312     # first loop through and read details for all devices
313     # request machine readable format, with numeric IDs
314     dev = {}
315     dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
316     for dev_line in dev_lines:
317         if (len(dev_line) == 0):
318             if (dev["Class"][0:2] == CRYPTO_BASE_CLASS):
319                 # convert device and vendor ids to numbers, then add to global
320                 dev["Vendor"] = int(dev["Vendor"], 16)
321                 dev["Device"] = int(dev["Device"], 16)
322                 # use dict to make copy of dev
323                 devices[dev["Slot"]] = dict(dev)
324         else:
325             name, value = dev_line.decode().split("\t", 1)
326             dev[name.rstrip(":")] = value
327
328     # based on the basic info, get extended text details
329     for d in devices.keys():
330         if devices[d]["Class"][0:2] != CRYPTO_BASE_CLASS:
331             continue
332
333         # get additional info and add it to existing data
334         devices[d] = devices[d].copy()
335         devices[d].update(get_pci_device_details(d).items())
336
337         # add igb_uio to list of supporting modules if needed
338         if "Module_str" in devices[d]:
339             for driver in dpdk_drivers:
340                 if driver not in devices[d]["Module_str"]:
341                     devices[d]["Module_str"] = \
342                         devices[d]["Module_str"] + ",%s" % driver
343         else:
344             devices[d]["Module_str"] = ",".join(dpdk_drivers)
345
346         # make sure the driver and module strings do not have any duplicates
347         if has_driver(d):
348             modules = devices[d]["Module_str"].split(",")
349             if devices[d]["Driver_str"] in modules:
350                 modules.remove(devices[d]["Driver_str"])
351                 devices[d]["Module_str"] = ",".join(modules)
352
353
354 def dev_id_from_dev_name(dev_name):
355     '''Take a device "name" - a string passed in by user to identify a NIC
356     device, and determine the device id - i.e. the domain:bus:slot.func - for
357     it, which can then be used to index into the devices array'''
358
359     # check if it's already a suitable index
360     if dev_name in devices:
361         return dev_name
362     # check if it's an index just missing the domain part
363     elif "0000:" + dev_name in devices:
364         return "0000:" + dev_name
365     else:
366         # check if it's an interface name, e.g. eth1
367         for d in devices.keys():
368             if dev_name in devices[d]["Interface"].split(","):
369                 return devices[d]["Slot"]
370     # if nothing else matches - error
371     print("Unknown device: %s. "
372           "Please specify device in \"bus:slot.func\" format" % dev_name)
373     sys.exit(1)
374
375
376 def unbind_one(dev_id, force):
377     '''Unbind the device identified by "dev_id" from its current driver'''
378     dev = devices[dev_id]
379     if not has_driver(dev_id):
380         print("%s %s %s is not currently managed by any driver\n" %
381               (dev["Slot"], dev["Device_str"], dev["Interface"]))
382         return
383
384     # prevent us disconnecting ourselves
385     if dev["Ssh_if"] and not force:
386         print("Routing table indicates that interface %s is active. "
387               "Skipping unbind" % (dev_id))
388         return
389
390     # write to /sys to unbind
391     filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
392     try:
393         f = open(filename, "a")
394     except:
395         print("Error: unbind failed for %s - Cannot open %s"
396               % (dev_id, filename))
397         sys.exit(1)
398     f.write(dev_id)
399     f.close()
400
401
402 def bind_one(dev_id, driver, force):
403     '''Bind the device given by "dev_id" to the driver "driver". If the device
404     is already bound to a different driver, it will be unbound first'''
405     dev = devices[dev_id]
406     saved_driver = None  # used to rollback any unbind in case of failure
407
408     # prevent disconnection of our ssh session
409     if dev["Ssh_if"] and not force:
410         print("Routing table indicates that interface %s is active. "
411               "Not modifying" % (dev_id))
412         return
413
414     # unbind any existing drivers we don't want
415     if has_driver(dev_id):
416         if dev["Driver_str"] == driver:
417             print("%s already bound to driver %s, skipping\n"
418                   % (dev_id, driver))
419             return
420         else:
421             saved_driver = dev["Driver_str"]
422             unbind_one(dev_id, force)
423             dev["Driver_str"] = ""  # clear driver string
424
425     # if we are binding to one of DPDK drivers, add PCI id's to that driver
426     if driver in dpdk_drivers:
427         filename = "/sys/bus/pci/drivers/%s/new_id" % driver
428         try:
429             f = open(filename, "w")
430         except:
431             print("Error: bind failed for %s - Cannot open %s"
432                   % (dev_id, filename))
433             return
434         try:
435             f.write("%04x %04x" % (dev["Vendor"], dev["Device"]))
436             f.close()
437         except:
438             print("Error: bind failed for %s - Cannot write new PCI ID to "
439                   "driver %s" % (dev_id, driver))
440             return
441
442     # do the bind by writing to /sys
443     filename = "/sys/bus/pci/drivers/%s/bind" % driver
444     try:
445         f = open(filename, "a")
446     except:
447         print("Error: bind failed for %s - Cannot open %s"
448               % (dev_id, filename))
449         if saved_driver is not None:  # restore any previous driver
450             bind_one(dev_id, saved_driver, force)
451         return
452     try:
453         f.write(dev_id)
454         f.close()
455     except:
456         # for some reason, closing dev_id after adding a new PCI ID to new_id
457         # results in IOError. however, if the device was successfully bound,
458         # we don't care for any errors and can safely ignore IOError
459         tmp = get_pci_device_details(dev_id)
460         if "Driver_str" in tmp and tmp["Driver_str"] == driver:
461             return
462         print("Error: bind failed for %s - Cannot bind to driver %s"
463               % (dev_id, driver))
464         if saved_driver is not None:  # restore any previous driver
465             bind_one(dev_id, saved_driver, force)
466         return
467
468
469 def unbind_all(dev_list, force=False):
470     """Unbind method, takes a list of device locations"""
471     dev_list = map(dev_id_from_dev_name, dev_list)
472     for d in dev_list:
473         unbind_one(d, force)
474
475
476 def bind_all(dev_list, driver, force=False):
477     """Bind method, takes a list of device locations"""
478     global devices
479
480     dev_list = map(dev_id_from_dev_name, dev_list)
481
482     for d in dev_list:
483         bind_one(d, driver, force)
484
485     # when binding devices to a generic driver (i.e. one that doesn't have a
486     # PCI ID table), some devices that are not bound to any other driver could
487     # be bound even if no one has asked them to. hence, we check the list of
488     # drivers again, and see if some of the previously-unbound devices were
489     # erroneously bound.
490     for d in devices.keys():
491         # skip devices that were already bound or that we know should be bound
492         if "Driver_str" in devices[d] or d in dev_list:
493             continue
494
495         # update information about this device
496         devices[d] = dict(devices[d].items() +
497                           get_pci_device_details(d).items())
498
499         # check if updated information indicates that the device was bound
500         if "Driver_str" in devices[d]:
501             unbind_one(d, force)
502
503
504 def display_devices(title, dev_list, extra_params=None):
505     '''Displays to the user the details of a list of devices given in
506     "dev_list". The "extra_params" parameter, if given, should contain a string
507      with %()s fields in it for replacement by the named fields in each
508      device's dictionary.'''
509     strings = []  # this holds the strings to print. We sort before printing
510     print("\n%s" % title)
511     print("="*len(title))
512     if len(dev_list) == 0:
513         strings.append("<none>")
514     else:
515         for dev in dev_list:
516             if extra_params is not None:
517                 strings.append("%s '%s' %s" % (dev["Slot"],
518                                dev["Device_str"], extra_params % dev))
519             else:
520                 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
521     # sort before printing, so that the entries appear in PCI order
522     strings.sort()
523     print("\n".join(strings))  # print one per line
524
525
526 def show_status():
527     '''Function called when the script is passed the "--status" option.
528     Displays to the user what devices are bound to the igb_uio driver, the
529     kernel driver or to no driver'''
530     global dpdk_drivers
531     kernel_drv = []
532     dpdk_drv = []
533     no_drv = []
534
535     # split our list of network devices into the three categories above
536     for d in devices.keys():
537         if (NETWORK_BASE_CLASS in devices[d]["Class"]):
538             if not has_driver(d):
539                 no_drv.append(devices[d])
540                 continue
541             if devices[d]["Driver_str"] in dpdk_drivers:
542                 dpdk_drv.append(devices[d])
543             else:
544                 kernel_drv.append(devices[d])
545
546     # print each category separately, so we can clearly see what's used by DPDK
547     display_devices("Network devices using DPDK-compatible driver", dpdk_drv,
548                     "drv=%(Driver_str)s unused=%(Module_str)s")
549     display_devices("Network devices using kernel driver", kernel_drv,
550                     "if=%(Interface)s drv=%(Driver_str)s "
551                     "unused=%(Module_str)s %(Active)s")
552     display_devices("Other network devices", no_drv, "unused=%(Module_str)s")
553
554     # split our list of crypto devices into the three categories above
555     kernel_drv = []
556     dpdk_drv = []
557     no_drv = []
558
559     for d in devices.keys():
560         if (CRYPTO_BASE_CLASS in devices[d]["Class"]):
561             if not has_driver(d):
562                 no_drv.append(devices[d])
563                 continue
564             if devices[d]["Driver_str"] in dpdk_drivers:
565                 dpdk_drv.append(devices[d])
566             else:
567                 kernel_drv.append(devices[d])
568
569     display_devices("Crypto devices using DPDK-compatible driver", dpdk_drv,
570                     "drv=%(Driver_str)s unused=%(Module_str)s")
571     display_devices("Crypto devices using kernel driver", kernel_drv,
572                     "drv=%(Driver_str)s "
573                     "unused=%(Module_str)s")
574     display_devices("Other crypto devices", no_drv, "unused=%(Module_str)s")
575
576
577 def parse_args():
578     '''Parses the command-line arguments given by the user and takes the
579     appropriate action for each'''
580     global b_flag
581     global status_flag
582     global force_flag
583     global args
584     if len(sys.argv) <= 1:
585         usage()
586         sys.exit(0)
587
588     try:
589         opts, args = getopt.getopt(sys.argv[1:], "b:us",
590                                    ["help", "usage", "status", "force",
591                                     "bind=", "unbind"])
592     except getopt.GetoptError as error:
593         print(str(error))
594         print("Run '%s --usage' for further information" % sys.argv[0])
595         sys.exit(1)
596
597     for opt, arg in opts:
598         if opt == "--help" or opt == "--usage":
599             usage()
600             sys.exit(0)
601         if opt == "--status" or opt == "-s":
602             status_flag = True
603         if opt == "--force":
604             force_flag = True
605         if opt == "-b" or opt == "-u" or opt == "--bind" or opt == "--unbind":
606             if b_flag is not None:
607                 print("Error - Only one bind or unbind may be specified\n")
608                 sys.exit(1)
609             if opt == "-u" or opt == "--unbind":
610                 b_flag = "none"
611             else:
612                 b_flag = arg
613
614
615 def do_arg_actions():
616     '''do the actual action requested by the user'''
617     global b_flag
618     global status_flag
619     global force_flag
620     global args
621
622     if b_flag is None and not status_flag:
623         print("Error: No action specified for devices."
624               "Please give a -b or -u option")
625         print("Run '%s --usage' for further information" % sys.argv[0])
626         sys.exit(1)
627
628     if b_flag is not None and len(args) == 0:
629         print("Error: No devices specified.")
630         print("Run '%s --usage' for further information" % sys.argv[0])
631         sys.exit(1)
632
633     if b_flag == "none" or b_flag == "None":
634         unbind_all(args, force_flag)
635     elif b_flag is not None:
636         bind_all(args, b_flag, force_flag)
637     if status_flag:
638         if b_flag is not None:
639             get_nic_details()  # refresh if we have changed anything
640             get_crypto_details()  # refresh if we have changed anything
641         show_status()
642
643
644 def main():
645     '''program main function'''
646     parse_args()
647     check_modules()
648     get_nic_details()
649     get_crypto_details()
650     do_arg_actions()
651
652 if __name__ == "__main__":
653     main()