vfio_pci.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  1. /*
  2. * vfio based device assignment support
  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 <dirent.h>
  21. #include <unistd.h>
  22. #include <sys/ioctl.h>
  23. #include <sys/mman.h>
  24. #include <sys/stat.h>
  25. #include <sys/types.h>
  26. #include <linux/vfio.h>
  27. #include "config.h"
  28. #include "event_notifier.h"
  29. #include "exec-memory.h"
  30. #include "kvm.h"
  31. #include "memory.h"
  32. #include "pci/msi.h"
  33. #include "pci/msix.h"
  34. #include "pci/pci.h"
  35. #include "qemu-common.h"
  36. #include "qemu-error.h"
  37. #include "qemu-queue.h"
  38. #include "range.h"
  39. /* #define DEBUG_VFIO */
  40. #ifdef DEBUG_VFIO
  41. #define DPRINTF(fmt, ...) \
  42. do { fprintf(stderr, "vfio: " fmt, ## __VA_ARGS__); } while (0)
  43. #else
  44. #define DPRINTF(fmt, ...) \
  45. do { } while (0)
  46. #endif
  47. typedef struct VFIOBAR {
  48. off_t fd_offset; /* offset of BAR within device fd */
  49. int fd; /* device fd, allows us to pass VFIOBAR as opaque data */
  50. MemoryRegion mem; /* slow, read/write access */
  51. MemoryRegion mmap_mem; /* direct mapped access */
  52. void *mmap;
  53. size_t size;
  54. uint32_t flags; /* VFIO region flags (rd/wr/mmap) */
  55. uint8_t nr; /* cache the BAR number for debug */
  56. } VFIOBAR;
  57. typedef struct VFIOINTx {
  58. bool pending; /* interrupt pending */
  59. bool kvm_accel; /* set when QEMU bypass through KVM enabled */
  60. uint8_t pin; /* which pin to pull for qemu_set_irq */
  61. EventNotifier interrupt; /* eventfd triggered on interrupt */
  62. EventNotifier unmask; /* eventfd for unmask on QEMU bypass */
  63. PCIINTxRoute route; /* routing info for QEMU bypass */
  64. uint32_t mmap_timeout; /* delay to re-enable mmaps after interrupt */
  65. QEMUTimer *mmap_timer; /* enable mmaps after periods w/o interrupts */
  66. } VFIOINTx;
  67. struct VFIODevice;
  68. typedef struct VFIOMSIVector {
  69. EventNotifier interrupt; /* eventfd triggered on interrupt */
  70. struct VFIODevice *vdev; /* back pointer to device */
  71. int virq; /* KVM irqchip route for QEMU bypass */
  72. bool use;
  73. } VFIOMSIVector;
  74. enum {
  75. VFIO_INT_NONE = 0,
  76. VFIO_INT_INTx = 1,
  77. VFIO_INT_MSI = 2,
  78. VFIO_INT_MSIX = 3,
  79. };
  80. struct VFIOGroup;
  81. typedef struct VFIOContainer {
  82. int fd; /* /dev/vfio/vfio, empowered by the attached groups */
  83. struct {
  84. /* enable abstraction to support various iommu backends */
  85. union {
  86. MemoryListener listener; /* Used by type1 iommu */
  87. };
  88. void (*release)(struct VFIOContainer *);
  89. } iommu_data;
  90. QLIST_HEAD(, VFIOGroup) group_list;
  91. QLIST_ENTRY(VFIOContainer) next;
  92. } VFIOContainer;
  93. /* Cache of MSI-X setup plus extra mmap and memory region for split BAR map */
  94. typedef struct VFIOMSIXInfo {
  95. uint8_t table_bar;
  96. uint8_t pba_bar;
  97. uint16_t entries;
  98. uint32_t table_offset;
  99. uint32_t pba_offset;
  100. MemoryRegion mmap_mem;
  101. void *mmap;
  102. } VFIOMSIXInfo;
  103. typedef struct VFIODevice {
  104. PCIDevice pdev;
  105. int fd;
  106. VFIOINTx intx;
  107. unsigned int config_size;
  108. off_t config_offset; /* Offset of config space region within device fd */
  109. unsigned int rom_size;
  110. off_t rom_offset; /* Offset of ROM region within device fd */
  111. int msi_cap_size;
  112. VFIOMSIVector *msi_vectors;
  113. VFIOMSIXInfo *msix;
  114. int nr_vectors; /* Number of MSI/MSIX vectors currently in use */
  115. int interrupt; /* Current interrupt type */
  116. VFIOBAR bars[PCI_NUM_REGIONS - 1]; /* No ROM */
  117. PCIHostDeviceAddress host;
  118. QLIST_ENTRY(VFIODevice) next;
  119. struct VFIOGroup *group;
  120. bool reset_works;
  121. } VFIODevice;
  122. typedef struct VFIOGroup {
  123. int fd;
  124. int groupid;
  125. VFIOContainer *container;
  126. QLIST_HEAD(, VFIODevice) device_list;
  127. QLIST_ENTRY(VFIOGroup) next;
  128. QLIST_ENTRY(VFIOGroup) container_next;
  129. } VFIOGroup;
  130. #define MSIX_CAP_LENGTH 12
  131. static QLIST_HEAD(, VFIOContainer)
  132. container_list = QLIST_HEAD_INITIALIZER(container_list);
  133. static QLIST_HEAD(, VFIOGroup)
  134. group_list = QLIST_HEAD_INITIALIZER(group_list);
  135. static void vfio_disable_interrupts(VFIODevice *vdev);
  136. static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len);
  137. static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled);
  138. /*
  139. * Common VFIO interrupt disable
  140. */
  141. static void vfio_disable_irqindex(VFIODevice *vdev, int index)
  142. {
  143. struct vfio_irq_set irq_set = {
  144. .argsz = sizeof(irq_set),
  145. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
  146. .index = index,
  147. .start = 0,
  148. .count = 0,
  149. };
  150. ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  151. }
  152. /*
  153. * INTx
  154. */
  155. static void vfio_unmask_intx(VFIODevice *vdev)
  156. {
  157. struct vfio_irq_set irq_set = {
  158. .argsz = sizeof(irq_set),
  159. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
  160. .index = VFIO_PCI_INTX_IRQ_INDEX,
  161. .start = 0,
  162. .count = 1,
  163. };
  164. ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  165. }
  166. #ifdef CONFIG_KVM /* Unused outside of CONFIG_KVM code */
  167. static void vfio_mask_intx(VFIODevice *vdev)
  168. {
  169. struct vfio_irq_set irq_set = {
  170. .argsz = sizeof(irq_set),
  171. .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
  172. .index = VFIO_PCI_INTX_IRQ_INDEX,
  173. .start = 0,
  174. .count = 1,
  175. };
  176. ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  177. }
  178. #endif
  179. /*
  180. * Disabling BAR mmaping can be slow, but toggling it around INTx can
  181. * also be a huge overhead. We try to get the best of both worlds by
  182. * waiting until an interrupt to disable mmaps (subsequent transitions
  183. * to the same state are effectively no overhead). If the interrupt has
  184. * been serviced and the time gap is long enough, we re-enable mmaps for
  185. * performance. This works well for things like graphics cards, which
  186. * may not use their interrupt at all and are penalized to an unusable
  187. * level by read/write BAR traps. Other devices, like NICs, have more
  188. * regular interrupts and see much better latency by staying in non-mmap
  189. * mode. We therefore set the default mmap_timeout such that a ping
  190. * is just enough to keep the mmap disabled. Users can experiment with
  191. * other options with the x-intx-mmap-timeout-ms parameter (a value of
  192. * zero disables the timer).
  193. */
  194. static void vfio_intx_mmap_enable(void *opaque)
  195. {
  196. VFIODevice *vdev = opaque;
  197. if (vdev->intx.pending) {
  198. qemu_mod_timer(vdev->intx.mmap_timer,
  199. qemu_get_clock_ms(vm_clock) + vdev->intx.mmap_timeout);
  200. return;
  201. }
  202. vfio_mmap_set_enabled(vdev, true);
  203. }
  204. static void vfio_intx_interrupt(void *opaque)
  205. {
  206. VFIODevice *vdev = opaque;
  207. if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
  208. return;
  209. }
  210. DPRINTF("%s(%04x:%02x:%02x.%x) Pin %c\n", __func__, vdev->host.domain,
  211. vdev->host.bus, vdev->host.slot, vdev->host.function,
  212. 'A' + vdev->intx.pin);
  213. vdev->intx.pending = true;
  214. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 1);
  215. vfio_mmap_set_enabled(vdev, false);
  216. if (vdev->intx.mmap_timeout) {
  217. qemu_mod_timer(vdev->intx.mmap_timer,
  218. qemu_get_clock_ms(vm_clock) + vdev->intx.mmap_timeout);
  219. }
  220. }
  221. static void vfio_eoi(VFIODevice *vdev)
  222. {
  223. if (!vdev->intx.pending) {
  224. return;
  225. }
  226. DPRINTF("%s(%04x:%02x:%02x.%x) EOI\n", __func__, vdev->host.domain,
  227. vdev->host.bus, vdev->host.slot, vdev->host.function);
  228. vdev->intx.pending = false;
  229. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
  230. vfio_unmask_intx(vdev);
  231. }
  232. static void vfio_enable_intx_kvm(VFIODevice *vdev)
  233. {
  234. #ifdef CONFIG_KVM
  235. struct kvm_irqfd irqfd = {
  236. .fd = event_notifier_get_fd(&vdev->intx.interrupt),
  237. .gsi = vdev->intx.route.irq,
  238. .flags = KVM_IRQFD_FLAG_RESAMPLE,
  239. };
  240. struct vfio_irq_set *irq_set;
  241. int ret, argsz;
  242. int32_t *pfd;
  243. if (!kvm_irqchip_in_kernel() ||
  244. vdev->intx.route.mode != PCI_INTX_ENABLED ||
  245. !kvm_check_extension(kvm_state, KVM_CAP_IRQFD_RESAMPLE)) {
  246. return;
  247. }
  248. /* Get to a known interrupt state */
  249. qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);
  250. vfio_mask_intx(vdev);
  251. vdev->intx.pending = false;
  252. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
  253. /* Get an eventfd for resample/unmask */
  254. if (event_notifier_init(&vdev->intx.unmask, 0)) {
  255. error_report("vfio: Error: event_notifier_init failed eoi\n");
  256. goto fail;
  257. }
  258. /* KVM triggers it, VFIO listens for it */
  259. irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);
  260. if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
  261. error_report("vfio: Error: Failed to setup resample irqfd: %m\n");
  262. goto fail_irqfd;
  263. }
  264. argsz = sizeof(*irq_set) + sizeof(*pfd);
  265. irq_set = g_malloc0(argsz);
  266. irq_set->argsz = argsz;
  267. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;
  268. irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
  269. irq_set->start = 0;
  270. irq_set->count = 1;
  271. pfd = (int32_t *)&irq_set->data;
  272. *pfd = irqfd.resamplefd;
  273. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  274. g_free(irq_set);
  275. if (ret) {
  276. error_report("vfio: Error: Failed to setup INTx unmask fd: %m\n");
  277. goto fail_vfio;
  278. }
  279. /* Let'em rip */
  280. vfio_unmask_intx(vdev);
  281. vdev->intx.kvm_accel = true;
  282. DPRINTF("%s(%04x:%02x:%02x.%x) KVM INTx accel enabled\n",
  283. __func__, vdev->host.domain, vdev->host.bus,
  284. vdev->host.slot, vdev->host.function);
  285. return;
  286. fail_vfio:
  287. irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;
  288. kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
  289. fail_irqfd:
  290. event_notifier_cleanup(&vdev->intx.unmask);
  291. fail:
  292. qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
  293. vfio_unmask_intx(vdev);
  294. #endif
  295. }
  296. static void vfio_disable_intx_kvm(VFIODevice *vdev)
  297. {
  298. #ifdef CONFIG_KVM
  299. struct kvm_irqfd irqfd = {
  300. .fd = event_notifier_get_fd(&vdev->intx.interrupt),
  301. .gsi = vdev->intx.route.irq,
  302. .flags = KVM_IRQFD_FLAG_DEASSIGN,
  303. };
  304. if (!vdev->intx.kvm_accel) {
  305. return;
  306. }
  307. /*
  308. * Get to a known state, hardware masked, QEMU ready to accept new
  309. * interrupts, QEMU IRQ de-asserted.
  310. */
  311. vfio_mask_intx(vdev);
  312. vdev->intx.pending = false;
  313. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
  314. /* Tell KVM to stop listening for an INTx irqfd */
  315. if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
  316. error_report("vfio: Error: Failed to disable INTx irqfd: %m\n");
  317. }
  318. /* We only need to close the eventfd for VFIO to cleanup the kernel side */
  319. event_notifier_cleanup(&vdev->intx.unmask);
  320. /* QEMU starts listening for interrupt events. */
  321. qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
  322. vdev->intx.kvm_accel = false;
  323. /* If we've missed an event, let it re-fire through QEMU */
  324. vfio_unmask_intx(vdev);
  325. DPRINTF("%s(%04x:%02x:%02x.%x) KVM INTx accel disabled\n",
  326. __func__, vdev->host.domain, vdev->host.bus,
  327. vdev->host.slot, vdev->host.function);
  328. #endif
  329. }
  330. static void vfio_update_irq(PCIDevice *pdev)
  331. {
  332. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  333. PCIINTxRoute route;
  334. if (vdev->interrupt != VFIO_INT_INTx) {
  335. return;
  336. }
  337. route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
  338. if (!pci_intx_route_changed(&vdev->intx.route, &route)) {
  339. return; /* Nothing changed */
  340. }
  341. DPRINTF("%s(%04x:%02x:%02x.%x) IRQ moved %d -> %d\n", __func__,
  342. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  343. vdev->host.function, vdev->intx.route.irq, route.irq);
  344. vfio_disable_intx_kvm(vdev);
  345. vdev->intx.route = route;
  346. if (route.mode != PCI_INTX_ENABLED) {
  347. return;
  348. }
  349. vfio_enable_intx_kvm(vdev);
  350. /* Re-enable the interrupt in cased we missed an EOI */
  351. vfio_eoi(vdev);
  352. }
  353. static int vfio_enable_intx(VFIODevice *vdev)
  354. {
  355. uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
  356. int ret, argsz;
  357. struct vfio_irq_set *irq_set;
  358. int32_t *pfd;
  359. if (!pin) {
  360. return 0;
  361. }
  362. vfio_disable_interrupts(vdev);
  363. vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
  364. #ifdef CONFIG_KVM
  365. /*
  366. * Only conditional to avoid generating error messages on platforms
  367. * where we won't actually use the result anyway.
  368. */
  369. if (kvm_check_extension(kvm_state, KVM_CAP_IRQFD_RESAMPLE)) {
  370. vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
  371. vdev->intx.pin);
  372. }
  373. #endif
  374. ret = event_notifier_init(&vdev->intx.interrupt, 0);
  375. if (ret) {
  376. error_report("vfio: Error: event_notifier_init failed\n");
  377. return ret;
  378. }
  379. argsz = sizeof(*irq_set) + sizeof(*pfd);
  380. irq_set = g_malloc0(argsz);
  381. irq_set->argsz = argsz;
  382. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
  383. irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
  384. irq_set->start = 0;
  385. irq_set->count = 1;
  386. pfd = (int32_t *)&irq_set->data;
  387. *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
  388. qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
  389. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  390. g_free(irq_set);
  391. if (ret) {
  392. error_report("vfio: Error: Failed to setup INTx fd: %m\n");
  393. qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
  394. event_notifier_cleanup(&vdev->intx.interrupt);
  395. return -errno;
  396. }
  397. vfio_enable_intx_kvm(vdev);
  398. vdev->interrupt = VFIO_INT_INTx;
  399. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  400. vdev->host.bus, vdev->host.slot, vdev->host.function);
  401. return 0;
  402. }
  403. static void vfio_disable_intx(VFIODevice *vdev)
  404. {
  405. int fd;
  406. qemu_del_timer(vdev->intx.mmap_timer);
  407. vfio_disable_intx_kvm(vdev);
  408. vfio_disable_irqindex(vdev, VFIO_PCI_INTX_IRQ_INDEX);
  409. vdev->intx.pending = false;
  410. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
  411. vfio_mmap_set_enabled(vdev, true);
  412. fd = event_notifier_get_fd(&vdev->intx.interrupt);
  413. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  414. event_notifier_cleanup(&vdev->intx.interrupt);
  415. vdev->interrupt = VFIO_INT_NONE;
  416. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  417. vdev->host.bus, vdev->host.slot, vdev->host.function);
  418. }
  419. /*
  420. * MSI/X
  421. */
  422. static void vfio_msi_interrupt(void *opaque)
  423. {
  424. VFIOMSIVector *vector = opaque;
  425. VFIODevice *vdev = vector->vdev;
  426. int nr = vector - vdev->msi_vectors;
  427. if (!event_notifier_test_and_clear(&vector->interrupt)) {
  428. return;
  429. }
  430. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d\n", __func__,
  431. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  432. vdev->host.function, nr);
  433. if (vdev->interrupt == VFIO_INT_MSIX) {
  434. msix_notify(&vdev->pdev, nr);
  435. } else if (vdev->interrupt == VFIO_INT_MSI) {
  436. msi_notify(&vdev->pdev, nr);
  437. } else {
  438. error_report("vfio: MSI interrupt receieved, but not enabled?\n");
  439. }
  440. }
  441. static int vfio_enable_vectors(VFIODevice *vdev, bool msix)
  442. {
  443. struct vfio_irq_set *irq_set;
  444. int ret = 0, i, argsz;
  445. int32_t *fds;
  446. argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
  447. irq_set = g_malloc0(argsz);
  448. irq_set->argsz = argsz;
  449. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
  450. irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
  451. irq_set->start = 0;
  452. irq_set->count = vdev->nr_vectors;
  453. fds = (int32_t *)&irq_set->data;
  454. for (i = 0; i < vdev->nr_vectors; i++) {
  455. if (!vdev->msi_vectors[i].use) {
  456. fds[i] = -1;
  457. continue;
  458. }
  459. fds[i] = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
  460. }
  461. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  462. g_free(irq_set);
  463. return ret;
  464. }
  465. static int vfio_msix_vector_use(PCIDevice *pdev,
  466. unsigned int nr, MSIMessage msg)
  467. {
  468. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  469. VFIOMSIVector *vector;
  470. int ret;
  471. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d used\n", __func__,
  472. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  473. vdev->host.function, nr);
  474. vector = &vdev->msi_vectors[nr];
  475. vector->vdev = vdev;
  476. vector->use = true;
  477. msix_vector_use(pdev, nr);
  478. if (event_notifier_init(&vector->interrupt, 0)) {
  479. error_report("vfio: Error: event_notifier_init failed\n");
  480. }
  481. /*
  482. * Attempt to enable route through KVM irqchip,
  483. * default to userspace handling if unavailable.
  484. */
  485. vector->virq = kvm_irqchip_add_msi_route(kvm_state, msg);
  486. if (vector->virq < 0 ||
  487. kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
  488. vector->virq) < 0) {
  489. if (vector->virq >= 0) {
  490. kvm_irqchip_release_virq(kvm_state, vector->virq);
  491. vector->virq = -1;
  492. }
  493. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  494. vfio_msi_interrupt, NULL, vector);
  495. }
  496. /*
  497. * We don't want to have the host allocate all possible MSI vectors
  498. * for a device if they're not in use, so we shutdown and incrementally
  499. * increase them as needed.
  500. */
  501. if (vdev->nr_vectors < nr + 1) {
  502. vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
  503. vdev->nr_vectors = nr + 1;
  504. ret = vfio_enable_vectors(vdev, true);
  505. if (ret) {
  506. error_report("vfio: failed to enable vectors, %d\n", ret);
  507. }
  508. } else {
  509. int argsz;
  510. struct vfio_irq_set *irq_set;
  511. int32_t *pfd;
  512. argsz = sizeof(*irq_set) + sizeof(*pfd);
  513. irq_set = g_malloc0(argsz);
  514. irq_set->argsz = argsz;
  515. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
  516. VFIO_IRQ_SET_ACTION_TRIGGER;
  517. irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
  518. irq_set->start = nr;
  519. irq_set->count = 1;
  520. pfd = (int32_t *)&irq_set->data;
  521. *pfd = event_notifier_get_fd(&vector->interrupt);
  522. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  523. g_free(irq_set);
  524. if (ret) {
  525. error_report("vfio: failed to modify vector, %d\n", ret);
  526. }
  527. }
  528. return 0;
  529. }
  530. static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
  531. {
  532. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  533. VFIOMSIVector *vector = &vdev->msi_vectors[nr];
  534. int argsz;
  535. struct vfio_irq_set *irq_set;
  536. int32_t *pfd;
  537. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d released\n", __func__,
  538. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  539. vdev->host.function, nr);
  540. /*
  541. * XXX What's the right thing to do here? This turns off the interrupt
  542. * completely, but do we really just want to switch the interrupt to
  543. * bouncing through userspace and let msix.c drop it? Not sure.
  544. */
  545. msix_vector_unuse(pdev, nr);
  546. argsz = sizeof(*irq_set) + sizeof(*pfd);
  547. irq_set = g_malloc0(argsz);
  548. irq_set->argsz = argsz;
  549. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
  550. VFIO_IRQ_SET_ACTION_TRIGGER;
  551. irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
  552. irq_set->start = nr;
  553. irq_set->count = 1;
  554. pfd = (int32_t *)&irq_set->data;
  555. *pfd = -1;
  556. ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  557. g_free(irq_set);
  558. if (vector->virq < 0) {
  559. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  560. NULL, NULL, NULL);
  561. } else {
  562. kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
  563. vector->virq);
  564. kvm_irqchip_release_virq(kvm_state, vector->virq);
  565. vector->virq = -1;
  566. }
  567. event_notifier_cleanup(&vector->interrupt);
  568. vector->use = false;
  569. }
  570. static void vfio_enable_msix(VFIODevice *vdev)
  571. {
  572. vfio_disable_interrupts(vdev);
  573. vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));
  574. vdev->interrupt = VFIO_INT_MSIX;
  575. if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
  576. vfio_msix_vector_release)) {
  577. error_report("vfio: msix_set_vector_notifiers failed\n");
  578. }
  579. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  580. vdev->host.bus, vdev->host.slot, vdev->host.function);
  581. }
  582. static void vfio_enable_msi(VFIODevice *vdev)
  583. {
  584. int ret, i;
  585. vfio_disable_interrupts(vdev);
  586. vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
  587. retry:
  588. vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
  589. for (i = 0; i < vdev->nr_vectors; i++) {
  590. MSIMessage msg;
  591. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  592. vector->vdev = vdev;
  593. vector->use = true;
  594. if (event_notifier_init(&vector->interrupt, 0)) {
  595. error_report("vfio: Error: event_notifier_init failed\n");
  596. }
  597. msg = msi_get_message(&vdev->pdev, i);
  598. /*
  599. * Attempt to enable route through KVM irqchip,
  600. * default to userspace handling if unavailable.
  601. */
  602. vector->virq = kvm_irqchip_add_msi_route(kvm_state, msg);
  603. if (vector->virq < 0 ||
  604. kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
  605. vector->virq) < 0) {
  606. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  607. vfio_msi_interrupt, NULL, vector);
  608. }
  609. }
  610. ret = vfio_enable_vectors(vdev, false);
  611. if (ret) {
  612. if (ret < 0) {
  613. error_report("vfio: Error: Failed to setup MSI fds: %m\n");
  614. } else if (ret != vdev->nr_vectors) {
  615. error_report("vfio: Error: Failed to enable %d "
  616. "MSI vectors, retry with %d\n", vdev->nr_vectors, ret);
  617. }
  618. for (i = 0; i < vdev->nr_vectors; i++) {
  619. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  620. if (vector->virq >= 0) {
  621. kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
  622. vector->virq);
  623. kvm_irqchip_release_virq(kvm_state, vector->virq);
  624. vector->virq = -1;
  625. } else {
  626. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  627. NULL, NULL, NULL);
  628. }
  629. event_notifier_cleanup(&vector->interrupt);
  630. }
  631. g_free(vdev->msi_vectors);
  632. if (ret > 0 && ret != vdev->nr_vectors) {
  633. vdev->nr_vectors = ret;
  634. goto retry;
  635. }
  636. vdev->nr_vectors = 0;
  637. return;
  638. }
  639. vdev->interrupt = VFIO_INT_MSI;
  640. DPRINTF("%s(%04x:%02x:%02x.%x) Enabled %d MSI vectors\n", __func__,
  641. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  642. vdev->host.function, vdev->nr_vectors);
  643. }
  644. static void vfio_disable_msi_common(VFIODevice *vdev)
  645. {
  646. g_free(vdev->msi_vectors);
  647. vdev->msi_vectors = NULL;
  648. vdev->nr_vectors = 0;
  649. vdev->interrupt = VFIO_INT_NONE;
  650. vfio_enable_intx(vdev);
  651. }
  652. static void vfio_disable_msix(VFIODevice *vdev)
  653. {
  654. msix_unset_vector_notifiers(&vdev->pdev);
  655. if (vdev->nr_vectors) {
  656. vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
  657. }
  658. vfio_disable_msi_common(vdev);
  659. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  660. vdev->host.bus, vdev->host.slot, vdev->host.function);
  661. }
  662. static void vfio_disable_msi(VFIODevice *vdev)
  663. {
  664. int i;
  665. vfio_disable_irqindex(vdev, VFIO_PCI_MSI_IRQ_INDEX);
  666. for (i = 0; i < vdev->nr_vectors; i++) {
  667. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  668. if (!vector->use) {
  669. continue;
  670. }
  671. if (vector->virq >= 0) {
  672. kvm_irqchip_remove_irqfd_notifier(kvm_state,
  673. &vector->interrupt, vector->virq);
  674. kvm_irqchip_release_virq(kvm_state, vector->virq);
  675. vector->virq = -1;
  676. } else {
  677. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  678. NULL, NULL, NULL);
  679. }
  680. event_notifier_cleanup(&vector->interrupt);
  681. }
  682. vfio_disable_msi_common(vdev);
  683. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  684. vdev->host.bus, vdev->host.slot, vdev->host.function);
  685. }
  686. /*
  687. * IO Port/MMIO - Beware of the endians, VFIO is always little endian
  688. */
  689. static void vfio_bar_write(void *opaque, hwaddr addr,
  690. uint64_t data, unsigned size)
  691. {
  692. VFIOBAR *bar = opaque;
  693. union {
  694. uint8_t byte;
  695. uint16_t word;
  696. uint32_t dword;
  697. uint64_t qword;
  698. } buf;
  699. switch (size) {
  700. case 1:
  701. buf.byte = data;
  702. break;
  703. case 2:
  704. buf.word = cpu_to_le16(data);
  705. break;
  706. case 4:
  707. buf.dword = cpu_to_le32(data);
  708. break;
  709. default:
  710. hw_error("vfio: unsupported write size, %d bytes\n", size);
  711. break;
  712. }
  713. if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
  714. error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m\n",
  715. __func__, addr, data, size);
  716. }
  717. DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", 0x%"PRIx64", %d)\n",
  718. __func__, bar->nr, addr, data, size);
  719. /*
  720. * A read or write to a BAR always signals an INTx EOI. This will
  721. * do nothing if not pending (including not in INTx mode). We assume
  722. * that a BAR access is in response to an interrupt and that BAR
  723. * accesses will service the interrupt. Unfortunately, we don't know
  724. * which access will service the interrupt, so we're potentially
  725. * getting quite a few host interrupts per guest interrupt.
  726. */
  727. vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
  728. }
  729. static uint64_t vfio_bar_read(void *opaque,
  730. hwaddr addr, unsigned size)
  731. {
  732. VFIOBAR *bar = opaque;
  733. union {
  734. uint8_t byte;
  735. uint16_t word;
  736. uint32_t dword;
  737. uint64_t qword;
  738. } buf;
  739. uint64_t data = 0;
  740. if (pread(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
  741. error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m\n",
  742. __func__, addr, size);
  743. return (uint64_t)-1;
  744. }
  745. switch (size) {
  746. case 1:
  747. data = buf.byte;
  748. break;
  749. case 2:
  750. data = le16_to_cpu(buf.word);
  751. break;
  752. case 4:
  753. data = le32_to_cpu(buf.dword);
  754. break;
  755. default:
  756. hw_error("vfio: unsupported read size, %d bytes\n", size);
  757. break;
  758. }
  759. DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", %d) = 0x%"PRIx64"\n",
  760. __func__, bar->nr, addr, size, data);
  761. /* Same as write above */
  762. vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
  763. return data;
  764. }
  765. static const MemoryRegionOps vfio_bar_ops = {
  766. .read = vfio_bar_read,
  767. .write = vfio_bar_write,
  768. .endianness = DEVICE_LITTLE_ENDIAN,
  769. };
  770. /*
  771. * PCI config space
  772. */
  773. static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
  774. {
  775. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  776. uint32_t val = 0;
  777. /*
  778. * We only need QEMU PCI config support for the ROM BAR, the MSI and MSIX
  779. * capabilities, and the multifunction bit below. We let VFIO handle
  780. * virtualizing everything else. Performance is not a concern here.
  781. */
  782. if (ranges_overlap(addr, len, PCI_ROM_ADDRESS, 4) ||
  783. (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
  784. ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) ||
  785. (pdev->cap_present & QEMU_PCI_CAP_MSI &&
  786. ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size))) {
  787. val = pci_default_read_config(pdev, addr, len);
  788. } else {
  789. if (pread(vdev->fd, &val, len, vdev->config_offset + addr) != len) {
  790. error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m\n",
  791. __func__, vdev->host.domain, vdev->host.bus,
  792. vdev->host.slot, vdev->host.function, addr, len);
  793. return -errno;
  794. }
  795. val = le32_to_cpu(val);
  796. }
  797. /* Multifunction bit is virualized in QEMU */
  798. if (unlikely(ranges_overlap(addr, len, PCI_HEADER_TYPE, 1))) {
  799. uint32_t mask = PCI_HEADER_TYPE_MULTI_FUNCTION;
  800. if (len == 4) {
  801. mask <<= 16;
  802. }
  803. if (pdev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
  804. val |= mask;
  805. } else {
  806. val &= ~mask;
  807. }
  808. }
  809. DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, len=0x%x) %x\n", __func__,
  810. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  811. vdev->host.function, addr, len, val);
  812. return val;
  813. }
  814. static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
  815. uint32_t val, int len)
  816. {
  817. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  818. uint32_t val_le = cpu_to_le32(val);
  819. DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,
  820. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  821. vdev->host.function, addr, val, len);
  822. /* Write everything to VFIO, let it filter out what we can't write */
  823. if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {
  824. error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m\n",
  825. __func__, vdev->host.domain, vdev->host.bus,
  826. vdev->host.slot, vdev->host.function, addr, val, len);
  827. }
  828. /* Write standard header bits to emulation */
  829. if (addr < PCI_CONFIG_HEADER_SIZE) {
  830. pci_default_write_config(pdev, addr, val, len);
  831. return;
  832. }
  833. /* MSI/MSI-X Enabling/Disabling */
  834. if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
  835. ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
  836. int is_enabled, was_enabled = msi_enabled(pdev);
  837. pci_default_write_config(pdev, addr, val, len);
  838. is_enabled = msi_enabled(pdev);
  839. if (!was_enabled && is_enabled) {
  840. vfio_enable_msi(vdev);
  841. } else if (was_enabled && !is_enabled) {
  842. vfio_disable_msi(vdev);
  843. }
  844. }
  845. if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
  846. ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
  847. int is_enabled, was_enabled = msix_enabled(pdev);
  848. pci_default_write_config(pdev, addr, val, len);
  849. is_enabled = msix_enabled(pdev);
  850. if (!was_enabled && is_enabled) {
  851. vfio_enable_msix(vdev);
  852. } else if (was_enabled && !is_enabled) {
  853. vfio_disable_msix(vdev);
  854. }
  855. }
  856. }
  857. /*
  858. * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
  859. */
  860. static int vfio_dma_unmap(VFIOContainer *container,
  861. hwaddr iova, ram_addr_t size)
  862. {
  863. struct vfio_iommu_type1_dma_unmap unmap = {
  864. .argsz = sizeof(unmap),
  865. .flags = 0,
  866. .iova = iova,
  867. .size = size,
  868. };
  869. if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
  870. DPRINTF("VFIO_UNMAP_DMA: %d\n", -errno);
  871. return -errno;
  872. }
  873. return 0;
  874. }
  875. static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
  876. ram_addr_t size, void *vaddr, bool readonly)
  877. {
  878. struct vfio_iommu_type1_dma_map map = {
  879. .argsz = sizeof(map),
  880. .flags = VFIO_DMA_MAP_FLAG_READ,
  881. .vaddr = (__u64)(uintptr_t)vaddr,
  882. .iova = iova,
  883. .size = size,
  884. };
  885. if (!readonly) {
  886. map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
  887. }
  888. /*
  889. * Try the mapping, if it fails with EBUSY, unmap the region and try
  890. * again. This shouldn't be necessary, but we sometimes see it in
  891. * the the VGA ROM space.
  892. */
  893. if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
  894. (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
  895. ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
  896. return 0;
  897. }
  898. DPRINTF("VFIO_MAP_DMA: %d\n", -errno);
  899. return -errno;
  900. }
  901. static bool vfio_listener_skipped_section(MemoryRegionSection *section)
  902. {
  903. return !memory_region_is_ram(section->mr);
  904. }
  905. static void vfio_listener_region_add(MemoryListener *listener,
  906. MemoryRegionSection *section)
  907. {
  908. VFIOContainer *container = container_of(listener, VFIOContainer,
  909. iommu_data.listener);
  910. hwaddr iova, end;
  911. void *vaddr;
  912. int ret;
  913. if (vfio_listener_skipped_section(section)) {
  914. DPRINTF("vfio: SKIPPING region_add %"HWADDR_PRIx" - %"PRIx64"\n",
  915. section->offset_within_address_space,
  916. section->offset_within_address_space + section->size - 1);
  917. return;
  918. }
  919. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  920. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  921. error_report("%s received unaligned region\n", __func__);
  922. return;
  923. }
  924. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  925. end = (section->offset_within_address_space + section->size) &
  926. TARGET_PAGE_MASK;
  927. if (iova >= end) {
  928. return;
  929. }
  930. vaddr = memory_region_get_ram_ptr(section->mr) +
  931. section->offset_within_region +
  932. (iova - section->offset_within_address_space);
  933. DPRINTF("vfio: region_add %"HWADDR_PRIx" - %"HWADDR_PRIx" [%p]\n",
  934. iova, end - 1, vaddr);
  935. ret = vfio_dma_map(container, iova, end - iova, vaddr, section->readonly);
  936. if (ret) {
  937. error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
  938. "0x%"HWADDR_PRIx", %p) = %d (%m)\n",
  939. container, iova, end - iova, vaddr, ret);
  940. }
  941. }
  942. static void vfio_listener_region_del(MemoryListener *listener,
  943. MemoryRegionSection *section)
  944. {
  945. VFIOContainer *container = container_of(listener, VFIOContainer,
  946. iommu_data.listener);
  947. hwaddr iova, end;
  948. int ret;
  949. if (vfio_listener_skipped_section(section)) {
  950. DPRINTF("vfio: SKIPPING region_del %"HWADDR_PRIx" - %"PRIx64"\n",
  951. section->offset_within_address_space,
  952. section->offset_within_address_space + section->size - 1);
  953. return;
  954. }
  955. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  956. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  957. error_report("%s received unaligned region\n", __func__);
  958. return;
  959. }
  960. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  961. end = (section->offset_within_address_space + section->size) &
  962. TARGET_PAGE_MASK;
  963. if (iova >= end) {
  964. return;
  965. }
  966. DPRINTF("vfio: region_del %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
  967. iova, end - 1);
  968. ret = vfio_dma_unmap(container, iova, end - iova);
  969. if (ret) {
  970. error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
  971. "0x%"HWADDR_PRIx") = %d (%m)\n",
  972. container, iova, end - iova, ret);
  973. }
  974. }
  975. static MemoryListener vfio_memory_listener = {
  976. .region_add = vfio_listener_region_add,
  977. .region_del = vfio_listener_region_del,
  978. };
  979. static void vfio_listener_release(VFIOContainer *container)
  980. {
  981. memory_listener_unregister(&container->iommu_data.listener);
  982. }
  983. /*
  984. * Interrupt setup
  985. */
  986. static void vfio_disable_interrupts(VFIODevice *vdev)
  987. {
  988. switch (vdev->interrupt) {
  989. case VFIO_INT_INTx:
  990. vfio_disable_intx(vdev);
  991. break;
  992. case VFIO_INT_MSI:
  993. vfio_disable_msi(vdev);
  994. break;
  995. case VFIO_INT_MSIX:
  996. vfio_disable_msix(vdev);
  997. break;
  998. }
  999. }
  1000. static int vfio_setup_msi(VFIODevice *vdev, int pos)
  1001. {
  1002. uint16_t ctrl;
  1003. bool msi_64bit, msi_maskbit;
  1004. int ret, entries;
  1005. if (pread(vdev->fd, &ctrl, sizeof(ctrl),
  1006. vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
  1007. return -errno;
  1008. }
  1009. ctrl = le16_to_cpu(ctrl);
  1010. msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
  1011. msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
  1012. entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
  1013. DPRINTF("%04x:%02x:%02x.%x PCI MSI CAP @0x%x\n", vdev->host.domain,
  1014. vdev->host.bus, vdev->host.slot, vdev->host.function, pos);
  1015. ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
  1016. if (ret < 0) {
  1017. if (ret == -ENOTSUP) {
  1018. return 0;
  1019. }
  1020. error_report("vfio: msi_init failed\n");
  1021. return ret;
  1022. }
  1023. vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
  1024. return 0;
  1025. }
  1026. /*
  1027. * We don't have any control over how pci_add_capability() inserts
  1028. * capabilities into the chain. In order to setup MSI-X we need a
  1029. * MemoryRegion for the BAR. In order to setup the BAR and not
  1030. * attempt to mmap the MSI-X table area, which VFIO won't allow, we
  1031. * need to first look for where the MSI-X table lives. So we
  1032. * unfortunately split MSI-X setup across two functions.
  1033. */
  1034. static int vfio_early_setup_msix(VFIODevice *vdev)
  1035. {
  1036. uint8_t pos;
  1037. uint16_t ctrl;
  1038. uint32_t table, pba;
  1039. pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
  1040. if (!pos) {
  1041. return 0;
  1042. }
  1043. if (pread(vdev->fd, &ctrl, sizeof(ctrl),
  1044. vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
  1045. return -errno;
  1046. }
  1047. if (pread(vdev->fd, &table, sizeof(table),
  1048. vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
  1049. return -errno;
  1050. }
  1051. if (pread(vdev->fd, &pba, sizeof(pba),
  1052. vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
  1053. return -errno;
  1054. }
  1055. ctrl = le16_to_cpu(ctrl);
  1056. table = le32_to_cpu(table);
  1057. pba = le32_to_cpu(pba);
  1058. vdev->msix = g_malloc0(sizeof(*(vdev->msix)));
  1059. vdev->msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
  1060. vdev->msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
  1061. vdev->msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
  1062. vdev->msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
  1063. vdev->msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
  1064. DPRINTF("%04x:%02x:%02x.%x "
  1065. "PCI MSI-X CAP @0x%x, BAR %d, offset 0x%x, entries %d\n",
  1066. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1067. vdev->host.function, pos, vdev->msix->table_bar,
  1068. vdev->msix->table_offset, vdev->msix->entries);
  1069. return 0;
  1070. }
  1071. static int vfio_setup_msix(VFIODevice *vdev, int pos)
  1072. {
  1073. int ret;
  1074. ret = msix_init(&vdev->pdev, vdev->msix->entries,
  1075. &vdev->bars[vdev->msix->table_bar].mem,
  1076. vdev->msix->table_bar, vdev->msix->table_offset,
  1077. &vdev->bars[vdev->msix->pba_bar].mem,
  1078. vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
  1079. if (ret < 0) {
  1080. if (ret == -ENOTSUP) {
  1081. return 0;
  1082. }
  1083. error_report("vfio: msix_init failed\n");
  1084. return ret;
  1085. }
  1086. return 0;
  1087. }
  1088. static void vfio_teardown_msi(VFIODevice *vdev)
  1089. {
  1090. msi_uninit(&vdev->pdev);
  1091. if (vdev->msix) {
  1092. msix_uninit(&vdev->pdev, &vdev->bars[vdev->msix->table_bar].mem,
  1093. &vdev->bars[vdev->msix->pba_bar].mem);
  1094. }
  1095. }
  1096. /*
  1097. * Resource setup
  1098. */
  1099. static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled)
  1100. {
  1101. int i;
  1102. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1103. VFIOBAR *bar = &vdev->bars[i];
  1104. if (!bar->size) {
  1105. continue;
  1106. }
  1107. memory_region_set_enabled(&bar->mmap_mem, enabled);
  1108. if (vdev->msix && vdev->msix->table_bar == i) {
  1109. memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
  1110. }
  1111. }
  1112. }
  1113. static void vfio_unmap_bar(VFIODevice *vdev, int nr)
  1114. {
  1115. VFIOBAR *bar = &vdev->bars[nr];
  1116. if (!bar->size) {
  1117. return;
  1118. }
  1119. memory_region_del_subregion(&bar->mem, &bar->mmap_mem);
  1120. munmap(bar->mmap, memory_region_size(&bar->mmap_mem));
  1121. if (vdev->msix && vdev->msix->table_bar == nr) {
  1122. memory_region_del_subregion(&bar->mem, &vdev->msix->mmap_mem);
  1123. munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
  1124. }
  1125. memory_region_destroy(&bar->mem);
  1126. }
  1127. static int vfio_mmap_bar(VFIOBAR *bar, MemoryRegion *mem, MemoryRegion *submem,
  1128. void **map, size_t size, off_t offset,
  1129. const char *name)
  1130. {
  1131. int ret = 0;
  1132. if (size && bar->flags & VFIO_REGION_INFO_FLAG_MMAP) {
  1133. int prot = 0;
  1134. if (bar->flags & VFIO_REGION_INFO_FLAG_READ) {
  1135. prot |= PROT_READ;
  1136. }
  1137. if (bar->flags & VFIO_REGION_INFO_FLAG_WRITE) {
  1138. prot |= PROT_WRITE;
  1139. }
  1140. *map = mmap(NULL, size, prot, MAP_SHARED,
  1141. bar->fd, bar->fd_offset + offset);
  1142. if (*map == MAP_FAILED) {
  1143. *map = NULL;
  1144. ret = -errno;
  1145. goto empty_region;
  1146. }
  1147. memory_region_init_ram_ptr(submem, name, size, *map);
  1148. } else {
  1149. empty_region:
  1150. /* Create a zero sized sub-region to make cleanup easy. */
  1151. memory_region_init(submem, name, 0);
  1152. }
  1153. memory_region_add_subregion(mem, offset, submem);
  1154. return ret;
  1155. }
  1156. static void vfio_map_bar(VFIODevice *vdev, int nr)
  1157. {
  1158. VFIOBAR *bar = &vdev->bars[nr];
  1159. unsigned size = bar->size;
  1160. char name[64];
  1161. uint32_t pci_bar;
  1162. uint8_t type;
  1163. int ret;
  1164. /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
  1165. if (!size) {
  1166. return;
  1167. }
  1168. snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
  1169. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1170. vdev->host.function, nr);
  1171. /* Determine what type of BAR this is for registration */
  1172. ret = pread(vdev->fd, &pci_bar, sizeof(pci_bar),
  1173. vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
  1174. if (ret != sizeof(pci_bar)) {
  1175. error_report("vfio: Failed to read BAR %d (%m)\n", nr);
  1176. return;
  1177. }
  1178. pci_bar = le32_to_cpu(pci_bar);
  1179. type = pci_bar & (pci_bar & PCI_BASE_ADDRESS_SPACE_IO ?
  1180. ~PCI_BASE_ADDRESS_IO_MASK : ~PCI_BASE_ADDRESS_MEM_MASK);
  1181. /* A "slow" read/write mapping underlies all BARs */
  1182. memory_region_init_io(&bar->mem, &vfio_bar_ops, bar, name, size);
  1183. pci_register_bar(&vdev->pdev, nr, type, &bar->mem);
  1184. /*
  1185. * We can't mmap areas overlapping the MSIX vector table, so we
  1186. * potentially insert a direct-mapped subregion before and after it.
  1187. */
  1188. if (vdev->msix && vdev->msix->table_bar == nr) {
  1189. size = vdev->msix->table_offset & TARGET_PAGE_MASK;
  1190. }
  1191. strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
  1192. if (vfio_mmap_bar(bar, &bar->mem,
  1193. &bar->mmap_mem, &bar->mmap, size, 0, name)) {
  1194. error_report("%s unsupported. Performance may be slow\n", name);
  1195. }
  1196. if (vdev->msix && vdev->msix->table_bar == nr) {
  1197. unsigned start;
  1198. start = TARGET_PAGE_ALIGN(vdev->msix->table_offset +
  1199. (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
  1200. size = start < bar->size ? bar->size - start : 0;
  1201. strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
  1202. /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
  1203. if (vfio_mmap_bar(bar, &bar->mem, &vdev->msix->mmap_mem,
  1204. &vdev->msix->mmap, size, start, name)) {
  1205. error_report("%s unsupported. Performance may be slow\n", name);
  1206. }
  1207. }
  1208. }
  1209. static void vfio_map_bars(VFIODevice *vdev)
  1210. {
  1211. int i;
  1212. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1213. vfio_map_bar(vdev, i);
  1214. }
  1215. }
  1216. static void vfio_unmap_bars(VFIODevice *vdev)
  1217. {
  1218. int i;
  1219. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1220. vfio_unmap_bar(vdev, i);
  1221. }
  1222. }
  1223. /*
  1224. * General setup
  1225. */
  1226. static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
  1227. {
  1228. uint8_t tmp, next = 0xff;
  1229. for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
  1230. tmp = pdev->config[tmp + 1]) {
  1231. if (tmp > pos && tmp < next) {
  1232. next = tmp;
  1233. }
  1234. }
  1235. return next - pos;
  1236. }
  1237. static int vfio_add_std_cap(VFIODevice *vdev, uint8_t pos)
  1238. {
  1239. PCIDevice *pdev = &vdev->pdev;
  1240. uint8_t cap_id, next, size;
  1241. int ret;
  1242. cap_id = pdev->config[pos];
  1243. next = pdev->config[pos + 1];
  1244. /*
  1245. * If it becomes important to configure capabilities to their actual
  1246. * size, use this as the default when it's something we don't recognize.
  1247. * Since QEMU doesn't actually handle many of the config accesses,
  1248. * exact size doesn't seem worthwhile.
  1249. */
  1250. size = vfio_std_cap_max_size(pdev, pos);
  1251. /*
  1252. * pci_add_capability always inserts the new capability at the head
  1253. * of the chain. Therefore to end up with a chain that matches the
  1254. * physical device, we insert from the end by making this recursive.
  1255. * This is also why we pre-caclulate size above as cached config space
  1256. * will be changed as we unwind the stack.
  1257. */
  1258. if (next) {
  1259. ret = vfio_add_std_cap(vdev, next);
  1260. if (ret) {
  1261. return ret;
  1262. }
  1263. } else {
  1264. pdev->config[PCI_CAPABILITY_LIST] = 0; /* Begin the rebuild */
  1265. }
  1266. switch (cap_id) {
  1267. case PCI_CAP_ID_MSI:
  1268. ret = vfio_setup_msi(vdev, pos);
  1269. break;
  1270. case PCI_CAP_ID_MSIX:
  1271. ret = vfio_setup_msix(vdev, pos);
  1272. break;
  1273. default:
  1274. ret = pci_add_capability(pdev, cap_id, pos, size);
  1275. break;
  1276. }
  1277. if (ret < 0) {
  1278. error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
  1279. "0x%x[0x%x]@0x%x: %d\n", vdev->host.domain,
  1280. vdev->host.bus, vdev->host.slot, vdev->host.function,
  1281. cap_id, size, pos, ret);
  1282. return ret;
  1283. }
  1284. return 0;
  1285. }
  1286. static int vfio_add_capabilities(VFIODevice *vdev)
  1287. {
  1288. PCIDevice *pdev = &vdev->pdev;
  1289. if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
  1290. !pdev->config[PCI_CAPABILITY_LIST]) {
  1291. return 0; /* Nothing to add */
  1292. }
  1293. return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
  1294. }
  1295. static int vfio_load_rom(VFIODevice *vdev)
  1296. {
  1297. uint64_t size = vdev->rom_size;
  1298. char name[32];
  1299. off_t off = 0, voff = vdev->rom_offset;
  1300. ssize_t bytes;
  1301. void *ptr;
  1302. /* If loading ROM from file, pci handles it */
  1303. if (vdev->pdev.romfile || !vdev->pdev.rom_bar || !size) {
  1304. return 0;
  1305. }
  1306. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  1307. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1308. snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
  1309. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1310. vdev->host.function);
  1311. memory_region_init_ram(&vdev->pdev.rom, name, size);
  1312. ptr = memory_region_get_ram_ptr(&vdev->pdev.rom);
  1313. memset(ptr, 0xff, size);
  1314. while (size) {
  1315. bytes = pread(vdev->fd, ptr + off, size, voff + off);
  1316. if (bytes == 0) {
  1317. break; /* expect that we could get back less than the ROM BAR */
  1318. } else if (bytes > 0) {
  1319. off += bytes;
  1320. size -= bytes;
  1321. } else {
  1322. if (errno == EINTR || errno == EAGAIN) {
  1323. continue;
  1324. }
  1325. error_report("vfio: Error reading device ROM: %m\n");
  1326. memory_region_destroy(&vdev->pdev.rom);
  1327. return -errno;
  1328. }
  1329. }
  1330. pci_register_bar(&vdev->pdev, PCI_ROM_SLOT, 0, &vdev->pdev.rom);
  1331. vdev->pdev.has_rom = true;
  1332. return 0;
  1333. }
  1334. static int vfio_connect_container(VFIOGroup *group)
  1335. {
  1336. VFIOContainer *container;
  1337. int ret, fd;
  1338. if (group->container) {
  1339. return 0;
  1340. }
  1341. QLIST_FOREACH(container, &container_list, next) {
  1342. if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
  1343. group->container = container;
  1344. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1345. return 0;
  1346. }
  1347. }
  1348. fd = qemu_open("/dev/vfio/vfio", O_RDWR);
  1349. if (fd < 0) {
  1350. error_report("vfio: failed to open /dev/vfio/vfio: %m\n");
  1351. return -errno;
  1352. }
  1353. ret = ioctl(fd, VFIO_GET_API_VERSION);
  1354. if (ret != VFIO_API_VERSION) {
  1355. error_report("vfio: supported vfio version: %d, "
  1356. "reported version: %d\n", VFIO_API_VERSION, ret);
  1357. close(fd);
  1358. return -EINVAL;
  1359. }
  1360. container = g_malloc0(sizeof(*container));
  1361. container->fd = fd;
  1362. if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
  1363. ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
  1364. if (ret) {
  1365. error_report("vfio: failed to set group container: %m\n");
  1366. g_free(container);
  1367. close(fd);
  1368. return -errno;
  1369. }
  1370. ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
  1371. if (ret) {
  1372. error_report("vfio: failed to set iommu for container: %m\n");
  1373. g_free(container);
  1374. close(fd);
  1375. return -errno;
  1376. }
  1377. container->iommu_data.listener = vfio_memory_listener;
  1378. container->iommu_data.release = vfio_listener_release;
  1379. memory_listener_register(&container->iommu_data.listener, &address_space_memory);
  1380. } else {
  1381. error_report("vfio: No available IOMMU models\n");
  1382. g_free(container);
  1383. close(fd);
  1384. return -EINVAL;
  1385. }
  1386. QLIST_INIT(&container->group_list);
  1387. QLIST_INSERT_HEAD(&container_list, container, next);
  1388. group->container = container;
  1389. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1390. return 0;
  1391. }
  1392. static void vfio_disconnect_container(VFIOGroup *group)
  1393. {
  1394. VFIOContainer *container = group->container;
  1395. if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
  1396. error_report("vfio: error disconnecting group %d from container\n",
  1397. group->groupid);
  1398. }
  1399. QLIST_REMOVE(group, container_next);
  1400. group->container = NULL;
  1401. if (QLIST_EMPTY(&container->group_list)) {
  1402. if (container->iommu_data.release) {
  1403. container->iommu_data.release(container);
  1404. }
  1405. QLIST_REMOVE(container, next);
  1406. DPRINTF("vfio_disconnect_container: close container->fd\n");
  1407. close(container->fd);
  1408. g_free(container);
  1409. }
  1410. }
  1411. static VFIOGroup *vfio_get_group(int groupid)
  1412. {
  1413. VFIOGroup *group;
  1414. char path[32];
  1415. struct vfio_group_status status = { .argsz = sizeof(status) };
  1416. QLIST_FOREACH(group, &group_list, next) {
  1417. if (group->groupid == groupid) {
  1418. return group;
  1419. }
  1420. }
  1421. group = g_malloc0(sizeof(*group));
  1422. snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
  1423. group->fd = qemu_open(path, O_RDWR);
  1424. if (group->fd < 0) {
  1425. error_report("vfio: error opening %s: %m\n", path);
  1426. g_free(group);
  1427. return NULL;
  1428. }
  1429. if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
  1430. error_report("vfio: error getting group status: %m\n");
  1431. close(group->fd);
  1432. g_free(group);
  1433. return NULL;
  1434. }
  1435. if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
  1436. error_report("vfio: error, group %d is not viable, please ensure "
  1437. "all devices within the iommu_group are bound to their "
  1438. "vfio bus driver.\n", groupid);
  1439. close(group->fd);
  1440. g_free(group);
  1441. return NULL;
  1442. }
  1443. group->groupid = groupid;
  1444. QLIST_INIT(&group->device_list);
  1445. if (vfio_connect_container(group)) {
  1446. error_report("vfio: failed to setup container for group %d\n", groupid);
  1447. close(group->fd);
  1448. g_free(group);
  1449. return NULL;
  1450. }
  1451. QLIST_INSERT_HEAD(&group_list, group, next);
  1452. return group;
  1453. }
  1454. static void vfio_put_group(VFIOGroup *group)
  1455. {
  1456. if (!QLIST_EMPTY(&group->device_list)) {
  1457. return;
  1458. }
  1459. vfio_disconnect_container(group);
  1460. QLIST_REMOVE(group, next);
  1461. DPRINTF("vfio_put_group: close group->fd\n");
  1462. close(group->fd);
  1463. g_free(group);
  1464. }
  1465. static int vfio_get_device(VFIOGroup *group, const char *name, VFIODevice *vdev)
  1466. {
  1467. struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
  1468. struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
  1469. int ret, i;
  1470. ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
  1471. if (ret < 0) {
  1472. error_report("vfio: error getting device %s from group %d: %m\n",
  1473. name, group->groupid);
  1474. error_report("Verify all devices in group %d are bound to vfio-pci "
  1475. "or pci-stub and not already in use\n", group->groupid);
  1476. return ret;
  1477. }
  1478. vdev->fd = ret;
  1479. vdev->group = group;
  1480. QLIST_INSERT_HEAD(&group->device_list, vdev, next);
  1481. /* Sanity check device */
  1482. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_INFO, &dev_info);
  1483. if (ret) {
  1484. error_report("vfio: error getting device info: %m\n");
  1485. goto error;
  1486. }
  1487. DPRINTF("Device %s flags: %u, regions: %u, irgs: %u\n", name,
  1488. dev_info.flags, dev_info.num_regions, dev_info.num_irqs);
  1489. if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {
  1490. error_report("vfio: Um, this isn't a PCI device\n");
  1491. goto error;
  1492. }
  1493. vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
  1494. if (!vdev->reset_works) {
  1495. error_report("Warning, device %s does not support reset\n", name);
  1496. }
  1497. if (dev_info.num_regions != VFIO_PCI_NUM_REGIONS) {
  1498. error_report("vfio: unexpected number of io regions %u\n",
  1499. dev_info.num_regions);
  1500. goto error;
  1501. }
  1502. if (dev_info.num_irqs != VFIO_PCI_NUM_IRQS) {
  1503. error_report("vfio: unexpected number of irqs %u\n", dev_info.num_irqs);
  1504. goto error;
  1505. }
  1506. for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
  1507. reg_info.index = i;
  1508. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1509. if (ret) {
  1510. error_report("vfio: Error getting region %d info: %m\n", i);
  1511. goto error;
  1512. }
  1513. DPRINTF("Device %s region %d:\n", name, i);
  1514. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1515. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1516. (unsigned long)reg_info.flags);
  1517. vdev->bars[i].flags = reg_info.flags;
  1518. vdev->bars[i].size = reg_info.size;
  1519. vdev->bars[i].fd_offset = reg_info.offset;
  1520. vdev->bars[i].fd = vdev->fd;
  1521. vdev->bars[i].nr = i;
  1522. }
  1523. reg_info.index = VFIO_PCI_ROM_REGION_INDEX;
  1524. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1525. if (ret) {
  1526. error_report("vfio: Error getting ROM info: %m\n");
  1527. goto error;
  1528. }
  1529. DPRINTF("Device %s ROM:\n", name);
  1530. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1531. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1532. (unsigned long)reg_info.flags);
  1533. vdev->rom_size = reg_info.size;
  1534. vdev->rom_offset = reg_info.offset;
  1535. reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
  1536. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1537. if (ret) {
  1538. error_report("vfio: Error getting config info: %m\n");
  1539. goto error;
  1540. }
  1541. DPRINTF("Device %s config:\n", name);
  1542. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1543. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1544. (unsigned long)reg_info.flags);
  1545. vdev->config_size = reg_info.size;
  1546. vdev->config_offset = reg_info.offset;
  1547. error:
  1548. if (ret) {
  1549. QLIST_REMOVE(vdev, next);
  1550. vdev->group = NULL;
  1551. close(vdev->fd);
  1552. }
  1553. return ret;
  1554. }
  1555. static void vfio_put_device(VFIODevice *vdev)
  1556. {
  1557. QLIST_REMOVE(vdev, next);
  1558. vdev->group = NULL;
  1559. DPRINTF("vfio_put_device: close vdev->fd\n");
  1560. close(vdev->fd);
  1561. if (vdev->msix) {
  1562. g_free(vdev->msix);
  1563. vdev->msix = NULL;
  1564. }
  1565. }
  1566. static int vfio_initfn(PCIDevice *pdev)
  1567. {
  1568. VFIODevice *pvdev, *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1569. VFIOGroup *group;
  1570. char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
  1571. ssize_t len;
  1572. struct stat st;
  1573. int groupid;
  1574. int ret;
  1575. /* Check that the host device exists */
  1576. snprintf(path, sizeof(path),
  1577. "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
  1578. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1579. vdev->host.function);
  1580. if (stat(path, &st) < 0) {
  1581. error_report("vfio: error: no such host device: %s\n", path);
  1582. return -errno;
  1583. }
  1584. strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
  1585. len = readlink(path, iommu_group_path, PATH_MAX);
  1586. if (len <= 0) {
  1587. error_report("vfio: error no iommu_group for device\n");
  1588. return -errno;
  1589. }
  1590. iommu_group_path[len] = 0;
  1591. group_name = basename(iommu_group_path);
  1592. if (sscanf(group_name, "%d", &groupid) != 1) {
  1593. error_report("vfio: error reading %s: %m\n", path);
  1594. return -errno;
  1595. }
  1596. DPRINTF("%s(%04x:%02x:%02x.%x) group %d\n", __func__, vdev->host.domain,
  1597. vdev->host.bus, vdev->host.slot, vdev->host.function, groupid);
  1598. group = vfio_get_group(groupid);
  1599. if (!group) {
  1600. error_report("vfio: failed to get group %d\n", groupid);
  1601. return -ENOENT;
  1602. }
  1603. snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
  1604. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1605. vdev->host.function);
  1606. QLIST_FOREACH(pvdev, &group->device_list, next) {
  1607. if (pvdev->host.domain == vdev->host.domain &&
  1608. pvdev->host.bus == vdev->host.bus &&
  1609. pvdev->host.slot == vdev->host.slot &&
  1610. pvdev->host.function == vdev->host.function) {
  1611. error_report("vfio: error: device %s is already attached\n", path);
  1612. vfio_put_group(group);
  1613. return -EBUSY;
  1614. }
  1615. }
  1616. ret = vfio_get_device(group, path, vdev);
  1617. if (ret) {
  1618. error_report("vfio: failed to get device %s\n", path);
  1619. vfio_put_group(group);
  1620. return ret;
  1621. }
  1622. /* Get a copy of config space */
  1623. ret = pread(vdev->fd, vdev->pdev.config,
  1624. MIN(pci_config_size(&vdev->pdev), vdev->config_size),
  1625. vdev->config_offset);
  1626. if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
  1627. ret = ret < 0 ? -errno : -EFAULT;
  1628. error_report("vfio: Failed to read device config space\n");
  1629. goto out_put;
  1630. }
  1631. /*
  1632. * Clear host resource mapping info. If we choose not to register a
  1633. * BAR, such as might be the case with the option ROM, we can get
  1634. * confusing, unwritable, residual addresses from the host here.
  1635. */
  1636. memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
  1637. memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
  1638. vfio_load_rom(vdev);
  1639. ret = vfio_early_setup_msix(vdev);
  1640. if (ret) {
  1641. goto out_put;
  1642. }
  1643. vfio_map_bars(vdev);
  1644. ret = vfio_add_capabilities(vdev);
  1645. if (ret) {
  1646. goto out_teardown;
  1647. }
  1648. if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
  1649. vdev->intx.mmap_timer = qemu_new_timer_ms(vm_clock,
  1650. vfio_intx_mmap_enable, vdev);
  1651. pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_update_irq);
  1652. ret = vfio_enable_intx(vdev);
  1653. if (ret) {
  1654. goto out_teardown;
  1655. }
  1656. }
  1657. return 0;
  1658. out_teardown:
  1659. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  1660. vfio_teardown_msi(vdev);
  1661. vfio_unmap_bars(vdev);
  1662. out_put:
  1663. vfio_put_device(vdev);
  1664. vfio_put_group(group);
  1665. return ret;
  1666. }
  1667. static void vfio_exitfn(PCIDevice *pdev)
  1668. {
  1669. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1670. VFIOGroup *group = vdev->group;
  1671. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  1672. vfio_disable_interrupts(vdev);
  1673. if (vdev->intx.mmap_timer) {
  1674. qemu_free_timer(vdev->intx.mmap_timer);
  1675. }
  1676. vfio_teardown_msi(vdev);
  1677. vfio_unmap_bars(vdev);
  1678. vfio_put_device(vdev);
  1679. vfio_put_group(group);
  1680. }
  1681. static void vfio_pci_reset(DeviceState *dev)
  1682. {
  1683. PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
  1684. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1685. uint16_t cmd;
  1686. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  1687. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1688. vfio_disable_interrupts(vdev);
  1689. /*
  1690. * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
  1691. * Also put INTx Disable in known state.
  1692. */
  1693. cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
  1694. cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
  1695. PCI_COMMAND_INTX_DISABLE);
  1696. vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
  1697. if (vdev->reset_works) {
  1698. if (ioctl(vdev->fd, VFIO_DEVICE_RESET)) {
  1699. error_report("vfio: Error unable to reset physical device "
  1700. "(%04x:%02x:%02x.%x): %m\n", vdev->host.domain,
  1701. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1702. }
  1703. }
  1704. vfio_enable_intx(vdev);
  1705. }
  1706. static Property vfio_pci_dev_properties[] = {
  1707. DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host),
  1708. DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIODevice,
  1709. intx.mmap_timeout, 1100),
  1710. /*
  1711. * TODO - support passed fds... is this necessary?
  1712. * DEFINE_PROP_STRING("vfiofd", VFIODevice, vfiofd_name),
  1713. * DEFINE_PROP_STRING("vfiogroupfd, VFIODevice, vfiogroupfd_name),
  1714. */
  1715. DEFINE_PROP_END_OF_LIST(),
  1716. };
  1717. static const VMStateDescription vfio_pci_vmstate = {
  1718. .name = "vfio-pci",
  1719. .unmigratable = 1,
  1720. };
  1721. static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
  1722. {
  1723. DeviceClass *dc = DEVICE_CLASS(klass);
  1724. PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
  1725. dc->reset = vfio_pci_reset;
  1726. dc->props = vfio_pci_dev_properties;
  1727. dc->vmsd = &vfio_pci_vmstate;
  1728. dc->desc = "VFIO-based PCI device assignment";
  1729. pdc->init = vfio_initfn;
  1730. pdc->exit = vfio_exitfn;
  1731. pdc->config_read = vfio_pci_read_config;
  1732. pdc->config_write = vfio_pci_write_config;
  1733. }
  1734. static const TypeInfo vfio_pci_dev_info = {
  1735. .name = "vfio-pci",
  1736. .parent = TYPE_PCI_DEVICE,
  1737. .instance_size = sizeof(VFIODevice),
  1738. .class_init = vfio_pci_dev_class_init,
  1739. };
  1740. static void register_vfio_pci_dev_type(void)
  1741. {
  1742. type_register_static(&vfio_pci_dev_info);
  1743. }
  1744. type_init(register_vfio_pci_dev_type)