1 # Copyright 2015-2017 Intel Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 """Automation of QEMU hypervisor with direct access to host NICs via
21 from conf import settings as S
22 from vnfs.qemu.qemu import IVnfQemu
23 from tools import tasks
24 from tools.module_manager import ModuleManager
26 _MODULE_MANAGER = ModuleManager()
28 class QemuPciPassthrough(IVnfQemu):
30 Control an instance of QEMU with direct access to the host network devices
34 Initialization function.
36 super(QemuPciPassthrough, self).__init__()
37 self._logger = logging.getLogger(__name__)
38 self._host_nics = S.getValue('NICS')
40 # in case of SRIOV and PCI passthrough we must ensure, that MAC addresses are swapped
41 if S.getValue('SRIOV_ENABLED') and not self._testpmd_fwd_mode.startswith('mac'):
42 self._logger.info("SRIOV detected, forwarding mode of testpmd was changed from '%s' to '%s'",
43 self._testpmd_fwd_mode, 'mac')
44 self._testpmd_fwd_mode = 'mac'
46 for nic in self._host_nics:
47 self._cmd += ['-device', 'vfio-pci,host=' + nic['pci']]
51 Start QEMU instance, bind host NICs to vfio-pci driver
54 _MODULE_MANAGER.insert_modules(['vfio-pci'])
56 # bind every interface to vfio-pci driver
58 nics_list = list(tmp_nic['pci'] for tmp_nic in self._host_nics)
59 tasks.run_task(['sudo', S.getValue('TOOLS')['bind-tool'], '--bind=vfio-pci'] + nics_list,
60 self._logger, 'Binding NICs %s...' % nics_list, True)
62 except subprocess.CalledProcessError:
63 self._logger.error('Unable to bind NICs %s', self._host_nics)
65 super(QemuPciPassthrough, self).start()
69 Stop QEMU instance, bind host NICs to the original driver
71 super(QemuPciPassthrough, self).stop()
73 # bind original driver to every interface
74 for nic in self._host_nics:
77 tasks.run_task(['sudo', S.getValue('TOOLS')['bind-tool'], '--bind=' + nic['driver'], nic['pci']],
78 self._logger, 'Binding NIC %s...' % nic['pci'], True)
80 except subprocess.CalledProcessError:
81 self._logger.error('Unable to bind NIC %s to driver %s', nic['pci'], nic['driver'])
83 # unload vfio-pci driver
84 _MODULE_MANAGER.remove_modules()