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