2
0

common.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. /*
  2. * generic functions used by VFIO devices
  3. *
  4. * Copyright Red Hat, Inc. 2012
  5. *
  6. * Authors:
  7. * Alex Williamson <alex.williamson@redhat.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2. See
  10. * the COPYING file in the top-level directory.
  11. *
  12. * Based on qemu-kvm device-assignment:
  13. * Adapted for KVM by Qumranet.
  14. * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
  15. * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
  16. * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
  17. * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
  18. * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
  19. */
  20. #include "qemu/osdep.h"
  21. #include <sys/ioctl.h>
  22. #ifdef CONFIG_KVM
  23. #include <linux/kvm.h>
  24. #endif
  25. #include <linux/vfio.h>
  26. #include "hw/vfio/vfio-common.h"
  27. #include "hw/vfio/vfio.h"
  28. #include "exec/address-spaces.h"
  29. #include "exec/memory.h"
  30. #include "hw/hw.h"
  31. #include "qemu/error-report.h"
  32. #include "qemu/main-loop.h"
  33. #include "qemu/range.h"
  34. #include "sysemu/balloon.h"
  35. #include "sysemu/kvm.h"
  36. #include "sysemu/reset.h"
  37. #include "trace.h"
  38. #include "qapi/error.h"
  39. VFIOGroupList vfio_group_list =
  40. QLIST_HEAD_INITIALIZER(vfio_group_list);
  41. static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
  42. QLIST_HEAD_INITIALIZER(vfio_address_spaces);
  43. #ifdef CONFIG_KVM
  44. /*
  45. * We have a single VFIO pseudo device per KVM VM. Once created it lives
  46. * for the life of the VM. Closing the file descriptor only drops our
  47. * reference to it and the device's reference to kvm. Therefore once
  48. * initialized, this file descriptor is only released on QEMU exit and
  49. * we'll re-use it should another vfio device be attached before then.
  50. */
  51. static int vfio_kvm_device_fd = -1;
  52. #endif
  53. /*
  54. * Common VFIO interrupt disable
  55. */
  56. void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
  57. {
  58. struct vfio_irq_set irq_set = {
  59. .argsz = sizeof(irq_set),
  60. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
  61. .index = index,
  62. .start = 0,
  63. .count = 0,
  64. };
  65. ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  66. }
  67. void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
  68. {
  69. struct vfio_irq_set irq_set = {
  70. .argsz = sizeof(irq_set),
  71. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
  72. .index = index,
  73. .start = 0,
  74. .count = 1,
  75. };
  76. ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  77. }
  78. void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
  79. {
  80. struct vfio_irq_set irq_set = {
  81. .argsz = sizeof(irq_set),
  82. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
  83. .index = index,
  84. .start = 0,
  85. .count = 1,
  86. };
  87. ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  88. }
  89. static inline const char *action_to_str(int action)
  90. {
  91. switch (action) {
  92. case VFIO_IRQ_SET_ACTION_MASK:
  93. return "MASK";
  94. case VFIO_IRQ_SET_ACTION_UNMASK:
  95. return "UNMASK";
  96. case VFIO_IRQ_SET_ACTION_TRIGGER:
  97. return "TRIGGER";
  98. default:
  99. return "UNKNOWN ACTION";
  100. }
  101. }
  102. static const char *index_to_str(VFIODevice *vbasedev, int index)
  103. {
  104. if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
  105. return NULL;
  106. }
  107. switch (index) {
  108. case VFIO_PCI_INTX_IRQ_INDEX:
  109. return "INTX";
  110. case VFIO_PCI_MSI_IRQ_INDEX:
  111. return "MSI";
  112. case VFIO_PCI_MSIX_IRQ_INDEX:
  113. return "MSIX";
  114. case VFIO_PCI_ERR_IRQ_INDEX:
  115. return "ERR";
  116. case VFIO_PCI_REQ_IRQ_INDEX:
  117. return "REQ";
  118. default:
  119. return NULL;
  120. }
  121. }
  122. int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex,
  123. int action, int fd, Error **errp)
  124. {
  125. struct vfio_irq_set *irq_set;
  126. int argsz, ret = 0;
  127. const char *name;
  128. int32_t *pfd;
  129. argsz = sizeof(*irq_set) + sizeof(*pfd);
  130. irq_set = g_malloc0(argsz);
  131. irq_set->argsz = argsz;
  132. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action;
  133. irq_set->index = index;
  134. irq_set->start = subindex;
  135. irq_set->count = 1;
  136. pfd = (int32_t *)&irq_set->data;
  137. *pfd = fd;
  138. if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
  139. ret = -errno;
  140. }
  141. g_free(irq_set);
  142. if (!ret) {
  143. return 0;
  144. }
  145. error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure");
  146. name = index_to_str(vbasedev, index);
  147. if (name) {
  148. error_prepend(errp, "%s-%d: ", name, subindex);
  149. } else {
  150. error_prepend(errp, "index %d-%d: ", index, subindex);
  151. }
  152. error_prepend(errp,
  153. "Failed to %s %s eventfd signaling for interrupt ",
  154. fd < 0 ? "tear down" : "set up", action_to_str(action));
  155. return ret;
  156. }
  157. /*
  158. * IO Port/MMIO - Beware of the endians, VFIO is always little endian
  159. */
  160. void vfio_region_write(void *opaque, hwaddr addr,
  161. uint64_t data, unsigned size)
  162. {
  163. VFIORegion *region = opaque;
  164. VFIODevice *vbasedev = region->vbasedev;
  165. union {
  166. uint8_t byte;
  167. uint16_t word;
  168. uint32_t dword;
  169. uint64_t qword;
  170. } buf;
  171. switch (size) {
  172. case 1:
  173. buf.byte = data;
  174. break;
  175. case 2:
  176. buf.word = cpu_to_le16(data);
  177. break;
  178. case 4:
  179. buf.dword = cpu_to_le32(data);
  180. break;
  181. case 8:
  182. buf.qword = cpu_to_le64(data);
  183. break;
  184. default:
  185. hw_error("vfio: unsupported write size, %d bytes", size);
  186. break;
  187. }
  188. if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
  189. error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
  190. ",%d) failed: %m",
  191. __func__, vbasedev->name, region->nr,
  192. addr, data, size);
  193. }
  194. trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
  195. /*
  196. * A read or write to a BAR always signals an INTx EOI. This will
  197. * do nothing if not pending (including not in INTx mode). We assume
  198. * that a BAR access is in response to an interrupt and that BAR
  199. * accesses will service the interrupt. Unfortunately, we don't know
  200. * which access will service the interrupt, so we're potentially
  201. * getting quite a few host interrupts per guest interrupt.
  202. */
  203. vbasedev->ops->vfio_eoi(vbasedev);
  204. }
  205. uint64_t vfio_region_read(void *opaque,
  206. hwaddr addr, unsigned size)
  207. {
  208. VFIORegion *region = opaque;
  209. VFIODevice *vbasedev = region->vbasedev;
  210. union {
  211. uint8_t byte;
  212. uint16_t word;
  213. uint32_t dword;
  214. uint64_t qword;
  215. } buf;
  216. uint64_t data = 0;
  217. if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
  218. error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
  219. __func__, vbasedev->name, region->nr,
  220. addr, size);
  221. return (uint64_t)-1;
  222. }
  223. switch (size) {
  224. case 1:
  225. data = buf.byte;
  226. break;
  227. case 2:
  228. data = le16_to_cpu(buf.word);
  229. break;
  230. case 4:
  231. data = le32_to_cpu(buf.dword);
  232. break;
  233. case 8:
  234. data = le64_to_cpu(buf.qword);
  235. break;
  236. default:
  237. hw_error("vfio: unsupported read size, %d bytes", size);
  238. break;
  239. }
  240. trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
  241. /* Same as write above */
  242. vbasedev->ops->vfio_eoi(vbasedev);
  243. return data;
  244. }
  245. const MemoryRegionOps vfio_region_ops = {
  246. .read = vfio_region_read,
  247. .write = vfio_region_write,
  248. .endianness = DEVICE_LITTLE_ENDIAN,
  249. .valid = {
  250. .min_access_size = 1,
  251. .max_access_size = 8,
  252. },
  253. .impl = {
  254. .min_access_size = 1,
  255. .max_access_size = 8,
  256. },
  257. };
  258. /*
  259. * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
  260. */
  261. static int vfio_dma_unmap(VFIOContainer *container,
  262. hwaddr iova, ram_addr_t size)
  263. {
  264. struct vfio_iommu_type1_dma_unmap unmap = {
  265. .argsz = sizeof(unmap),
  266. .flags = 0,
  267. .iova = iova,
  268. .size = size,
  269. };
  270. while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
  271. /*
  272. * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
  273. * v4.15) where an overflow in its wrap-around check prevents us from
  274. * unmapping the last page of the address space. Test for the error
  275. * condition and re-try the unmap excluding the last page. The
  276. * expectation is that we've never mapped the last page anyway and this
  277. * unmap request comes via vIOMMU support which also makes it unlikely
  278. * that this page is used. This bug was introduced well after type1 v2
  279. * support was introduced, so we shouldn't need to test for v1. A fix
  280. * is queued for kernel v5.0 so this workaround can be removed once
  281. * affected kernels are sufficiently deprecated.
  282. */
  283. if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
  284. container->iommu_type == VFIO_TYPE1v2_IOMMU) {
  285. trace_vfio_dma_unmap_overflow_workaround();
  286. unmap.size -= 1ULL << ctz64(container->pgsizes);
  287. continue;
  288. }
  289. error_report("VFIO_UNMAP_DMA: %d", -errno);
  290. return -errno;
  291. }
  292. return 0;
  293. }
  294. static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
  295. ram_addr_t size, void *vaddr, bool readonly)
  296. {
  297. struct vfio_iommu_type1_dma_map map = {
  298. .argsz = sizeof(map),
  299. .flags = VFIO_DMA_MAP_FLAG_READ,
  300. .vaddr = (__u64)(uintptr_t)vaddr,
  301. .iova = iova,
  302. .size = size,
  303. };
  304. if (!readonly) {
  305. map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
  306. }
  307. /*
  308. * Try the mapping, if it fails with EBUSY, unmap the region and try
  309. * again. This shouldn't be necessary, but we sometimes see it in
  310. * the VGA ROM space.
  311. */
  312. if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
  313. (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
  314. ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
  315. return 0;
  316. }
  317. error_report("VFIO_MAP_DMA: %d", -errno);
  318. return -errno;
  319. }
  320. static void vfio_host_win_add(VFIOContainer *container,
  321. hwaddr min_iova, hwaddr max_iova,
  322. uint64_t iova_pgsizes)
  323. {
  324. VFIOHostDMAWindow *hostwin;
  325. QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
  326. if (ranges_overlap(hostwin->min_iova,
  327. hostwin->max_iova - hostwin->min_iova + 1,
  328. min_iova,
  329. max_iova - min_iova + 1)) {
  330. hw_error("%s: Overlapped IOMMU are not enabled", __func__);
  331. }
  332. }
  333. hostwin = g_malloc0(sizeof(*hostwin));
  334. hostwin->min_iova = min_iova;
  335. hostwin->max_iova = max_iova;
  336. hostwin->iova_pgsizes = iova_pgsizes;
  337. QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
  338. }
  339. static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
  340. hwaddr max_iova)
  341. {
  342. VFIOHostDMAWindow *hostwin;
  343. QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
  344. if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
  345. QLIST_REMOVE(hostwin, hostwin_next);
  346. return 0;
  347. }
  348. }
  349. return -1;
  350. }
  351. static bool vfio_listener_skipped_section(MemoryRegionSection *section)
  352. {
  353. return (!memory_region_is_ram(section->mr) &&
  354. !memory_region_is_iommu(section->mr)) ||
  355. /*
  356. * Sizing an enabled 64-bit BAR can cause spurious mappings to
  357. * addresses in the upper part of the 64-bit address space. These
  358. * are never accessed by the CPU and beyond the address width of
  359. * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
  360. */
  361. section->offset_within_address_space & (1ULL << 63);
  362. }
  363. /* Called with rcu_read_lock held. */
  364. static bool vfio_get_vaddr(IOMMUTLBEntry *iotlb, void **vaddr,
  365. bool *read_only)
  366. {
  367. MemoryRegion *mr;
  368. hwaddr xlat;
  369. hwaddr len = iotlb->addr_mask + 1;
  370. bool writable = iotlb->perm & IOMMU_WO;
  371. /*
  372. * The IOMMU TLB entry we have just covers translation through
  373. * this IOMMU to its immediate target. We need to translate
  374. * it the rest of the way through to memory.
  375. */
  376. mr = address_space_translate(&address_space_memory,
  377. iotlb->translated_addr,
  378. &xlat, &len, writable,
  379. MEMTXATTRS_UNSPECIFIED);
  380. if (!memory_region_is_ram(mr)) {
  381. error_report("iommu map to non memory area %"HWADDR_PRIx"",
  382. xlat);
  383. return false;
  384. }
  385. /*
  386. * Translation truncates length to the IOMMU page size,
  387. * check that it did not truncate too much.
  388. */
  389. if (len & iotlb->addr_mask) {
  390. error_report("iommu has granularity incompatible with target AS");
  391. return false;
  392. }
  393. *vaddr = memory_region_get_ram_ptr(mr) + xlat;
  394. *read_only = !writable || mr->readonly;
  395. return true;
  396. }
  397. static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
  398. {
  399. VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
  400. VFIOContainer *container = giommu->container;
  401. hwaddr iova = iotlb->iova + giommu->iommu_offset;
  402. bool read_only;
  403. void *vaddr;
  404. int ret;
  405. trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
  406. iova, iova + iotlb->addr_mask);
  407. if (iotlb->target_as != &address_space_memory) {
  408. error_report("Wrong target AS \"%s\", only system memory is allowed",
  409. iotlb->target_as->name ? iotlb->target_as->name : "none");
  410. return;
  411. }
  412. rcu_read_lock();
  413. if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
  414. if (!vfio_get_vaddr(iotlb, &vaddr, &read_only)) {
  415. goto out;
  416. }
  417. /*
  418. * vaddr is only valid until rcu_read_unlock(). But after
  419. * vfio_dma_map has set up the mapping the pages will be
  420. * pinned by the kernel. This makes sure that the RAM backend
  421. * of vaddr will always be there, even if the memory object is
  422. * destroyed and its backing memory munmap-ed.
  423. */
  424. ret = vfio_dma_map(container, iova,
  425. iotlb->addr_mask + 1, vaddr,
  426. read_only);
  427. if (ret) {
  428. error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
  429. "0x%"HWADDR_PRIx", %p) = %d (%m)",
  430. container, iova,
  431. iotlb->addr_mask + 1, vaddr, ret);
  432. }
  433. } else {
  434. ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1);
  435. if (ret) {
  436. error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
  437. "0x%"HWADDR_PRIx") = %d (%m)",
  438. container, iova,
  439. iotlb->addr_mask + 1, ret);
  440. }
  441. }
  442. out:
  443. rcu_read_unlock();
  444. }
  445. static void vfio_listener_region_add(MemoryListener *listener,
  446. MemoryRegionSection *section)
  447. {
  448. VFIOContainer *container = container_of(listener, VFIOContainer, listener);
  449. hwaddr iova, end;
  450. Int128 llend, llsize;
  451. void *vaddr;
  452. int ret;
  453. VFIOHostDMAWindow *hostwin;
  454. bool hostwin_found;
  455. Error *err = NULL;
  456. if (vfio_listener_skipped_section(section)) {
  457. trace_vfio_listener_region_add_skip(
  458. section->offset_within_address_space,
  459. section->offset_within_address_space +
  460. int128_get64(int128_sub(section->size, int128_one())));
  461. return;
  462. }
  463. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  464. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  465. error_report("%s received unaligned region", __func__);
  466. return;
  467. }
  468. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  469. llend = int128_make64(section->offset_within_address_space);
  470. llend = int128_add(llend, section->size);
  471. llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
  472. if (int128_ge(int128_make64(iova), llend)) {
  473. return;
  474. }
  475. end = int128_get64(int128_sub(llend, int128_one()));
  476. if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
  477. hwaddr pgsize = 0;
  478. /* For now intersections are not allowed, we may relax this later */
  479. QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
  480. if (ranges_overlap(hostwin->min_iova,
  481. hostwin->max_iova - hostwin->min_iova + 1,
  482. section->offset_within_address_space,
  483. int128_get64(section->size))) {
  484. error_setg(&err,
  485. "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing"
  486. "host DMA window [0x%"PRIx64",0x%"PRIx64"]",
  487. section->offset_within_address_space,
  488. section->offset_within_address_space +
  489. int128_get64(section->size) - 1,
  490. hostwin->min_iova, hostwin->max_iova);
  491. goto fail;
  492. }
  493. }
  494. ret = vfio_spapr_create_window(container, section, &pgsize);
  495. if (ret) {
  496. error_setg_errno(&err, -ret, "Failed to create SPAPR window");
  497. goto fail;
  498. }
  499. vfio_host_win_add(container, section->offset_within_address_space,
  500. section->offset_within_address_space +
  501. int128_get64(section->size) - 1, pgsize);
  502. #ifdef CONFIG_KVM
  503. if (kvm_enabled()) {
  504. VFIOGroup *group;
  505. IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
  506. struct kvm_vfio_spapr_tce param;
  507. struct kvm_device_attr attr = {
  508. .group = KVM_DEV_VFIO_GROUP,
  509. .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
  510. .addr = (uint64_t)(unsigned long)&param,
  511. };
  512. if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
  513. &param.tablefd)) {
  514. QLIST_FOREACH(group, &container->group_list, container_next) {
  515. param.groupfd = group->fd;
  516. if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
  517. error_report("vfio: failed to setup fd %d "
  518. "for a group with fd %d: %s",
  519. param.tablefd, param.groupfd,
  520. strerror(errno));
  521. return;
  522. }
  523. trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
  524. }
  525. }
  526. }
  527. #endif
  528. }
  529. hostwin_found = false;
  530. QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
  531. if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
  532. hostwin_found = true;
  533. break;
  534. }
  535. }
  536. if (!hostwin_found) {
  537. error_setg(&err, "Container %p can't map guest IOVA region"
  538. " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
  539. goto fail;
  540. }
  541. memory_region_ref(section->mr);
  542. if (memory_region_is_iommu(section->mr)) {
  543. VFIOGuestIOMMU *giommu;
  544. IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
  545. int iommu_idx;
  546. trace_vfio_listener_region_add_iommu(iova, end);
  547. /*
  548. * FIXME: For VFIO iommu types which have KVM acceleration to
  549. * avoid bouncing all map/unmaps through qemu this way, this
  550. * would be the right place to wire that up (tell the KVM
  551. * device emulation the VFIO iommu handles to use).
  552. */
  553. giommu = g_malloc0(sizeof(*giommu));
  554. giommu->iommu = iommu_mr;
  555. giommu->iommu_offset = section->offset_within_address_space -
  556. section->offset_within_region;
  557. giommu->container = container;
  558. llend = int128_add(int128_make64(section->offset_within_region),
  559. section->size);
  560. llend = int128_sub(llend, int128_one());
  561. iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
  562. MEMTXATTRS_UNSPECIFIED);
  563. iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
  564. IOMMU_NOTIFIER_ALL,
  565. section->offset_within_region,
  566. int128_get64(llend),
  567. iommu_idx);
  568. ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
  569. &err);
  570. if (ret) {
  571. g_free(giommu);
  572. goto fail;
  573. }
  574. QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
  575. memory_region_iommu_replay(giommu->iommu, &giommu->n);
  576. return;
  577. }
  578. /* Here we assume that memory_region_is_ram(section->mr)==true */
  579. vaddr = memory_region_get_ram_ptr(section->mr) +
  580. section->offset_within_region +
  581. (iova - section->offset_within_address_space);
  582. trace_vfio_listener_region_add_ram(iova, end, vaddr);
  583. llsize = int128_sub(llend, int128_make64(iova));
  584. if (memory_region_is_ram_device(section->mr)) {
  585. hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
  586. if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
  587. trace_vfio_listener_region_add_no_dma_map(
  588. memory_region_name(section->mr),
  589. section->offset_within_address_space,
  590. int128_getlo(section->size),
  591. pgmask + 1);
  592. return;
  593. }
  594. }
  595. ret = vfio_dma_map(container, iova, int128_get64(llsize),
  596. vaddr, section->readonly);
  597. if (ret) {
  598. error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
  599. "0x%"HWADDR_PRIx", %p) = %d (%m)",
  600. container, iova, int128_get64(llsize), vaddr, ret);
  601. if (memory_region_is_ram_device(section->mr)) {
  602. /* Allow unexpected mappings not to be fatal for RAM devices */
  603. error_report_err(err);
  604. return;
  605. }
  606. goto fail;
  607. }
  608. return;
  609. fail:
  610. if (memory_region_is_ram_device(section->mr)) {
  611. error_report("failed to vfio_dma_map. pci p2p may not work");
  612. return;
  613. }
  614. /*
  615. * On the initfn path, store the first error in the container so we
  616. * can gracefully fail. Runtime, there's not much we can do other
  617. * than throw a hardware error.
  618. */
  619. if (!container->initialized) {
  620. if (!container->error) {
  621. error_propagate_prepend(&container->error, err,
  622. "Region %s: ",
  623. memory_region_name(section->mr));
  624. } else {
  625. error_free(err);
  626. }
  627. } else {
  628. error_report_err(err);
  629. hw_error("vfio: DMA mapping failed, unable to continue");
  630. }
  631. }
  632. static void vfio_listener_region_del(MemoryListener *listener,
  633. MemoryRegionSection *section)
  634. {
  635. VFIOContainer *container = container_of(listener, VFIOContainer, listener);
  636. hwaddr iova, end;
  637. Int128 llend, llsize;
  638. int ret;
  639. bool try_unmap = true;
  640. if (vfio_listener_skipped_section(section)) {
  641. trace_vfio_listener_region_del_skip(
  642. section->offset_within_address_space,
  643. section->offset_within_address_space +
  644. int128_get64(int128_sub(section->size, int128_one())));
  645. return;
  646. }
  647. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  648. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  649. error_report("%s received unaligned region", __func__);
  650. return;
  651. }
  652. if (memory_region_is_iommu(section->mr)) {
  653. VFIOGuestIOMMU *giommu;
  654. QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
  655. if (MEMORY_REGION(giommu->iommu) == section->mr &&
  656. giommu->n.start == section->offset_within_region) {
  657. memory_region_unregister_iommu_notifier(section->mr,
  658. &giommu->n);
  659. QLIST_REMOVE(giommu, giommu_next);
  660. g_free(giommu);
  661. break;
  662. }
  663. }
  664. /*
  665. * FIXME: We assume the one big unmap below is adequate to
  666. * remove any individual page mappings in the IOMMU which
  667. * might have been copied into VFIO. This works for a page table
  668. * based IOMMU where a big unmap flattens a large range of IO-PTEs.
  669. * That may not be true for all IOMMU types.
  670. */
  671. }
  672. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  673. llend = int128_make64(section->offset_within_address_space);
  674. llend = int128_add(llend, section->size);
  675. llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
  676. if (int128_ge(int128_make64(iova), llend)) {
  677. return;
  678. }
  679. end = int128_get64(int128_sub(llend, int128_one()));
  680. llsize = int128_sub(llend, int128_make64(iova));
  681. trace_vfio_listener_region_del(iova, end);
  682. if (memory_region_is_ram_device(section->mr)) {
  683. hwaddr pgmask;
  684. VFIOHostDMAWindow *hostwin;
  685. bool hostwin_found = false;
  686. QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
  687. if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
  688. hostwin_found = true;
  689. break;
  690. }
  691. }
  692. assert(hostwin_found); /* or region_add() would have failed */
  693. pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
  694. try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
  695. }
  696. if (try_unmap) {
  697. ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
  698. if (ret) {
  699. error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
  700. "0x%"HWADDR_PRIx") = %d (%m)",
  701. container, iova, int128_get64(llsize), ret);
  702. }
  703. }
  704. memory_region_unref(section->mr);
  705. if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
  706. vfio_spapr_remove_window(container,
  707. section->offset_within_address_space);
  708. if (vfio_host_win_del(container,
  709. section->offset_within_address_space,
  710. section->offset_within_address_space +
  711. int128_get64(section->size) - 1) < 0) {
  712. hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
  713. __func__, section->offset_within_address_space);
  714. }
  715. }
  716. }
  717. static const MemoryListener vfio_memory_listener = {
  718. .region_add = vfio_listener_region_add,
  719. .region_del = vfio_listener_region_del,
  720. };
  721. static void vfio_listener_release(VFIOContainer *container)
  722. {
  723. memory_listener_unregister(&container->listener);
  724. if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
  725. memory_listener_unregister(&container->prereg_listener);
  726. }
  727. }
  728. struct vfio_info_cap_header *
  729. vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
  730. {
  731. struct vfio_info_cap_header *hdr;
  732. void *ptr = info;
  733. if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
  734. return NULL;
  735. }
  736. for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
  737. if (hdr->id == id) {
  738. return hdr;
  739. }
  740. }
  741. return NULL;
  742. }
  743. static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
  744. struct vfio_region_info *info)
  745. {
  746. struct vfio_info_cap_header *hdr;
  747. struct vfio_region_info_cap_sparse_mmap *sparse;
  748. int i, j;
  749. hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
  750. if (!hdr) {
  751. return -ENODEV;
  752. }
  753. sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
  754. trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
  755. region->nr, sparse->nr_areas);
  756. region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
  757. for (i = 0, j = 0; i < sparse->nr_areas; i++) {
  758. trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
  759. sparse->areas[i].offset +
  760. sparse->areas[i].size);
  761. if (sparse->areas[i].size) {
  762. region->mmaps[j].offset = sparse->areas[i].offset;
  763. region->mmaps[j].size = sparse->areas[i].size;
  764. j++;
  765. }
  766. }
  767. region->nr_mmaps = j;
  768. region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
  769. return 0;
  770. }
  771. int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
  772. int index, const char *name)
  773. {
  774. struct vfio_region_info *info;
  775. int ret;
  776. ret = vfio_get_region_info(vbasedev, index, &info);
  777. if (ret) {
  778. return ret;
  779. }
  780. region->vbasedev = vbasedev;
  781. region->flags = info->flags;
  782. region->size = info->size;
  783. region->fd_offset = info->offset;
  784. region->nr = index;
  785. if (region->size) {
  786. region->mem = g_new0(MemoryRegion, 1);
  787. memory_region_init_io(region->mem, obj, &vfio_region_ops,
  788. region, name, region->size);
  789. if (!vbasedev->no_mmap &&
  790. region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
  791. ret = vfio_setup_region_sparse_mmaps(region, info);
  792. if (ret) {
  793. region->nr_mmaps = 1;
  794. region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
  795. region->mmaps[0].offset = 0;
  796. region->mmaps[0].size = region->size;
  797. }
  798. }
  799. }
  800. g_free(info);
  801. trace_vfio_region_setup(vbasedev->name, index, name,
  802. region->flags, region->fd_offset, region->size);
  803. return 0;
  804. }
  805. int vfio_region_mmap(VFIORegion *region)
  806. {
  807. int i, prot = 0;
  808. char *name;
  809. if (!region->mem) {
  810. return 0;
  811. }
  812. prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
  813. prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
  814. for (i = 0; i < region->nr_mmaps; i++) {
  815. region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
  816. MAP_SHARED, region->vbasedev->fd,
  817. region->fd_offset +
  818. region->mmaps[i].offset);
  819. if (region->mmaps[i].mmap == MAP_FAILED) {
  820. int ret = -errno;
  821. trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
  822. region->fd_offset +
  823. region->mmaps[i].offset,
  824. region->fd_offset +
  825. region->mmaps[i].offset +
  826. region->mmaps[i].size - 1, ret);
  827. region->mmaps[i].mmap = NULL;
  828. for (i--; i >= 0; i--) {
  829. memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
  830. munmap(region->mmaps[i].mmap, region->mmaps[i].size);
  831. object_unparent(OBJECT(&region->mmaps[i].mem));
  832. region->mmaps[i].mmap = NULL;
  833. }
  834. return ret;
  835. }
  836. name = g_strdup_printf("%s mmaps[%d]",
  837. memory_region_name(region->mem), i);
  838. memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
  839. memory_region_owner(region->mem),
  840. name, region->mmaps[i].size,
  841. region->mmaps[i].mmap);
  842. g_free(name);
  843. memory_region_add_subregion(region->mem, region->mmaps[i].offset,
  844. &region->mmaps[i].mem);
  845. trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
  846. region->mmaps[i].offset,
  847. region->mmaps[i].offset +
  848. region->mmaps[i].size - 1);
  849. }
  850. return 0;
  851. }
  852. void vfio_region_exit(VFIORegion *region)
  853. {
  854. int i;
  855. if (!region->mem) {
  856. return;
  857. }
  858. for (i = 0; i < region->nr_mmaps; i++) {
  859. if (region->mmaps[i].mmap) {
  860. memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
  861. }
  862. }
  863. trace_vfio_region_exit(region->vbasedev->name, region->nr);
  864. }
  865. void vfio_region_finalize(VFIORegion *region)
  866. {
  867. int i;
  868. if (!region->mem) {
  869. return;
  870. }
  871. for (i = 0; i < region->nr_mmaps; i++) {
  872. if (region->mmaps[i].mmap) {
  873. munmap(region->mmaps[i].mmap, region->mmaps[i].size);
  874. object_unparent(OBJECT(&region->mmaps[i].mem));
  875. }
  876. }
  877. object_unparent(OBJECT(region->mem));
  878. g_free(region->mem);
  879. g_free(region->mmaps);
  880. trace_vfio_region_finalize(region->vbasedev->name, region->nr);
  881. region->mem = NULL;
  882. region->mmaps = NULL;
  883. region->nr_mmaps = 0;
  884. region->size = 0;
  885. region->flags = 0;
  886. region->nr = 0;
  887. }
  888. void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
  889. {
  890. int i;
  891. if (!region->mem) {
  892. return;
  893. }
  894. for (i = 0; i < region->nr_mmaps; i++) {
  895. if (region->mmaps[i].mmap) {
  896. memory_region_set_enabled(&region->mmaps[i].mem, enabled);
  897. }
  898. }
  899. trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
  900. enabled);
  901. }
  902. void vfio_reset_handler(void *opaque)
  903. {
  904. VFIOGroup *group;
  905. VFIODevice *vbasedev;
  906. QLIST_FOREACH(group, &vfio_group_list, next) {
  907. QLIST_FOREACH(vbasedev, &group->device_list, next) {
  908. if (vbasedev->dev->realized) {
  909. vbasedev->ops->vfio_compute_needs_reset(vbasedev);
  910. }
  911. }
  912. }
  913. QLIST_FOREACH(group, &vfio_group_list, next) {
  914. QLIST_FOREACH(vbasedev, &group->device_list, next) {
  915. if (vbasedev->dev->realized && vbasedev->needs_reset) {
  916. vbasedev->ops->vfio_hot_reset_multi(vbasedev);
  917. }
  918. }
  919. }
  920. }
  921. static void vfio_kvm_device_add_group(VFIOGroup *group)
  922. {
  923. #ifdef CONFIG_KVM
  924. struct kvm_device_attr attr = {
  925. .group = KVM_DEV_VFIO_GROUP,
  926. .attr = KVM_DEV_VFIO_GROUP_ADD,
  927. .addr = (uint64_t)(unsigned long)&group->fd,
  928. };
  929. if (!kvm_enabled()) {
  930. return;
  931. }
  932. if (vfio_kvm_device_fd < 0) {
  933. struct kvm_create_device cd = {
  934. .type = KVM_DEV_TYPE_VFIO,
  935. };
  936. if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
  937. error_report("Failed to create KVM VFIO device: %m");
  938. return;
  939. }
  940. vfio_kvm_device_fd = cd.fd;
  941. }
  942. if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
  943. error_report("Failed to add group %d to KVM VFIO device: %m",
  944. group->groupid);
  945. }
  946. #endif
  947. }
  948. static void vfio_kvm_device_del_group(VFIOGroup *group)
  949. {
  950. #ifdef CONFIG_KVM
  951. struct kvm_device_attr attr = {
  952. .group = KVM_DEV_VFIO_GROUP,
  953. .attr = KVM_DEV_VFIO_GROUP_DEL,
  954. .addr = (uint64_t)(unsigned long)&group->fd,
  955. };
  956. if (vfio_kvm_device_fd < 0) {
  957. return;
  958. }
  959. if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
  960. error_report("Failed to remove group %d from KVM VFIO device: %m",
  961. group->groupid);
  962. }
  963. #endif
  964. }
  965. static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
  966. {
  967. VFIOAddressSpace *space;
  968. QLIST_FOREACH(space, &vfio_address_spaces, list) {
  969. if (space->as == as) {
  970. return space;
  971. }
  972. }
  973. /* No suitable VFIOAddressSpace, create a new one */
  974. space = g_malloc0(sizeof(*space));
  975. space->as = as;
  976. QLIST_INIT(&space->containers);
  977. QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
  978. return space;
  979. }
  980. static void vfio_put_address_space(VFIOAddressSpace *space)
  981. {
  982. if (QLIST_EMPTY(&space->containers)) {
  983. QLIST_REMOVE(space, list);
  984. g_free(space);
  985. }
  986. }
  987. /*
  988. * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
  989. */
  990. static int vfio_get_iommu_type(VFIOContainer *container,
  991. Error **errp)
  992. {
  993. int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
  994. VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
  995. int i;
  996. for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
  997. if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
  998. return iommu_types[i];
  999. }
  1000. }
  1001. error_setg(errp, "No available IOMMU models");
  1002. return -EINVAL;
  1003. }
  1004. static int vfio_init_container(VFIOContainer *container, int group_fd,
  1005. Error **errp)
  1006. {
  1007. int iommu_type, ret;
  1008. iommu_type = vfio_get_iommu_type(container, errp);
  1009. if (iommu_type < 0) {
  1010. return iommu_type;
  1011. }
  1012. ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
  1013. if (ret) {
  1014. error_setg_errno(errp, errno, "Failed to set group container");
  1015. return -errno;
  1016. }
  1017. while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
  1018. if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
  1019. /*
  1020. * On sPAPR, despite the IOMMU subdriver always advertises v1 and
  1021. * v2, the running platform may not support v2 and there is no
  1022. * way to guess it until an IOMMU group gets added to the container.
  1023. * So in case it fails with v2, try v1 as a fallback.
  1024. */
  1025. iommu_type = VFIO_SPAPR_TCE_IOMMU;
  1026. continue;
  1027. }
  1028. error_setg_errno(errp, errno, "Failed to set iommu for container");
  1029. return -errno;
  1030. }
  1031. container->iommu_type = iommu_type;
  1032. return 0;
  1033. }
  1034. static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
  1035. Error **errp)
  1036. {
  1037. VFIOContainer *container;
  1038. int ret, fd;
  1039. VFIOAddressSpace *space;
  1040. space = vfio_get_address_space(as);
  1041. /*
  1042. * VFIO is currently incompatible with memory ballooning insofar as the
  1043. * madvise to purge (zap) the page from QEMU's address space does not
  1044. * interact with the memory API and therefore leaves stale virtual to
  1045. * physical mappings in the IOMMU if the page was previously pinned. We
  1046. * therefore add a balloon inhibit for each group added to a container,
  1047. * whether the container is used individually or shared. This provides
  1048. * us with options to allow devices within a group to opt-in and allow
  1049. * ballooning, so long as it is done consistently for a group (for instance
  1050. * if the device is an mdev device where it is known that the host vendor
  1051. * driver will never pin pages outside of the working set of the guest
  1052. * driver, which would thus not be ballooning candidates).
  1053. *
  1054. * The first opportunity to induce pinning occurs here where we attempt to
  1055. * attach the group to existing containers within the AddressSpace. If any
  1056. * pages are already zapped from the virtual address space, such as from a
  1057. * previous ballooning opt-in, new pinning will cause valid mappings to be
  1058. * re-established. Likewise, when the overall MemoryListener for a new
  1059. * container is registered, a replay of mappings within the AddressSpace
  1060. * will occur, re-establishing any previously zapped pages as well.
  1061. *
  1062. * NB. Balloon inhibiting does not currently block operation of the
  1063. * balloon driver or revoke previously pinned pages, it only prevents
  1064. * calling madvise to modify the virtual mapping of ballooned pages.
  1065. */
  1066. qemu_balloon_inhibit(true);
  1067. QLIST_FOREACH(container, &space->containers, next) {
  1068. if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
  1069. group->container = container;
  1070. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1071. vfio_kvm_device_add_group(group);
  1072. return 0;
  1073. }
  1074. }
  1075. fd = qemu_open("/dev/vfio/vfio", O_RDWR);
  1076. if (fd < 0) {
  1077. error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
  1078. ret = -errno;
  1079. goto put_space_exit;
  1080. }
  1081. ret = ioctl(fd, VFIO_GET_API_VERSION);
  1082. if (ret != VFIO_API_VERSION) {
  1083. error_setg(errp, "supported vfio version: %d, "
  1084. "reported version: %d", VFIO_API_VERSION, ret);
  1085. ret = -EINVAL;
  1086. goto close_fd_exit;
  1087. }
  1088. container = g_malloc0(sizeof(*container));
  1089. container->space = space;
  1090. container->fd = fd;
  1091. container->error = NULL;
  1092. QLIST_INIT(&container->giommu_list);
  1093. QLIST_INIT(&container->hostwin_list);
  1094. ret = vfio_init_container(container, group->fd, errp);
  1095. if (ret) {
  1096. goto free_container_exit;
  1097. }
  1098. switch (container->iommu_type) {
  1099. case VFIO_TYPE1v2_IOMMU:
  1100. case VFIO_TYPE1_IOMMU:
  1101. {
  1102. struct vfio_iommu_type1_info info;
  1103. /*
  1104. * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
  1105. * IOVA whatsoever. That's not actually true, but the current
  1106. * kernel interface doesn't tell us what it can map, and the
  1107. * existing Type1 IOMMUs generally support any IOVA we're
  1108. * going to actually try in practice.
  1109. */
  1110. info.argsz = sizeof(info);
  1111. ret = ioctl(fd, VFIO_IOMMU_GET_INFO, &info);
  1112. /* Ignore errors */
  1113. if (ret || !(info.flags & VFIO_IOMMU_INFO_PGSIZES)) {
  1114. /* Assume 4k IOVA page size */
  1115. info.iova_pgsizes = 4096;
  1116. }
  1117. vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
  1118. container->pgsizes = info.iova_pgsizes;
  1119. break;
  1120. }
  1121. case VFIO_SPAPR_TCE_v2_IOMMU:
  1122. case VFIO_SPAPR_TCE_IOMMU:
  1123. {
  1124. struct vfio_iommu_spapr_tce_info info;
  1125. bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU;
  1126. /*
  1127. * The host kernel code implementing VFIO_IOMMU_DISABLE is called
  1128. * when container fd is closed so we do not call it explicitly
  1129. * in this file.
  1130. */
  1131. if (!v2) {
  1132. ret = ioctl(fd, VFIO_IOMMU_ENABLE);
  1133. if (ret) {
  1134. error_setg_errno(errp, errno, "failed to enable container");
  1135. ret = -errno;
  1136. goto free_container_exit;
  1137. }
  1138. } else {
  1139. container->prereg_listener = vfio_prereg_listener;
  1140. memory_listener_register(&container->prereg_listener,
  1141. &address_space_memory);
  1142. if (container->error) {
  1143. memory_listener_unregister(&container->prereg_listener);
  1144. ret = -1;
  1145. error_propagate_prepend(errp, container->error,
  1146. "RAM memory listener initialization failed: ");
  1147. goto free_container_exit;
  1148. }
  1149. }
  1150. info.argsz = sizeof(info);
  1151. ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
  1152. if (ret) {
  1153. error_setg_errno(errp, errno,
  1154. "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
  1155. ret = -errno;
  1156. if (v2) {
  1157. memory_listener_unregister(&container->prereg_listener);
  1158. }
  1159. goto free_container_exit;
  1160. }
  1161. if (v2) {
  1162. container->pgsizes = info.ddw.pgsizes;
  1163. /*
  1164. * There is a default window in just created container.
  1165. * To make region_add/del simpler, we better remove this
  1166. * window now and let those iommu_listener callbacks
  1167. * create/remove them when needed.
  1168. */
  1169. ret = vfio_spapr_remove_window(container, info.dma32_window_start);
  1170. if (ret) {
  1171. error_setg_errno(errp, -ret,
  1172. "failed to remove existing window");
  1173. goto free_container_exit;
  1174. }
  1175. } else {
  1176. /* The default table uses 4K pages */
  1177. container->pgsizes = 0x1000;
  1178. vfio_host_win_add(container, info.dma32_window_start,
  1179. info.dma32_window_start +
  1180. info.dma32_window_size - 1,
  1181. 0x1000);
  1182. }
  1183. }
  1184. }
  1185. vfio_kvm_device_add_group(group);
  1186. QLIST_INIT(&container->group_list);
  1187. QLIST_INSERT_HEAD(&space->containers, container, next);
  1188. group->container = container;
  1189. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1190. container->listener = vfio_memory_listener;
  1191. memory_listener_register(&container->listener, container->space->as);
  1192. if (container->error) {
  1193. ret = -1;
  1194. error_propagate_prepend(errp, container->error,
  1195. "memory listener initialization failed: ");
  1196. goto listener_release_exit;
  1197. }
  1198. container->initialized = true;
  1199. return 0;
  1200. listener_release_exit:
  1201. QLIST_REMOVE(group, container_next);
  1202. QLIST_REMOVE(container, next);
  1203. vfio_kvm_device_del_group(group);
  1204. vfio_listener_release(container);
  1205. free_container_exit:
  1206. g_free(container);
  1207. close_fd_exit:
  1208. close(fd);
  1209. put_space_exit:
  1210. qemu_balloon_inhibit(false);
  1211. vfio_put_address_space(space);
  1212. return ret;
  1213. }
  1214. static void vfio_disconnect_container(VFIOGroup *group)
  1215. {
  1216. VFIOContainer *container = group->container;
  1217. QLIST_REMOVE(group, container_next);
  1218. group->container = NULL;
  1219. /*
  1220. * Explicitly release the listener first before unset container,
  1221. * since unset may destroy the backend container if it's the last
  1222. * group.
  1223. */
  1224. if (QLIST_EMPTY(&container->group_list)) {
  1225. vfio_listener_release(container);
  1226. }
  1227. if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
  1228. error_report("vfio: error disconnecting group %d from container",
  1229. group->groupid);
  1230. }
  1231. if (QLIST_EMPTY(&container->group_list)) {
  1232. VFIOAddressSpace *space = container->space;
  1233. VFIOGuestIOMMU *giommu, *tmp;
  1234. QLIST_REMOVE(container, next);
  1235. QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
  1236. memory_region_unregister_iommu_notifier(
  1237. MEMORY_REGION(giommu->iommu), &giommu->n);
  1238. QLIST_REMOVE(giommu, giommu_next);
  1239. g_free(giommu);
  1240. }
  1241. trace_vfio_disconnect_container(container->fd);
  1242. close(container->fd);
  1243. g_free(container);
  1244. vfio_put_address_space(space);
  1245. }
  1246. }
  1247. VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
  1248. {
  1249. VFIOGroup *group;
  1250. char path[32];
  1251. struct vfio_group_status status = { .argsz = sizeof(status) };
  1252. QLIST_FOREACH(group, &vfio_group_list, next) {
  1253. if (group->groupid == groupid) {
  1254. /* Found it. Now is it already in the right context? */
  1255. if (group->container->space->as == as) {
  1256. return group;
  1257. } else {
  1258. error_setg(errp, "group %d used in multiple address spaces",
  1259. group->groupid);
  1260. return NULL;
  1261. }
  1262. }
  1263. }
  1264. group = g_malloc0(sizeof(*group));
  1265. snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
  1266. group->fd = qemu_open(path, O_RDWR);
  1267. if (group->fd < 0) {
  1268. error_setg_errno(errp, errno, "failed to open %s", path);
  1269. goto free_group_exit;
  1270. }
  1271. if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
  1272. error_setg_errno(errp, errno, "failed to get group %d status", groupid);
  1273. goto close_fd_exit;
  1274. }
  1275. if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
  1276. error_setg(errp, "group %d is not viable", groupid);
  1277. error_append_hint(errp,
  1278. "Please ensure all devices within the iommu_group "
  1279. "are bound to their vfio bus driver.\n");
  1280. goto close_fd_exit;
  1281. }
  1282. group->groupid = groupid;
  1283. QLIST_INIT(&group->device_list);
  1284. if (vfio_connect_container(group, as, errp)) {
  1285. error_prepend(errp, "failed to setup container for group %d: ",
  1286. groupid);
  1287. goto close_fd_exit;
  1288. }
  1289. if (QLIST_EMPTY(&vfio_group_list)) {
  1290. qemu_register_reset(vfio_reset_handler, NULL);
  1291. }
  1292. QLIST_INSERT_HEAD(&vfio_group_list, group, next);
  1293. return group;
  1294. close_fd_exit:
  1295. close(group->fd);
  1296. free_group_exit:
  1297. g_free(group);
  1298. return NULL;
  1299. }
  1300. void vfio_put_group(VFIOGroup *group)
  1301. {
  1302. if (!group || !QLIST_EMPTY(&group->device_list)) {
  1303. return;
  1304. }
  1305. if (!group->balloon_allowed) {
  1306. qemu_balloon_inhibit(false);
  1307. }
  1308. vfio_kvm_device_del_group(group);
  1309. vfio_disconnect_container(group);
  1310. QLIST_REMOVE(group, next);
  1311. trace_vfio_put_group(group->fd);
  1312. close(group->fd);
  1313. g_free(group);
  1314. if (QLIST_EMPTY(&vfio_group_list)) {
  1315. qemu_unregister_reset(vfio_reset_handler, NULL);
  1316. }
  1317. }
  1318. int vfio_get_device(VFIOGroup *group, const char *name,
  1319. VFIODevice *vbasedev, Error **errp)
  1320. {
  1321. struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
  1322. int ret, fd;
  1323. fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
  1324. if (fd < 0) {
  1325. error_setg_errno(errp, errno, "error getting device from group %d",
  1326. group->groupid);
  1327. error_append_hint(errp,
  1328. "Verify all devices in group %d are bound to vfio-<bus> "
  1329. "or pci-stub and not already in use\n", group->groupid);
  1330. return fd;
  1331. }
  1332. ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
  1333. if (ret) {
  1334. error_setg_errno(errp, errno, "error getting device info");
  1335. close(fd);
  1336. return ret;
  1337. }
  1338. /*
  1339. * Clear the balloon inhibitor for this group if the driver knows the
  1340. * device operates compatibly with ballooning. Setting must be consistent
  1341. * per group, but since compatibility is really only possible with mdev
  1342. * currently, we expect singleton groups.
  1343. */
  1344. if (vbasedev->balloon_allowed != group->balloon_allowed) {
  1345. if (!QLIST_EMPTY(&group->device_list)) {
  1346. error_setg(errp,
  1347. "Inconsistent device balloon setting within group");
  1348. close(fd);
  1349. return -1;
  1350. }
  1351. if (!group->balloon_allowed) {
  1352. group->balloon_allowed = true;
  1353. qemu_balloon_inhibit(false);
  1354. }
  1355. }
  1356. vbasedev->fd = fd;
  1357. vbasedev->group = group;
  1358. QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
  1359. vbasedev->num_irqs = dev_info.num_irqs;
  1360. vbasedev->num_regions = dev_info.num_regions;
  1361. vbasedev->flags = dev_info.flags;
  1362. trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
  1363. dev_info.num_irqs);
  1364. vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
  1365. return 0;
  1366. }
  1367. void vfio_put_base_device(VFIODevice *vbasedev)
  1368. {
  1369. if (!vbasedev->group) {
  1370. return;
  1371. }
  1372. QLIST_REMOVE(vbasedev, next);
  1373. vbasedev->group = NULL;
  1374. trace_vfio_put_base_device(vbasedev->fd);
  1375. close(vbasedev->fd);
  1376. }
  1377. int vfio_get_region_info(VFIODevice *vbasedev, int index,
  1378. struct vfio_region_info **info)
  1379. {
  1380. size_t argsz = sizeof(struct vfio_region_info);
  1381. *info = g_malloc0(argsz);
  1382. (*info)->index = index;
  1383. retry:
  1384. (*info)->argsz = argsz;
  1385. if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
  1386. g_free(*info);
  1387. *info = NULL;
  1388. return -errno;
  1389. }
  1390. if ((*info)->argsz > argsz) {
  1391. argsz = (*info)->argsz;
  1392. *info = g_realloc(*info, argsz);
  1393. goto retry;
  1394. }
  1395. return 0;
  1396. }
  1397. int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
  1398. uint32_t subtype, struct vfio_region_info **info)
  1399. {
  1400. int i;
  1401. for (i = 0; i < vbasedev->num_regions; i++) {
  1402. struct vfio_info_cap_header *hdr;
  1403. struct vfio_region_info_cap_type *cap_type;
  1404. if (vfio_get_region_info(vbasedev, i, info)) {
  1405. continue;
  1406. }
  1407. hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
  1408. if (!hdr) {
  1409. g_free(*info);
  1410. continue;
  1411. }
  1412. cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
  1413. trace_vfio_get_dev_region(vbasedev->name, i,
  1414. cap_type->type, cap_type->subtype);
  1415. if (cap_type->type == type && cap_type->subtype == subtype) {
  1416. return 0;
  1417. }
  1418. g_free(*info);
  1419. }
  1420. *info = NULL;
  1421. return -ENODEV;
  1422. }
  1423. bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
  1424. {
  1425. struct vfio_region_info *info = NULL;
  1426. bool ret = false;
  1427. if (!vfio_get_region_info(vbasedev, region, &info)) {
  1428. if (vfio_get_region_info_cap(info, cap_type)) {
  1429. ret = true;
  1430. }
  1431. g_free(info);
  1432. }
  1433. return ret;
  1434. }
  1435. /*
  1436. * Interfaces for IBM EEH (Enhanced Error Handling)
  1437. */
  1438. static bool vfio_eeh_container_ok(VFIOContainer *container)
  1439. {
  1440. /*
  1441. * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
  1442. * implementation is broken if there are multiple groups in a
  1443. * container. The hardware works in units of Partitionable
  1444. * Endpoints (== IOMMU groups) and the EEH operations naively
  1445. * iterate across all groups in the container, without any logic
  1446. * to make sure the groups have their state synchronized. For
  1447. * certain operations (ENABLE) that might be ok, until an error
  1448. * occurs, but for others (GET_STATE) it's clearly broken.
  1449. */
  1450. /*
  1451. * XXX Once fixed kernels exist, test for them here
  1452. */
  1453. if (QLIST_EMPTY(&container->group_list)) {
  1454. return false;
  1455. }
  1456. if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
  1457. return false;
  1458. }
  1459. return true;
  1460. }
  1461. static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
  1462. {
  1463. struct vfio_eeh_pe_op pe_op = {
  1464. .argsz = sizeof(pe_op),
  1465. .op = op,
  1466. };
  1467. int ret;
  1468. if (!vfio_eeh_container_ok(container)) {
  1469. error_report("vfio/eeh: EEH_PE_OP 0x%x: "
  1470. "kernel requires a container with exactly one group", op);
  1471. return -EPERM;
  1472. }
  1473. ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
  1474. if (ret < 0) {
  1475. error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
  1476. return -errno;
  1477. }
  1478. return ret;
  1479. }
  1480. static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
  1481. {
  1482. VFIOAddressSpace *space = vfio_get_address_space(as);
  1483. VFIOContainer *container = NULL;
  1484. if (QLIST_EMPTY(&space->containers)) {
  1485. /* No containers to act on */
  1486. goto out;
  1487. }
  1488. container = QLIST_FIRST(&space->containers);
  1489. if (QLIST_NEXT(container, next)) {
  1490. /* We don't yet have logic to synchronize EEH state across
  1491. * multiple containers */
  1492. container = NULL;
  1493. goto out;
  1494. }
  1495. out:
  1496. vfio_put_address_space(space);
  1497. return container;
  1498. }
  1499. bool vfio_eeh_as_ok(AddressSpace *as)
  1500. {
  1501. VFIOContainer *container = vfio_eeh_as_container(as);
  1502. return (container != NULL) && vfio_eeh_container_ok(container);
  1503. }
  1504. int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
  1505. {
  1506. VFIOContainer *container = vfio_eeh_as_container(as);
  1507. if (!container) {
  1508. return -ENODEV;
  1509. }
  1510. return vfio_eeh_container_op(container, op);
  1511. }