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