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