eal/linux: fix remaining checks for 64-bit architectures
[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 # 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     --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     fd = file("/proc/modules")
160     loaded_mods = fd.readlines()
161     fd.close()
162
163     # list of supported modules
164     mods =  [{"Name" : driver, "Found" : False} for driver in dpdk_drivers]
165
166     # first check if module is loaded
167     for line in loaded_mods:
168         for mod in mods:
169             if line.startswith(mod["Name"]):
170                 mod["Found"] = True
171             # special case for vfio_pci (module is named vfio-pci,
172             # but its .ko is named vfio_pci)
173             elif line.replace("_", "-").startswith(mod["Name"]):
174                 mod["Found"] = True
175
176     # check if we have at least one loaded module
177     if True not in [mod["Found"] for mod in mods] and b_flag is not None:
178         print "Error - no supported modules are loaded"
179         sys.exit(1)
180
181     # change DPDK driver list to only contain drivers that are loaded
182     dpdk_drivers = [mod["Name"] for mod in mods if mod["Found"]]
183
184 def has_driver(dev_id):
185     '''return true if a device is assigned to a driver. False otherwise'''
186     return "Driver_str" in devices[dev_id]
187
188 def get_pci_device_details(dev_id):
189     '''This function gets additional details for a PCI device'''
190     device = {}
191
192     extra_info = check_output(["lspci", "-vmmks", dev_id]).splitlines()
193
194     # parse lspci details
195     for line in extra_info:
196         if len(line) == 0:
197             continue
198         name, value = line.split("\t", 1)
199         name = name.strip(":") + "_str"
200         device[name] = value
201     # check for a unix interface name
202     sys_path = "/sys/bus/pci/devices/%s/net/" % dev_id
203     if exists(sys_path):
204         device["Interface"] = ",".join(os.listdir(sys_path))
205     else:
206         device["Interface"] = ""
207     # check if a port is used for ssh connection
208     device["Ssh_if"] = False
209     device["Active"] = ""
210
211     return device
212
213 def get_nic_details():
214     '''This function populates the "devices" dictionary. The keys used are
215     the pci addresses (domain:bus:slot.func). The values are themselves
216     dictionaries - one for each NIC.'''
217     global devices
218     global dpdk_drivers
219
220     # clear any old data
221     devices = {}
222     # first loop through and read details for all devices
223     # request machine readable format, with numeric IDs
224     dev = {};
225     dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
226     for dev_line in dev_lines:
227         if (len(dev_line) == 0):
228             if dev["Class"] == ETHERNET_CLASS:
229                 #convert device and vendor ids to numbers, then add to global
230                 dev["Vendor"] = int(dev["Vendor"],16)
231                 dev["Device"] = int(dev["Device"],16)
232                 devices[dev["Slot"]] = dict(dev) # use dict to make copy of dev
233         else:
234             name, value = dev_line.split("\t", 1)
235             dev[name.rstrip(":")] = value
236
237     # check what is the interface if any for an ssh connection if
238     # any to this host, so we can mark it later.
239     ssh_if = []
240     route = check_output(["ip", "-o", "route"])
241     # filter out all lines for 169.254 routes
242     route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
243                              route.splitlines()))
244     rt_info = route.split()
245     for i in xrange(len(rt_info) - 1):
246         if rt_info[i] == "dev":
247             ssh_if.append(rt_info[i+1])
248
249     # based on the basic info, get extended text details
250     for d in devices.keys():
251         # get additional info and add it to existing data
252         devices[d] = dict(devices[d].items() +
253                           get_pci_device_details(d).items())
254
255         for _if in ssh_if:
256             if _if in devices[d]["Interface"].split(","):
257                 devices[d]["Ssh_if"] = True
258                 devices[d]["Active"] = "*Active*"
259                 break;
260
261         # add igb_uio to list of supporting modules if needed
262         if "Module_str" in devices[d]:
263             for driver in dpdk_drivers:
264                 if driver not in devices[d]["Module_str"]:
265                     devices[d]["Module_str"] = devices[d]["Module_str"] + ",%s" % driver
266         else:
267             devices[d]["Module_str"] = ",".join(dpdk_drivers)
268
269         # make sure the driver and module strings do not have any duplicates
270         if has_driver(d):
271             modules = devices[d]["Module_str"].split(",")
272             if devices[d]["Driver_str"] in modules:
273                 modules.remove(devices[d]["Driver_str"])
274                 devices[d]["Module_str"] = ",".join(modules)
275
276 def dev_id_from_dev_name(dev_name):
277     '''Take a device "name" - a string passed in by user to identify a NIC
278     device, and determine the device id - i.e. the domain:bus:slot.func - for
279     it, which can then be used to index into the devices array'''
280     dev = None
281     # check if it's already a suitable index
282     if dev_name in devices:
283         return dev_name
284     # check if it's an index just missing the domain part
285     elif "0000:" + dev_name in devices:
286         return "0000:" + dev_name
287     else:
288         # check if it's an interface name, e.g. eth1
289         for d in devices.keys():
290             if dev_name in devices[d]["Interface"].split(","):
291                 return devices[d]["Slot"]
292     # if nothing else matches - error
293     print "Unknown device: %s. " \
294         "Please specify device in \"bus:slot.func\" format" % dev_name
295     sys.exit(1)
296
297 def unbind_one(dev_id, force):
298     '''Unbind the device identified by "dev_id" from its current driver'''
299     dev = devices[dev_id]
300     if not has_driver(dev_id):
301         print "%s %s %s is not currently managed by any driver\n" % \
302             (dev["Slot"], dev["Device_str"], dev["Interface"])
303         return
304
305     # prevent us disconnecting ourselves
306     if dev["Ssh_if"] and not force:
307         print "Routing table indicates that interface %s is active" \
308             ". Skipping unbind" % (dev_id)
309         return
310
311     # write to /sys to unbind
312     filename = "/sys/bus/pci/drivers/%s/unbind" % dev["Driver_str"]
313     try:
314         f = open(filename, "a")
315     except:
316         print "Error: unbind failed for %s - Cannot open %s" % (dev_id, filename)
317         sys/exit(1)
318     f.write(dev_id)
319     f.close()
320
321 def bind_one(dev_id, driver, force):
322     '''Bind the device given by "dev_id" to the driver "driver". If the device
323     is already bound to a different driver, it will be unbound first'''
324     dev = devices[dev_id]
325     saved_driver = None # used to rollback any unbind in case of failure
326
327     # prevent disconnection of our ssh session
328     if dev["Ssh_if"] and not force:
329         print "Routing table indicates that interface %s is active" \
330             ". Not modifying" % (dev_id)
331         return
332
333     # unbind any existing drivers we don't want
334     if has_driver(dev_id):
335         if dev["Driver_str"] == driver:
336             print "%s already bound to driver %s, skipping\n" % (dev_id, driver)
337             return
338         else:
339             saved_driver = dev["Driver_str"]
340             unbind_one(dev_id, force)
341             dev["Driver_str"] = "" # clear driver string
342
343     # if we are binding to one of DPDK drivers, add PCI id's to that driver
344     if driver in dpdk_drivers:
345         filename = "/sys/bus/pci/drivers/%s/new_id" % driver
346         try:
347             f = open(filename, "w")
348         except:
349             print "Error: bind failed for %s - Cannot open %s" % (dev_id, filename)
350             return
351         try:
352             f.write("%04x %04x" % (dev["Vendor"], dev["Device"]))
353             f.close()
354         except:
355             print "Error: bind failed for %s - Cannot write new PCI ID to " \
356                 "driver %s" % (dev_id, driver)
357             return
358
359     # do the bind by writing to /sys
360     filename = "/sys/bus/pci/drivers/%s/bind" % driver
361     try:
362         f = open(filename, "a")
363     except:
364         print "Error: bind failed for %s - Cannot open %s" % (dev_id, filename)
365         if saved_driver is not None: # restore any previous driver
366             bind_one(dev_id, saved_driver, force)
367         return
368     try:
369         f.write(dev_id)
370         f.close()
371     except:
372         # for some reason, closing dev_id after adding a new PCI ID to new_id
373         # results in IOError. however, if the device was successfully bound,
374         # we don't care for any errors and can safely ignore IOError
375         tmp = get_pci_device_details(dev_id)
376         if "Driver_str" in tmp and tmp["Driver_str"] == driver:
377             return
378         print "Error: bind failed for %s - Cannot bind to driver %s" % (dev_id, driver)
379         if saved_driver is not None: # restore any previous driver
380             bind_one(dev_id, saved_driver, force)
381         return
382
383
384 def unbind_all(dev_list, 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         unbind_one(d, force)
389
390 def bind_all(dev_list, driver, force=False):
391     """Unbind method, takes a list of device locations"""
392     global devices
393
394     dev_list = map(dev_id_from_dev_name, dev_list)
395
396     for d in dev_list:
397         bind_one(d, driver, force)
398
399     # when binding devices to a generic driver (i.e. one that doesn't have a
400     # PCI ID table), some devices that are not bound to any other driver could
401     # be bound even if no one has asked them to. hence, we check the list of
402     # drivers again, and see if some of the previously-unbound devices were
403     # erroneously bound.
404     for d in devices.keys():
405         # skip devices that were already bound or that we know should be bound
406         if "Driver_str" in devices[d] or d in dev_list:
407             continue
408
409         # update information about this device
410         devices[d] = dict(devices[d].items() +
411                           get_pci_device_details(d).items())
412
413         # check if updated information indicates that the device was bound
414         if "Driver_str" in devices[d]:
415             unbind_one(d, force)
416
417 def display_devices(title, dev_list, extra_params = None):
418     '''Displays to the user the details of a list of devices given in "dev_list"
419     The "extra_params" parameter, if given, should contain a string with
420     %()s fields in it for replacement by the named fields in each device's
421     dictionary.'''
422     strings = [] # this holds the strings to print. We sort before printing
423     print "\n%s" % title
424     print   "="*len(title)
425     if len(dev_list) == 0:
426         strings.append("<none>")
427     else:
428         for dev in dev_list:
429             if extra_params is not None:
430                 strings.append("%s '%s' %s" % (dev["Slot"], \
431                                 dev["Device_str"], extra_params % dev))
432             else:
433                 strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
434     # sort before printing, so that the entries appear in PCI order
435     strings.sort()
436     print "\n".join(strings) # print one per line
437
438 def show_status():
439     '''Function called when the script is passed the "--status" option. Displays
440     to the user what devices are bound to the igb_uio driver, the kernel driver
441     or to no driver'''
442     global dpdk_drivers
443     kernel_drv = []
444     dpdk_drv = []
445     no_drv = []
446
447     # split our list of devices into the three categories above
448     for d in devices.keys():
449         if not has_driver(d):
450             no_drv.append(devices[d])
451             continue
452         if devices[d]["Driver_str"] in dpdk_drivers:
453             dpdk_drv.append(devices[d])
454         else:
455             kernel_drv.append(devices[d])
456
457     # print each category separately, so we can clearly see what's used by DPDK
458     display_devices("Network devices using DPDK-compatible driver", dpdk_drv, \
459                     "drv=%(Driver_str)s unused=%(Module_str)s")
460     display_devices("Network devices using kernel driver", kernel_drv,
461                     "if=%(Interface)s drv=%(Driver_str)s unused=%(Module_str)s %(Active)s")
462     display_devices("Other network devices", no_drv,\
463                     "unused=%(Module_str)s")
464
465 def parse_args():
466     '''Parses the command-line arguments given by the user and takes the
467     appropriate action for each'''
468     global b_flag
469     global status_flag
470     global force_flag
471     global args
472     if len(sys.argv) <= 1:
473         usage()
474         sys.exit(0)
475
476     try:
477         opts, args = getopt.getopt(sys.argv[1:], "b:u",
478                                ["help", "usage", "status", "force",
479                                 "bind=", "unbind"])
480     except getopt.GetoptError, error:
481         print str(error)
482         print "Run '%s --usage' for further information" % sys.argv[0]
483         sys.exit(1)
484
485     for opt, arg in opts:
486         if opt == "--help" or opt == "--usage":
487             usage()
488             sys.exit(0)
489         if opt == "--status":
490             status_flag = True
491         if opt == "--force":
492             force_flag = True
493         if opt == "-b" or opt == "-u" or opt == "--bind" or opt == "--unbind":
494             if b_flag is not None:
495                 print "Error - Only one bind or unbind may be specified\n"
496                 sys.exit(1)
497             if opt == "-u" or opt == "--unbind":
498                 b_flag = "none"
499             else:
500                 b_flag = arg
501
502 def do_arg_actions():
503     '''do the actual action requested by the user'''
504     global b_flag
505     global status_flag
506     global force_flag
507     global args
508
509     if b_flag is None and not status_flag:
510         print "Error: No action specified for devices. Please give a -b or -u option"
511         print "Run '%s --usage' for further information" % sys.argv[0]
512         sys.exit(1)
513
514     if b_flag is not None and len(args) == 0:
515         print "Error: No devices specified."
516         print "Run '%s --usage' for further information" % sys.argv[0]
517         sys.exit(1)
518
519     if b_flag == "none" or b_flag == "None":
520         unbind_all(args, force_flag)
521     elif b_flag is not None:
522         bind_all(args, b_flag, force_flag)
523     if status_flag:
524         if b_flag is not None:
525             get_nic_details() # refresh if we have changed anything
526         show_status()
527
528 def main():
529     '''program main function'''
530     parse_args()
531     check_modules()
532     get_nic_details()
533     do_arg_actions()
534
535 if __name__ == "__main__":
536     main()