remove trailing whitespaces
[dpdk.git] / examples / vhost / libvirt / qemu-wrap.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 #####################################################################
36 # This script is designed to modify the call to the QEMU emulator
37 # to support userspace vhost when starting a guest machine through
38 # libvirt with vhost enabled. The steps to enable this are as follows
39 # and should be run as root:
40 #
41 # 1. Place this script in a libvirtd's binary search PATH ($PATH)
42 #    A good location would be in the same directory that the QEMU
43 #    binary is located
44 #
45 # 2. Ensure that the script has the same owner/group and file
46 #    permissions as the QEMU binary
47 #
48 # 3. Update the VM xml file using "virsh edit VM.xml"
49 #
50 #    3.a) Set the VM to use the launch script
51 #
52 #       Set the emulator path contained in the
53 #               <emulator><emulator/> tags
54 #
55 #       e.g replace <emulator>/usr/bin/qemu-kvm<emulator/>
56 #        with    <emulator>/usr/bin/qemu-wrap.py<emulator/>
57 #
58 #        3.b) Set the VM's device's to use vhost-net offload
59 #
60 #               <interface type="network">
61 #               <model type="virtio"/>
62 #               <driver name="vhost"/>
63 #               <interface/>
64 #
65 # 4. Enable libvirt to access our userpace device file by adding it to
66 #    controllers cgroup for libvirtd using the following steps
67 #
68 #   4.a) In /etc/libvirt/qemu.conf add/edit the following lines:
69 #         1) cgroup_controllers = [ ... "devices", ... ]
70 #                 2) clear_emulator_capabilities = 0
71 #         3) user = "root"
72 #         4) group = "root"
73 #         5) cgroup_device_acl = [
74 #                "/dev/null", "/dev/full", "/dev/zero",
75 #                "/dev/random", "/dev/urandom",
76 #                "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
77 #                "/dev/rtc", "/dev/hpet", "/dev/net/tun",
78 #                "/dev/<devbase-name>-<index>",
79 #            ]
80 #
81 #   4.b) Disable SELinux or set to permissive mode
82 #
83 #   4.c) Mount cgroup device controller
84 #        "mkdir /dev/cgroup"
85 #        "mount -t cgroup none /dev/cgroup -o devices"
86 #
87 #   4.d) Set hugetlbfs_mount variable - ( Optional )
88 #        VMs using userspace vhost must use hugepage backed
89 #        memory. This can be enabled in the libvirt XML
90 #        config by adding a memory backing section to the
91 #        XML config e.g.
92 #             <memoryBacking>
93 #             <hugepages/>
94 #             </memoryBacking>
95 #        This memory backing section should be added after the
96 #        <memory> and <currentMemory> sections. This will add
97 #        flags "-mem-prealloc -mem-path <path>" to the QEMU
98 #        command line. The hugetlbfs_mount variable can be used
99 #        to override the default <path> passed through by libvirt.
100 #
101 #        if "-mem-prealloc" or "-mem-path <path>" are not passed
102 #        through and a vhost device is detected then these options will
103 #        be automatically added by this script. This script will detect
104 #        the system hugetlbfs mount point to be used for <path>. The
105 #        default <path> for this script can be overidden by the
106 #        hugetlbfs_dir variable in the configuration section of this script.
107 #
108 #
109 #   4.e) Restart the libvirtd system process
110 #        e.g. on Fedora "systemctl restart libvirtd.service"
111 #
112 #
113 #   4.f) Edit the Configuration Parameters section of this script
114 #        to point to the correct emulator location and set any
115 #        addition options
116 #
117 # The script modifies the libvirtd Qemu call by modifying/adding
118 # options based on the configuration parameters below.
119 # NOTE:
120 #     emul_path and us_vhost_path must be set
121 #     All other parameters are optional
122 #####################################################################
123
124
125 #############################################
126 # Configuration Parameters
127 #############################################
128 #Path to QEMU binary
129 emul_path = "/usr/local/bin/qemu-system-x86_64"
130
131 #Path to userspace vhost device file
132 # This filename should match the --dev-basename --dev-index parameters of
133 # the command used to launch the userspace vhost sample application e.g.
134 # if the sample app lauch command is:
135 #    ./build/vhost-switch ..... --dev-basename usvhost --dev-index 1
136 # then this variable should be set to:
137 #   us_vhost_path = "/dev/usvhost-1"
138 us_vhost_path = "/dev/usvhost-1"
139
140 #List of additional user defined emulation options. These options will
141 #be added to all Qemu calls
142 emul_opts_user = []
143
144 #List of additional user defined emulation options for vhost only.
145 #These options will only be added to vhost enabled guests
146 emul_opts_user_vhost = []
147
148 #For all VHOST enabled VMs, the VM memory is preallocated from hugetlbfs
149 # Set this variable to one to enable this option for all VMs
150 use_huge_all = 0
151
152 #Instead of autodetecting, override the hugetlbfs directory by setting
153 #this variable
154 hugetlbfs_dir = ""
155
156 #############################################
157
158
159 #############################################
160 # ****** Do Not Modify Below this Line ******
161 #############################################
162
163 import sys, os, subprocess
164
165
166 #List of open userspace vhost file descriptors
167 fd_list = []
168
169 #additional virtio device flags when using userspace vhost
170 vhost_flags = [ "csum=off",
171                 "gso=off",
172                 "guest_tso4=off",
173                 "guest_tso6=off",
174                 "guest_ecn=off"
175               ]
176
177
178 #############################################
179 # Find the system hugefile mount point.
180 # Note:
181 # if multiple hugetlbfs mount points exist
182 # then the first one found will be used
183 #############################################
184 def find_huge_mount():
185
186     if (len(hugetlbfs_dir)):
187         return hugetlbfs_dir
188
189     huge_mount = ""
190
191     if (os.access("/proc/mounts", os.F_OK)):
192         f = open("/proc/mounts", "r")
193         line = f.readline()
194         while line:
195             line_split = line.split(" ")
196             if line_split[2] == 'hugetlbfs':
197                 huge_mount = line_split[1]
198                 break
199             line = f.readline()
200     else:
201         print "/proc/mounts not found"
202         exit (1)
203
204     f.close
205     if len(huge_mount) == 0:
206         print "Failed to find hugetlbfs mount point"
207         exit (1)
208
209     return huge_mount
210
211
212 #############################################
213 # Get a userspace Vhost file descriptor
214 #############################################
215 def get_vhost_fd():
216
217     if (os.access(us_vhost_path, os.F_OK)):
218         fd = os.open( us_vhost_path, os.O_RDWR)
219     else:
220         print ("US-Vhost file %s not found" %us_vhost_path)
221         exit (1)
222
223     return fd
224
225
226 #############################################
227 # Check for vhostfd. if found then replace
228 # with our own vhost fd and append any vhost
229 # flags onto the end
230 #############################################
231 def modify_netdev_arg(arg):
232         
233     global fd_list
234     vhost_in_use = 0
235     s = ''
236     new_opts = []
237     netdev_opts = arg.split(",")
238
239     for opt in netdev_opts:
240         #check if vhost is used
241         if "vhost" == opt[:5]:
242             vhost_in_use = 1
243         else:
244             new_opts.append(opt)
245
246     #if using vhost append vhost options
247     if vhost_in_use == 1:
248         #append vhost on option
249         new_opts.append('vhost=on')
250         #append vhostfd ption
251         new_fd = get_vhost_fd()
252         new_opts.append('vhostfd=' + str(new_fd))
253         fd_list.append(new_fd)
254
255     #concatenate all options
256     for opt in new_opts:
257         if len(s) > 0:
258                         s+=','
259
260         s+=opt
261
262     return s    
263
264
265 #############################################
266 # Main
267 #############################################
268 def main():
269
270     global fd_list
271     global vhost_in_use
272     new_args = []
273     num_cmd_args = len(sys.argv)
274     emul_call = ''
275     mem_prealloc_set = 0
276     mem_path_set = 0
277     num = 0;
278
279     #parse the parameters
280     while (num < num_cmd_args):
281         arg = sys.argv[num]
282
283                 #Check netdev +1 parameter for vhostfd
284         if arg == '-netdev':
285             num_vhost_devs = len(fd_list)
286             new_args.append(arg)
287
288             num+=1
289             arg = sys.argv[num]
290             mod_arg = modify_netdev_arg(arg)
291             new_args.append(mod_arg)
292
293             #append vhost flags if this is a vhost device
294             # and -device is the next arg
295             # i.e -device -opt1,-opt2,...,-opt3,%vhost
296             if (num_vhost_devs < len(fd_list)):
297                 num+=1
298                 arg = sys.argv[num]
299                 if arg == '-device':
300                     new_args.append(arg)
301                     num+=1
302                     new_arg = sys.argv[num]
303                     for flag in vhost_flags:
304                         new_arg = ''.join([new_arg,',',flag])
305                     new_args.append(new_arg)
306                 else:
307                     new_args.append(arg)
308         elif arg == '-mem-prealloc':
309             mem_prealloc_set = 1
310             new_args.append(arg)
311         elif arg == '-mem-path':
312             mem_path_set = 1
313             new_args.append(arg)
314
315         else:
316             new_args.append(arg)
317
318         num+=1
319
320     #Set Qemu binary location
321     emul_call+=emul_path
322     emul_call+=" "
323
324     #Add prealloc mem options if using vhost and not already added
325     if ((len(fd_list) > 0) and (mem_prealloc_set == 0)):
326         emul_call += "-mem-prealloc "
327
328     #Add mempath mem options if using vhost and not already added
329     if ((len(fd_list) > 0) and (mem_path_set == 0)):
330         #Detect and add hugetlbfs mount point
331         mp = find_huge_mount()
332         mp = "".join(["-mem-path ", mp])
333         emul_call += mp
334         emul_call += " "
335
336
337     #add user options
338     for opt in emul_opts_user:
339         emul_call += opt
340         emul_call += " "
341
342     #Add add user vhost only options
343     if len(fd_list) > 0:
344         for opt in emul_opts_user_vhost:
345             emul_call += opt
346             emul_call += " "
347
348     #Add updated libvirt options
349     iter_args = iter(new_args)
350     #skip 1st arg i.e. call to this script
351     next(iter_args)
352     for arg in iter_args:
353         emul_call+=str(arg)
354         emul_call+= " "
355
356     #Call QEMU
357     subprocess.call(emul_call, shell=True)
358
359
360     #Close usvhost files
361     for fd in fd_list:
362         os.close(fd)
363
364
365 if __name__ == "__main__":
366     main()
367