tools: support vfio in dpdk_nic_bind
[dpdk.git] / tools / dpdk_nic_bind.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, os, getopt, subprocess
36 from os.path import exists, abspath, dirname, basename
37
38
39 # The PCI device class for ETHERNET devices
40 ETHERNET_CLASS = "0200"
41
42 # global dict ethernet devices present. Dictionary indexed by PCI address.
43 # Each device within this is itself a dictionary of device properties
44 devices = {}
45 # list of supported DPDK drivers
46 dpdk_drivers = [ "igb_uio", "vfio-pci" ]
47
48 def usage():
49     '''Print usage information for the program'''
50     argv0 = basename(sys.argv[0])
51     print """
52 Usage:
53 ------
54
55      %(argv0)s [options] DEVICE1 DEVICE2 ....
56
57 where DEVICE1, DEVICE2 etc, are specified via PCI "domain:bus:slot.func" syntax
58 or "bus:slot.func" syntax. For devices bound to Linux kernel drivers, they may
59 also be referred to by Linux interface name e.g. eth0, eth1, em0, em1, etc.
60
61 Options:
62     --help, --usage:
63         Display usage information and quit
64
65     --status:
66         Print the current status of all known network interfaces.
67         For each device, it displays the PCI domain, bus, slot and function,
68         along with a text description of the device. Depending upon whether the
69         device is being used by a kernel driver, the igb_uio driver, or no
70         driver, other relevant information will be displayed:
71         * the Linux interface name e.g. if=eth0
72         * the driver being used e.g. drv=igb_uio
73         * any suitable drivers not currently using that device
74             e.g. unused=igb_uio
75         NOTE: if this flag is passed along with a bind/unbind option, the status
76         display will always occur after the other operations have taken place.
77
78     -b driver, --bind=driver:
79         Select the driver to use or \"none\" to unbind the device
80
81     -u, --unbind:
82         Unbind a device (Equivalent to \"-b none\")
83
84     --force:
85         By default, devices which are used by Linux - as indicated by having
86         routes in the routing table - cannot be modified. Using the --force
87         flag overrides this behavior, allowing active links to be forcibly
88         unbound.
89         WARNING: This can lead to loss of network connection and should be used
90         with caution.
91
92 Examples:
93 ---------
94
95 To display current device status:
96         %(argv0)s --status
97
98 To bind eth1 from the current driver and move to use igb_uio
99         %(argv0)s --bind=igb_uio eth1
100
101 To unbind 0000:01:00.0 from using any driver
102         %(argv0)s -u 0000:01:00.0
103
104 To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
105         %(argv0)s -b ixgbe 02:00.0 02:00.1
106
107     """ % locals() # replace items from local variables
108
109 # This is roughly compatible with check_output function in subprocess module
110 # which is only available in python 2.7.
111 def check_output(args, stderr=None):
112     '''Run a command and capture its output'''
113     return subprocess.Popen(args, stdout=subprocess.PIPE,
114                             stderr=stderr).communicate()[0]
115
116 def find_module(mod):
117     '''find the .ko file for kernel module named mod.
118     Searches the $RTE_SDK/$RTE_TARGET directory, the kernel
119     modules directory and finally under the parent directory of
120     the script '''
121     # check $RTE_SDK/$RTE_TARGET directory
122     if 'RTE_SDK' in os.environ and 'RTE_TARGET' in os.environ:
123         path = "%s/%s/kmod/%s.ko" % (os.environ['RTE_SDK'],\
124                                      os.environ['RTE_TARGET'], mod)
125         if exists(path):
126             return path
127
128     # check using depmod
129     try:
130         depmod_out = check_output(["modinfo", "-n", mod], \
131                                   stderr=subprocess.STDOUT).lower()
132         if "error" not in depmod_out:
133             path = depmod_out.strip()
134             if exists(path):
135                 return path
136     except: # if modinfo can't find module, it fails, so continue
137         pass
138
139     # check for a copy based off current path
140     tools_dir = dirname(abspath(sys.argv[0]))
141     if (tools_dir.endswith("tools")):
142         base_dir = dirname(tools_dir)
143         find_out = check_output(["find", base_dir, "-name", mod + ".ko"])
144         if len(find_out) > 0: #something matched
145             path = find_out.splitlines()[0]
146             if exists(path):
147                 return path
148
149 def check_modules():
150     '''Checks that igb_uio is loaded'''
151     global dpdk_drivers
152
153     fd = file("/proc/modules")
154     loaded_mods = fd.readlines()
155     fd.close()
156
157     # list of supported modules
158     mods =  [{"Name" : driver, "Found" : False} for driver in dpdk_drivers]
159
160     # first check if module is loaded
161     for line in loaded_mods:
162         for mod in mods:
163             if line.startswith(mod["Name"]):
164                 mod["Found"] = True
165             # special case for vfio_pci (module is named vfio-pci,
166             # but its .ko is named vfio_pci)
167             elif line.replace("_", "-").startswith(mod["Name"]):
168                 mod["Found"] = True
169
170     # check if we have at least one loaded module
171     if True not in [mod["Found"] for mod in mods]:
172         print "Error - no supported modules are loaded"
173         sys.exit(1)
174
175     # change DPDK driver list to only contain drivers that are loaded
176     dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
177
178 def has_driver(dev_id):
179     '''return true if a device is assigned to a driver. False otherwise'''
180     return "Driver_str" in devices[dev_id]
181
182 def get_pci_device_details(dev_id):
183     '''This function gets additional details for a PCI device'''
184     device = {}
185
186     extra_info = check_output(["lspci", "-vmmks", dev_id]).splitlines()
187
188     # parse lspci details
189     for line in extra_info:
190         if len(line) == 0:
191             continue
192         name, value = line.split("\t", 1)
193         name = name.strip(":") + "_str"
194         device[name] = value
195     # check for a unix interface name
196     sys_path = "/sys/bus/pci/devices/%s/net/" % dev_id
197     if exists(sys_path):
198         device["Interface"] = ",".join(os.listdir(sys_path))
199     else:
200         device["Interface"] = ""
201     # check if a port is used for ssh connection
202     device["Ssh_if"] = False
203     device["Active"] = ""
204
205     return device
206
207 def get_nic_details():
208     '''This function populates the "devices" dictionary. The keys used are
209     the pci addresses (domain:bus:slot.func). The values are themselves
210     dictionaries - one for each NIC.'''
211     global devices
212     global dpdk_drivers
213
214     # clear any old data
215     devices = {}
216     # first loop through and read details for all devices
217     # request machine readable format, with numeric IDs
218     dev = {};
219     dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
220     for dev_line in dev_lines:
221         if (len(dev_line) == 0):
222             if dev["Class"] == ETHERNET_CLASS:
223                 #convert device and vendor ids to numbers, then add to global
224                 dev["Vendor"] = int(dev["Vendor"],16)
225                 dev["Device"] = int(dev["Device"],16)
226                 devices[dev["Slot"]] = dict(dev) # use dict to make copy of dev
227         else:
228             name, value = dev_line.split("\t", 1)
229             dev[name.rstrip(":")] = value
230
231     # check what is the interface if any for an ssh connection if
232     # any to this host, so we can mark it later.
233     ssh_if = []
234     route = check_output(["ip", "-o", "route"])
235     # filter out all lines for 169.254 routes
236     route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
237                              route.splitlines()))
238     rt_info = route.split()
239     for i in xrange(len(rt_info) - 1):
240         if rt_info[i] == "dev":
241             ssh_if.append(rt_info[i+1])
242
243     # based on the basic info, get extended text details
244     for d in devices.keys():
245         # get additional info and add it to existing data
246         devices[d] = dict(devices[d].items() +
247                           get_pci_device_details(d).items())
248
249         for _if in ssh_if:
250             if _if in devices[d]["Interface"].split(","):
251                 devices[d]["Ssh_if"] = True
252                 devices[d]["Active"] = "*Active*"
253                 break;
254
255         # add igb_uio to list of supporting modules if needed
256         if "Module_str" in devices[d]:
257             for driver in dpdk_drivers:
258                 if driver not in devices[d]["Module_str"]:
259                     devices[d]["Module_str"] = devices[d]["Module_str"] + ",%s" % driver
260         else:
261             devices[d]["Module_str"] = ",".join(dpdk_drivers)
262
263         # make sure the driver and module strings do not have any duplicates
264         if has_driver(d):
265             modules = devices[d]["Module_str"].split(",")
266             if devices[d]["Driver_str"] in modules:
267                 modules.remove(devices[d]["Driver_str"])
268                 devices[d]["Module_str"] = ",".join(modules)
269
270 def dev_id_from_dev_name(dev_name):
271     '''Take a device "name" - a string passed in by user to identify a NIC
272     device, and determine the device id - i.e. the domain:bus:slot.func - for
273     it, which can then be used to index into the devices array'''
274     dev = None
275     # check if it's already a suitable index
276     if dev_name in devices:
277         return dev_name
278     # check if it's an index just missing the domain part
279     elif "0000:" + dev_name in devices:
280         return "0000:" + dev_name
281     else:
282         # check if it's an interface name, e.g. eth1
283         for d in devices.keys():
284             if dev_name in devices[d]["Interface"].split(","):
285                 return devices[d]["Slot"]
286     # if nothing else matches - error
287     print "Unknown device: %s. " \
288         "Please specify device in \"bus:slot.func\" format" % dev_name
289     sys.exit(1)
290
291 def unbind_one(dev_id, force):
292     '''Unbind the device identified by "dev_id" from its current driver'''
293     dev = devices[dev_id]
294     if not has_driver(dev_id):
295         print "%s %s %s is not currently managed by any driver\n" % \
296             (dev["Slot"], dev["Device_str"], dev["Interface"])
297         return
298
299     # prevent us disconnecting ourselves
300     if dev["Ssh_if"] and not force:
301         print "Routing table indicates that interface %s is active" \
302             ". Skipping unbind" % (dev_id)
303         return
304
305     # write to /sys to unbind
306     filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
307     try:
308         f = open(filename, "a")
309     except:
310         print "Error: unbind failed for %s - Cannot open %s" % (dev_id, filename)
311         sys/exit(1)
312     f.write(dev_id)
313     f.close()
314
315 def bind_one(dev_id, driver, force):
316     '''Bind the device given by "dev_id" to the driver "driver". If the device
317     is already bound to a different driver, it will be unbound first'''
318     dev = devices[dev_id]
319     saved_driver = None # used to rollback any unbind in case of failure
320
321     # prevent disconnection of our ssh session
322     if dev["Ssh_if"] and not force:
323         print "Routing table indicates that interface %s is active" \
324             ". Not modifying" % (dev_id)
325         return
326
327     # unbind any existing drivers we don't want
328     if has_driver(dev_id):
329         if dev["Driver_str"] == driver:
330             print "%s already bound to driver %s, skipping\n" % (dev_id, driver)
331             return
332         else:
333             saved_driver = dev["Driver_str"]
334             unbind_one(dev_id, force)
335             dev["Driver_str"] = "" # clear driver string
336
337     # if we are binding to one of DPDK drivers, add PCI id's to that driver
338     if driver in dpdk_drivers:
339         filename = "/sys/bus/pci/drivers/%s/new_id" % driver
340         try:
341             f = open(filename, "w")
342         except:
343             print "Error: bind failed for %s - Cannot open %s" % (dev_id, filename)
344             return
345         try:
346             f.write("%04x %04x" % (dev["Vendor"], dev["Device"]))
347             f.close()
348         except:
349             print "Error: bind failed for %s - Cannot write new PCI ID to " \
350                 "driver %s" % (dev_id, driver)
351             return
352
353     # do the bind by writing to /sys
354     filename = "/sys/bus/pci/drivers/%s/bind" % driver
355     try:
356         f = open(filename, "a")
357     except:
358         print "Error: bind failed for %s - Cannot open %s" % (dev_id, filename)
359         if saved_driver is not None: # restore any previous driver
360             bind_one(dev_id, saved_driver, force)
361         return
362     try:
363         f.write(dev_id)
364         f.close()
365     except:
366         # for some reason, closing dev_id after adding a new PCI ID to new_id
367         # results in IOError. however, if the device was successfully bound,
368         # we don't care for any errors and can safely ignore IOError
369         tmp = get_pci_device_details(dev_id)
370         if "Driver_str" in tmp and tmp["Driver_str"] == driver:
371             return
372         print "Error: bind failed for %s - Cannot bind to driver %s" % (dev_id, driver)
373         if saved_driver is not None: # restore any previous driver
374             bind_one(dev_id, saved_driver, force)
375         return
376
377
378 def unbind_all(dev_list, force=False):
379     """Unbind method, takes a list of device locations"""
380     dev_list = map(dev_id_from_dev_name, dev_list)
381     for d in dev_list:
382         unbind_one(d, force)
383
384 def bind_all(dev_list, driver, force=False):
385     """Unbind method, takes a list of device locations"""
386     dev_list = map(dev_id_from_dev_name, dev_list)
387     for d in dev_list:
388         bind_one(d, driver, force)
389
390 def display_devices(title, dev_list, extra_params = None):
391     '''Displays to the user the details of a list of devices given in "dev_list"
392     The "extra_params" parameter, if given, should contain a string with
393     %()s fields in it for replacement by the named fields in each device's
394     dictionary.'''
395     strings = [] # this holds the strings to print. We sort before printing
396     print "\n%s" % title
397     print   "="*len(title)
398     if len(dev_list) == 0:
399         strings.append("<none>")
400     else:
401         for dev in dev_list:
402             if extra_params is not None:
403                 strings.append("%s '%s' %s" % (dev["Slot"], \
404                                 dev["Device_str"], extra_params % dev))
405             else:
406                 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
407     # sort before printing, so that the entries appear in PCI order
408     strings.sort()
409     print "\n".join(strings) # print one per line
410
411 def show_status():
412     '''Function called when the script is passed the "--status" option. Displays
413     to the user what devices are bound to the igb_uio driver, the kernel driver
414     or to no driver'''
415     global dpdk_drivers
416     kernel_drv = []
417     dpdk_drv = []
418     no_drv = []
419
420     # split our list of devices into the three categories above
421     for d in devices.keys():
422         if not has_driver(d):
423             no_drv.append(devices[d])
424             continue
425         if devices[d]["Driver_str"] in dpdk_drivers:
426             dpdk_drv.append(devices[d])
427         else:
428             kernel_drv.append(devices[d])
429
430     # print each category separately, so we can clearly see what's used by DPDK
431     display_devices("Network devices using DPDK-compatible driver", dpdk_drv, \
432                     "drv=%(Driver_str)s unused=%(Module_str)s")
433     display_devices("Network devices using kernel driver", kernel_drv,
434                     "if=%(Interface)s drv=%(Driver_str)s unused=%(Module_str)s %(Active)s")
435     display_devices("Other network devices", no_drv,\
436                     "unused=%(Module_str)s")
437
438 def parse_args():
439     '''Parses the command-line arguments given by the user and takes the
440     appropriate action for each'''
441     b_flag = None
442     status_flag = False
443     force_flag = False
444     if len(sys.argv) <= 1:
445         usage()
446         sys.exit(0)
447
448     try:
449         opts, args = getopt.getopt(sys.argv[1:], "b:u",
450                                ["help", "usage", "status", "force",
451                                 "bind=", "unbind"])
452     except getopt.GetoptError, error:
453         print str(error)
454         print "Run '%s --usage' for further information" % sys.argv[0]
455         sys.exit(1)
456
457     for opt, arg in opts:
458         if opt == "--help" or opt == "--usage":
459             usage()
460             sys.exit(0)
461         if opt == "--status":
462             status_flag = True
463         if opt == "--force":
464             force_flag = True
465         if opt == "-b" or opt == "-u" or opt == "--bind" or opt == "--unbind":
466             if b_flag is not None:
467                 print "Error - Only one bind or unbind may be specified\n"
468                 sys.exit(1)
469             if opt == "-u" or opt == "--unbind":
470                 b_flag = "none"
471             else:
472                 b_flag = arg
473
474     if b_flag is None and not status_flag:
475         print "Error: No action specified for devices. Please give a -b or -u option"
476         print "Run '%s --usage' for further information" % sys.argv[0]
477         sys.exit(1)
478
479     if b_flag is not None and len(args) == 0:
480         print "Error: No devices specified."
481         print "Run '%s --usage' for further information" % sys.argv[0]
482         sys.exit(1)
483
484     if b_flag == "none" or b_flag == "None":
485         unbind_all(args, force_flag)
486     elif b_flag is not None:
487         bind_all(args, b_flag, force_flag)
488     if status_flag:
489         if b_flag is not None:
490             get_nic_details() # refresh if we have changed anything
491         show_status()
492
493 def main():
494     '''program main function'''
495     check_modules()
496     get_nic_details()
497     parse_args()
498
499 if __name__ == "__main__":
500     main()