pci.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. import os
  22. import re
  23. import subprocess
  24. import libvirt
  25. import lxml
  26. import lxml.etree
  27. import qubes.devices
  28. import qubes.ext
  29. #: cache of PCI device classes
  30. pci_classes = None
  31. def load_pci_classes():
  32. # List of known device classes, subclasses and programming interfaces
  33. # Syntax:
  34. # C class class_name
  35. # subclass subclass_name <-- single tab
  36. # prog-if prog-if_name <-- two tabs
  37. result = {}
  38. with open('/usr/share/hwdata/pci.ids') as pciids:
  39. class_id = None
  40. subclass_id = None
  41. for line in pciids.readlines():
  42. line = line.rstrip()
  43. if line.startswith('\t\t') and class_id and subclass_id:
  44. (progif_id, _, class_name) = line[2:].split(' ', 2)
  45. result[class_id + subclass_id + progif_id] = \
  46. class_name
  47. elif line.startswith('\t') and class_id:
  48. (subclass_id, _, class_name) = line[1:].split(' ', 2)
  49. # store both prog-if specific entry and generic one
  50. result[class_id + subclass_id + '00'] = \
  51. class_name
  52. result[class_id + subclass_id] = \
  53. class_name
  54. elif line.startswith('C '):
  55. (_, class_id, _, class_name) = line.split(' ', 3)
  56. result[class_id + '0000'] = class_name
  57. result[class_id + '00'] = class_name
  58. subclass_id = None
  59. return result
  60. def pcidev_class(dev_xmldesc):
  61. sysfs_path = dev_xmldesc.findtext('path')
  62. assert sysfs_path
  63. try:
  64. class_id = open(sysfs_path + '/class').read().strip()
  65. except OSError:
  66. return "Unknown"
  67. if not qubes.ext.pci.pci_classes:
  68. qubes.ext.pci.pci_classes = load_pci_classes()
  69. if class_id.startswith('0x'):
  70. class_id = class_id[2:]
  71. try:
  72. # ignore prog-if
  73. return qubes.ext.pci.pci_classes[class_id[0:4]]
  74. except KeyError:
  75. return "Unknown"
  76. def attached_devices(app):
  77. """Return map device->domain-name for all currently attached devices"""
  78. # Libvirt do not expose nice API to query where the device is
  79. # attached. The only way would be to query _all_ the domains (
  80. # each with separate libvirt call) and look if the device is
  81. # there. Horrible waste of resources.
  82. # Instead, do this on much lower level - xenstore info for
  83. # xen-pciback driver, where we get all the info at once
  84. xs = app.vmm.xs
  85. devices = {}
  86. for domid in xs.ls('', 'backend/pci') or []:
  87. for devid in xs.ls('', 'backend/pci/' + domid) or []:
  88. devpath = 'backend/pci/' + domid + '/' + devid
  89. domain_name = xs.read('', devpath + '/domain')
  90. try:
  91. domain = app.domains[domain_name]
  92. except KeyError:
  93. # unknown domain - maybe from another qubes.xml?
  94. continue
  95. devnum = xs.read('', devpath + '/num_devs')
  96. for dev in range(int(devnum)):
  97. dbdf = xs.read('', devpath + '/dev-' + str(dev))
  98. bdf = dbdf[len('0000:'):]
  99. devices[bdf] = domain
  100. return devices
  101. def _device_desc(hostdev_xml):
  102. return '{devclass}: {vendor} {product}'.format(
  103. devclass=pcidev_class(hostdev_xml),
  104. vendor=hostdev_xml.findtext('capability/vendor'),
  105. product=hostdev_xml.findtext('capability/product'),
  106. )
  107. class PCIDevice(qubes.devices.DeviceInfo):
  108. # pylint: disable=too-few-public-methods
  109. regex = re.compile(
  110. r'^(?P<bus>[0-9a-f]+):(?P<device>[0-9a-f]+)\.(?P<function>[0-9a-f]+)$')
  111. libvirt_regex = re.compile(
  112. r'^pci_0000_(?P<bus>[0-9a-f]+)_(?P<device>[0-9a-f]+)_'
  113. r'(?P<function>[0-9a-f]+)$')
  114. def __init__(self, backend_domain, ident, libvirt_name=None):
  115. if libvirt_name:
  116. dev_match = self.libvirt_regex.match(libvirt_name)
  117. assert dev_match
  118. ident = '{bus}:{device}.{function}'.format(**dev_match.groupdict())
  119. super(PCIDevice, self).__init__(backend_domain, ident, None)
  120. # lazy loading
  121. self._description = None
  122. @property
  123. def libvirt_name(self):
  124. # pylint: disable=no-member
  125. # noinspection PyUnresolvedReferences
  126. return 'pci_0000_{}_{}_{}'.format(self.bus, self.device, self.function)
  127. @property
  128. def description(self):
  129. if self._description is None:
  130. hostdev_details = \
  131. self.backend_domain.app.vmm.libvirt_conn.nodeDeviceLookupByName(
  132. self.libvirt_name
  133. )
  134. self._description = _device_desc(lxml.etree.fromstring(
  135. hostdev_details.XMLDesc()))
  136. return self._description
  137. @property
  138. def frontend_domain(self):
  139. # TODO: cache this
  140. all_attached = attached_devices(self.backend_domain.app)
  141. return all_attached.get(self.ident, None)
  142. class PCIDeviceExtension(qubes.ext.Extension):
  143. def __init__(self):
  144. super(PCIDeviceExtension, self).__init__()
  145. # lazy load this
  146. self.pci_classes = {}
  147. @qubes.ext.handler('device-list:pci')
  148. def on_device_list_pci(self, vm, event):
  149. # pylint: disable=unused-argument,no-self-use
  150. # only dom0 expose PCI devices
  151. if vm.qid != 0:
  152. return
  153. for dev in vm.app.vmm.libvirt_conn.listAllDevices():
  154. if 'pci' not in dev.listCaps():
  155. continue
  156. xml_desc = lxml.etree.fromstring(dev.XMLDesc())
  157. libvirt_name = xml_desc.findtext('name')
  158. yield PCIDevice(vm, None, libvirt_name=libvirt_name)
  159. @qubes.ext.handler('device-get:pci')
  160. def on_device_get_pci(self, vm, event, ident):
  161. # pylint: disable=unused-argument,no-self-use
  162. if not vm.app.vmm.offline_mode:
  163. yield PCIDevice(vm, ident)
  164. @qubes.ext.handler('device-list-attached:pci')
  165. def on_device_list_attached(self, vm, event, **kwargs):
  166. # pylint: disable=unused-argument,no-self-use
  167. if not vm.is_running() or isinstance(vm, qubes.vm.adminvm.AdminVM):
  168. return
  169. xml_desc = lxml.etree.fromstring(vm.libvirt_domain.XMLDesc())
  170. for hostdev in xml_desc.findall('devices/hostdev'):
  171. if hostdev.get('type') != 'pci':
  172. continue
  173. address = hostdev.find('source/address')
  174. bus = address.get('bus')[2:]
  175. device = address.get('slot')[2:]
  176. function = address.get('function')[2:]
  177. ident = '{bus}:{device}.{function}'.format(
  178. bus=bus,
  179. device=device,
  180. function=function,
  181. )
  182. yield PCIDevice(vm.app.domains[0], ident)
  183. @qubes.ext.handler('device-pre-attach:pci')
  184. def on_device_pre_attached_pci(self, vm, event, device):
  185. # pylint: disable=unused-argument
  186. if not os.path.exists('/sys/bus/pci/devices/0000:{}'.format(
  187. device.ident)):
  188. raise qubes.exc.QubesException(
  189. 'Invalid PCI device: {}'.format(device.ident))
  190. if not vm.is_running():
  191. return
  192. try:
  193. self.bind_pci_to_pciback(vm.app, device)
  194. vm.libvirt_domain.attachDevice(
  195. vm.app.env.get_template('libvirt/devices/pci.xml').render(
  196. device=device, vm=vm))
  197. except subprocess.CalledProcessError as e:
  198. vm.log.exception('Failed to attach PCI device {!r} on the fly,'
  199. ' changes will be seen after VM restart.'.format(
  200. device.ident), e)
  201. @qubes.ext.handler('device-pre-detach:pci')
  202. def on_device_pre_detached_pci(self, vm, event, device):
  203. # pylint: disable=unused-argument,no-self-use
  204. if not vm.is_running():
  205. return
  206. # this cannot be converted to general API, because there is no
  207. # provision in libvirt for extracting device-side BDF; we need it for
  208. # qubes.DetachPciDevice, which unbinds driver, not to oops the kernel
  209. p = subprocess.Popen(['xl', 'pci-list', str(vm.xid)],
  210. stdout=subprocess.PIPE)
  211. result = p.communicate()[0]
  212. m = re.search(r'^(\d+.\d+)\s+0000:{}$'.format(device.ident), result,
  213. flags=re.MULTILINE)
  214. if not m:
  215. vm.log.error('Device %s already detached', device.ident)
  216. return
  217. vmdev = m.group(1)
  218. try:
  219. vm.run_service('qubes.DetachPciDevice',
  220. user='root', input='00:{}'.format(vmdev))
  221. vm.libvirt_domain.detachDevice(
  222. vm.app.env.get_template('libvirt/devices/pci.xml').render(
  223. device=device, vm=vm))
  224. except (subprocess.CalledProcessError, libvirt.libvirtError) as e:
  225. vm.log.exception('Failed to detach PCI device {!r} on the fly,'
  226. ' changes will be seen after VM restart.'.format(
  227. device.ident), e)
  228. raise
  229. @qubes.ext.handler('domain-pre-start')
  230. def on_domain_pre_start(self, vm, _event, **_kwargs):
  231. # Bind pci devices to pciback driver
  232. for pci in vm.devices['pci'].attached():
  233. self.bind_pci_to_pciback(vm.app, pci)
  234. @staticmethod
  235. def bind_pci_to_pciback(app, device):
  236. '''Bind PCI device to pciback driver.
  237. :param qubes.devices.PCIDevice device: device to attach
  238. Devices should be unbound from their normal kernel drivers and bound to
  239. the dummy driver, which allows for attaching them to a domain.
  240. '''
  241. try:
  242. node = app.vmm.libvirt_conn.nodeDeviceLookupByName(
  243. device.libvirt_name)
  244. except libvirt.libvirtError as e:
  245. if e.get_error_code() == libvirt.VIR_ERR_NO_NODE_DEVICE:
  246. raise qubes.exc.QubesException(
  247. 'PCI device {!r} does not exist'.format(
  248. device))
  249. raise
  250. try:
  251. node.dettach()
  252. except libvirt.libvirtError as e:
  253. if e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  254. # allreaddy dettached
  255. pass
  256. else:
  257. raise