vfio_pci.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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 "qemu/event_notifier.h"
  29. #include "exec/address-spaces.h"
  30. #include "sysemu/kvm.h"
  31. #include "exec/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-report.h"
  37. #include "qemu/queue.h"
  38. #include "qemu/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_irqfds_enabled() ||
  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");
  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");
  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");
  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");
  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_irqfds_enabled() &&
  370. kvm_check_extension(kvm_state, KVM_CAP_IRQFD_RESAMPLE)) {
  371. vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
  372. vdev->intx.pin);
  373. }
  374. #endif
  375. ret = event_notifier_init(&vdev->intx.interrupt, 0);
  376. if (ret) {
  377. error_report("vfio: Error: event_notifier_init failed");
  378. return ret;
  379. }
  380. argsz = sizeof(*irq_set) + sizeof(*pfd);
  381. irq_set = g_malloc0(argsz);
  382. irq_set->argsz = argsz;
  383. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
  384. irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
  385. irq_set->start = 0;
  386. irq_set->count = 1;
  387. pfd = (int32_t *)&irq_set->data;
  388. *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
  389. qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
  390. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  391. g_free(irq_set);
  392. if (ret) {
  393. error_report("vfio: Error: Failed to setup INTx fd: %m");
  394. qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
  395. event_notifier_cleanup(&vdev->intx.interrupt);
  396. return -errno;
  397. }
  398. vfio_enable_intx_kvm(vdev);
  399. vdev->interrupt = VFIO_INT_INTx;
  400. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  401. vdev->host.bus, vdev->host.slot, vdev->host.function);
  402. return 0;
  403. }
  404. static void vfio_disable_intx(VFIODevice *vdev)
  405. {
  406. int fd;
  407. qemu_del_timer(vdev->intx.mmap_timer);
  408. vfio_disable_intx_kvm(vdev);
  409. vfio_disable_irqindex(vdev, VFIO_PCI_INTX_IRQ_INDEX);
  410. vdev->intx.pending = false;
  411. qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
  412. vfio_mmap_set_enabled(vdev, true);
  413. fd = event_notifier_get_fd(&vdev->intx.interrupt);
  414. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  415. event_notifier_cleanup(&vdev->intx.interrupt);
  416. vdev->interrupt = VFIO_INT_NONE;
  417. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  418. vdev->host.bus, vdev->host.slot, vdev->host.function);
  419. }
  420. /*
  421. * MSI/X
  422. */
  423. static void vfio_msi_interrupt(void *opaque)
  424. {
  425. VFIOMSIVector *vector = opaque;
  426. VFIODevice *vdev = vector->vdev;
  427. int nr = vector - vdev->msi_vectors;
  428. if (!event_notifier_test_and_clear(&vector->interrupt)) {
  429. return;
  430. }
  431. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d\n", __func__,
  432. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  433. vdev->host.function, nr);
  434. if (vdev->interrupt == VFIO_INT_MSIX) {
  435. msix_notify(&vdev->pdev, nr);
  436. } else if (vdev->interrupt == VFIO_INT_MSI) {
  437. msi_notify(&vdev->pdev, nr);
  438. } else {
  439. error_report("vfio: MSI interrupt receieved, but not enabled?");
  440. }
  441. }
  442. static int vfio_enable_vectors(VFIODevice *vdev, bool msix)
  443. {
  444. struct vfio_irq_set *irq_set;
  445. int ret = 0, i, argsz;
  446. int32_t *fds;
  447. argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
  448. irq_set = g_malloc0(argsz);
  449. irq_set->argsz = argsz;
  450. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
  451. irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
  452. irq_set->start = 0;
  453. irq_set->count = vdev->nr_vectors;
  454. fds = (int32_t *)&irq_set->data;
  455. for (i = 0; i < vdev->nr_vectors; i++) {
  456. if (!vdev->msi_vectors[i].use) {
  457. fds[i] = -1;
  458. continue;
  459. }
  460. fds[i] = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
  461. }
  462. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  463. g_free(irq_set);
  464. return ret;
  465. }
  466. static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
  467. MSIMessage *msg, IOHandler *handler)
  468. {
  469. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  470. VFIOMSIVector *vector;
  471. int ret;
  472. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d used\n", __func__,
  473. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  474. vdev->host.function, nr);
  475. vector = &vdev->msi_vectors[nr];
  476. vector->vdev = vdev;
  477. vector->use = true;
  478. msix_vector_use(pdev, nr);
  479. if (event_notifier_init(&vector->interrupt, 0)) {
  480. error_report("vfio: Error: event_notifier_init failed");
  481. }
  482. /*
  483. * Attempt to enable route through KVM irqchip,
  484. * default to userspace handling if unavailable.
  485. */
  486. vector->virq = msg ? kvm_irqchip_add_msi_route(kvm_state, *msg) : -1;
  487. if (vector->virq < 0 ||
  488. kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
  489. vector->virq) < 0) {
  490. if (vector->virq >= 0) {
  491. kvm_irqchip_release_virq(kvm_state, vector->virq);
  492. vector->virq = -1;
  493. }
  494. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  495. handler, NULL, vector);
  496. }
  497. /*
  498. * We don't want to have the host allocate all possible MSI vectors
  499. * for a device if they're not in use, so we shutdown and incrementally
  500. * increase them as needed.
  501. */
  502. if (vdev->nr_vectors < nr + 1) {
  503. vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
  504. vdev->nr_vectors = nr + 1;
  505. ret = vfio_enable_vectors(vdev, true);
  506. if (ret) {
  507. error_report("vfio: failed to enable vectors, %d", ret);
  508. }
  509. } else {
  510. int argsz;
  511. struct vfio_irq_set *irq_set;
  512. int32_t *pfd;
  513. argsz = sizeof(*irq_set) + sizeof(*pfd);
  514. irq_set = g_malloc0(argsz);
  515. irq_set->argsz = argsz;
  516. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
  517. VFIO_IRQ_SET_ACTION_TRIGGER;
  518. irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
  519. irq_set->start = nr;
  520. irq_set->count = 1;
  521. pfd = (int32_t *)&irq_set->data;
  522. *pfd = event_notifier_get_fd(&vector->interrupt);
  523. ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  524. g_free(irq_set);
  525. if (ret) {
  526. error_report("vfio: failed to modify vector, %d", ret);
  527. }
  528. }
  529. return 0;
  530. }
  531. static int vfio_msix_vector_use(PCIDevice *pdev,
  532. unsigned int nr, MSIMessage msg)
  533. {
  534. return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
  535. }
  536. static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
  537. {
  538. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  539. VFIOMSIVector *vector = &vdev->msi_vectors[nr];
  540. int argsz;
  541. struct vfio_irq_set *irq_set;
  542. int32_t *pfd;
  543. DPRINTF("%s(%04x:%02x:%02x.%x) vector %d released\n", __func__,
  544. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  545. vdev->host.function, nr);
  546. /*
  547. * XXX What's the right thing to do here? This turns off the interrupt
  548. * completely, but do we really just want to switch the interrupt to
  549. * bouncing through userspace and let msix.c drop it? Not sure.
  550. */
  551. msix_vector_unuse(pdev, nr);
  552. argsz = sizeof(*irq_set) + sizeof(*pfd);
  553. irq_set = g_malloc0(argsz);
  554. irq_set->argsz = argsz;
  555. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
  556. VFIO_IRQ_SET_ACTION_TRIGGER;
  557. irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
  558. irq_set->start = nr;
  559. irq_set->count = 1;
  560. pfd = (int32_t *)&irq_set->data;
  561. *pfd = -1;
  562. ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
  563. g_free(irq_set);
  564. if (vector->virq < 0) {
  565. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  566. NULL, NULL, NULL);
  567. } else {
  568. kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
  569. vector->virq);
  570. kvm_irqchip_release_virq(kvm_state, vector->virq);
  571. vector->virq = -1;
  572. }
  573. event_notifier_cleanup(&vector->interrupt);
  574. vector->use = false;
  575. }
  576. static void vfio_enable_msix(VFIODevice *vdev)
  577. {
  578. vfio_disable_interrupts(vdev);
  579. vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));
  580. vdev->interrupt = VFIO_INT_MSIX;
  581. /*
  582. * Some communication channels between VF & PF or PF & fw rely on the
  583. * physical state of the device and expect that enabling MSI-X from the
  584. * guest enables the same on the host. When our guest is Linux, the
  585. * guest driver call to pci_enable_msix() sets the enabling bit in the
  586. * MSI-X capability, but leaves the vector table masked. We therefore
  587. * can't rely on a vector_use callback (from request_irq() in the guest)
  588. * to switch the physical device into MSI-X mode because that may come a
  589. * long time after pci_enable_msix(). This code enables vector 0 with
  590. * triggering to userspace, then immediately release the vector, leaving
  591. * the physical device with no vectors enabled, but MSI-X enabled, just
  592. * like the guest view.
  593. */
  594. vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);
  595. vfio_msix_vector_release(&vdev->pdev, 0);
  596. if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
  597. vfio_msix_vector_release, NULL)) {
  598. error_report("vfio: msix_set_vector_notifiers failed");
  599. }
  600. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  601. vdev->host.bus, vdev->host.slot, vdev->host.function);
  602. }
  603. static void vfio_enable_msi(VFIODevice *vdev)
  604. {
  605. int ret, i;
  606. vfio_disable_interrupts(vdev);
  607. vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
  608. retry:
  609. vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
  610. for (i = 0; i < vdev->nr_vectors; i++) {
  611. MSIMessage msg;
  612. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  613. vector->vdev = vdev;
  614. vector->use = true;
  615. if (event_notifier_init(&vector->interrupt, 0)) {
  616. error_report("vfio: Error: event_notifier_init failed");
  617. }
  618. msg = msi_get_message(&vdev->pdev, i);
  619. /*
  620. * Attempt to enable route through KVM irqchip,
  621. * default to userspace handling if unavailable.
  622. */
  623. vector->virq = kvm_irqchip_add_msi_route(kvm_state, msg);
  624. if (vector->virq < 0 ||
  625. kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
  626. vector->virq) < 0) {
  627. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  628. vfio_msi_interrupt, NULL, vector);
  629. }
  630. }
  631. ret = vfio_enable_vectors(vdev, false);
  632. if (ret) {
  633. if (ret < 0) {
  634. error_report("vfio: Error: Failed to setup MSI fds: %m");
  635. } else if (ret != vdev->nr_vectors) {
  636. error_report("vfio: Error: Failed to enable %d "
  637. "MSI vectors, retry with %d", vdev->nr_vectors, ret);
  638. }
  639. for (i = 0; i < vdev->nr_vectors; i++) {
  640. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  641. if (vector->virq >= 0) {
  642. kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
  643. vector->virq);
  644. kvm_irqchip_release_virq(kvm_state, vector->virq);
  645. vector->virq = -1;
  646. } else {
  647. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  648. NULL, NULL, NULL);
  649. }
  650. event_notifier_cleanup(&vector->interrupt);
  651. }
  652. g_free(vdev->msi_vectors);
  653. if (ret > 0 && ret != vdev->nr_vectors) {
  654. vdev->nr_vectors = ret;
  655. goto retry;
  656. }
  657. vdev->nr_vectors = 0;
  658. return;
  659. }
  660. vdev->interrupt = VFIO_INT_MSI;
  661. DPRINTF("%s(%04x:%02x:%02x.%x) Enabled %d MSI vectors\n", __func__,
  662. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  663. vdev->host.function, vdev->nr_vectors);
  664. }
  665. static void vfio_disable_msi_common(VFIODevice *vdev)
  666. {
  667. g_free(vdev->msi_vectors);
  668. vdev->msi_vectors = NULL;
  669. vdev->nr_vectors = 0;
  670. vdev->interrupt = VFIO_INT_NONE;
  671. vfio_enable_intx(vdev);
  672. }
  673. static void vfio_disable_msix(VFIODevice *vdev)
  674. {
  675. msix_unset_vector_notifiers(&vdev->pdev);
  676. if (vdev->nr_vectors) {
  677. vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
  678. }
  679. vfio_disable_msi_common(vdev);
  680. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  681. vdev->host.bus, vdev->host.slot, vdev->host.function);
  682. }
  683. static void vfio_disable_msi(VFIODevice *vdev)
  684. {
  685. int i;
  686. vfio_disable_irqindex(vdev, VFIO_PCI_MSI_IRQ_INDEX);
  687. for (i = 0; i < vdev->nr_vectors; i++) {
  688. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  689. if (!vector->use) {
  690. continue;
  691. }
  692. if (vector->virq >= 0) {
  693. kvm_irqchip_remove_irqfd_notifier(kvm_state,
  694. &vector->interrupt, vector->virq);
  695. kvm_irqchip_release_virq(kvm_state, vector->virq);
  696. vector->virq = -1;
  697. } else {
  698. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  699. NULL, NULL, NULL);
  700. }
  701. event_notifier_cleanup(&vector->interrupt);
  702. }
  703. vfio_disable_msi_common(vdev);
  704. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  705. vdev->host.bus, vdev->host.slot, vdev->host.function);
  706. }
  707. /*
  708. * IO Port/MMIO - Beware of the endians, VFIO is always little endian
  709. */
  710. static void vfio_bar_write(void *opaque, hwaddr addr,
  711. uint64_t data, unsigned size)
  712. {
  713. VFIOBAR *bar = opaque;
  714. union {
  715. uint8_t byte;
  716. uint16_t word;
  717. uint32_t dword;
  718. uint64_t qword;
  719. } buf;
  720. switch (size) {
  721. case 1:
  722. buf.byte = data;
  723. break;
  724. case 2:
  725. buf.word = cpu_to_le16(data);
  726. break;
  727. case 4:
  728. buf.dword = cpu_to_le32(data);
  729. break;
  730. default:
  731. hw_error("vfio: unsupported write size, %d bytes\n", size);
  732. break;
  733. }
  734. if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
  735. error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
  736. __func__, addr, data, size);
  737. }
  738. DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", 0x%"PRIx64", %d)\n",
  739. __func__, bar->nr, addr, data, size);
  740. /*
  741. * A read or write to a BAR always signals an INTx EOI. This will
  742. * do nothing if not pending (including not in INTx mode). We assume
  743. * that a BAR access is in response to an interrupt and that BAR
  744. * accesses will service the interrupt. Unfortunately, we don't know
  745. * which access will service the interrupt, so we're potentially
  746. * getting quite a few host interrupts per guest interrupt.
  747. */
  748. vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
  749. }
  750. static uint64_t vfio_bar_read(void *opaque,
  751. hwaddr addr, unsigned size)
  752. {
  753. VFIOBAR *bar = opaque;
  754. union {
  755. uint8_t byte;
  756. uint16_t word;
  757. uint32_t dword;
  758. uint64_t qword;
  759. } buf;
  760. uint64_t data = 0;
  761. if (pread(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
  762. error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
  763. __func__, addr, size);
  764. return (uint64_t)-1;
  765. }
  766. switch (size) {
  767. case 1:
  768. data = buf.byte;
  769. break;
  770. case 2:
  771. data = le16_to_cpu(buf.word);
  772. break;
  773. case 4:
  774. data = le32_to_cpu(buf.dword);
  775. break;
  776. default:
  777. hw_error("vfio: unsupported read size, %d bytes\n", size);
  778. break;
  779. }
  780. DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", %d) = 0x%"PRIx64"\n",
  781. __func__, bar->nr, addr, size, data);
  782. /* Same as write above */
  783. vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
  784. return data;
  785. }
  786. static const MemoryRegionOps vfio_bar_ops = {
  787. .read = vfio_bar_read,
  788. .write = vfio_bar_write,
  789. .endianness = DEVICE_LITTLE_ENDIAN,
  790. };
  791. /*
  792. * PCI config space
  793. */
  794. static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
  795. {
  796. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  797. uint32_t val = 0;
  798. /*
  799. * We only need QEMU PCI config support for the ROM BAR, the MSI and MSIX
  800. * capabilities, and the multifunction bit below. We let VFIO handle
  801. * virtualizing everything else. Performance is not a concern here.
  802. */
  803. if (ranges_overlap(addr, len, PCI_ROM_ADDRESS, 4) ||
  804. (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
  805. ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) ||
  806. (pdev->cap_present & QEMU_PCI_CAP_MSI &&
  807. ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size))) {
  808. val = pci_default_read_config(pdev, addr, len);
  809. } else {
  810. if (pread(vdev->fd, &val, len, vdev->config_offset + addr) != len) {
  811. error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m",
  812. __func__, vdev->host.domain, vdev->host.bus,
  813. vdev->host.slot, vdev->host.function, addr, len);
  814. return -errno;
  815. }
  816. val = le32_to_cpu(val);
  817. }
  818. /* Multifunction bit is virualized in QEMU */
  819. if (unlikely(ranges_overlap(addr, len, PCI_HEADER_TYPE, 1))) {
  820. uint32_t mask = PCI_HEADER_TYPE_MULTI_FUNCTION;
  821. if (len == 4) {
  822. mask <<= 16;
  823. }
  824. if (pdev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
  825. val |= mask;
  826. } else {
  827. val &= ~mask;
  828. }
  829. }
  830. DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, len=0x%x) %x\n", __func__,
  831. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  832. vdev->host.function, addr, len, val);
  833. return val;
  834. }
  835. static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
  836. uint32_t val, int len)
  837. {
  838. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  839. uint32_t val_le = cpu_to_le32(val);
  840. DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,
  841. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  842. vdev->host.function, addr, val, len);
  843. /* Write everything to VFIO, let it filter out what we can't write */
  844. if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {
  845. error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",
  846. __func__, vdev->host.domain, vdev->host.bus,
  847. vdev->host.slot, vdev->host.function, addr, val, len);
  848. }
  849. /* Write standard header bits to emulation */
  850. if (addr < PCI_CONFIG_HEADER_SIZE) {
  851. pci_default_write_config(pdev, addr, val, len);
  852. return;
  853. }
  854. /* MSI/MSI-X Enabling/Disabling */
  855. if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
  856. ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
  857. int is_enabled, was_enabled = msi_enabled(pdev);
  858. pci_default_write_config(pdev, addr, val, len);
  859. is_enabled = msi_enabled(pdev);
  860. if (!was_enabled && is_enabled) {
  861. vfio_enable_msi(vdev);
  862. } else if (was_enabled && !is_enabled) {
  863. vfio_disable_msi(vdev);
  864. }
  865. }
  866. if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
  867. ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
  868. int is_enabled, was_enabled = msix_enabled(pdev);
  869. pci_default_write_config(pdev, addr, val, len);
  870. is_enabled = msix_enabled(pdev);
  871. if (!was_enabled && is_enabled) {
  872. vfio_enable_msix(vdev);
  873. } else if (was_enabled && !is_enabled) {
  874. vfio_disable_msix(vdev);
  875. }
  876. }
  877. }
  878. /*
  879. * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
  880. */
  881. static int vfio_dma_unmap(VFIOContainer *container,
  882. hwaddr iova, ram_addr_t size)
  883. {
  884. struct vfio_iommu_type1_dma_unmap unmap = {
  885. .argsz = sizeof(unmap),
  886. .flags = 0,
  887. .iova = iova,
  888. .size = size,
  889. };
  890. if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
  891. DPRINTF("VFIO_UNMAP_DMA: %d\n", -errno);
  892. return -errno;
  893. }
  894. return 0;
  895. }
  896. static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
  897. ram_addr_t size, void *vaddr, bool readonly)
  898. {
  899. struct vfio_iommu_type1_dma_map map = {
  900. .argsz = sizeof(map),
  901. .flags = VFIO_DMA_MAP_FLAG_READ,
  902. .vaddr = (__u64)(uintptr_t)vaddr,
  903. .iova = iova,
  904. .size = size,
  905. };
  906. if (!readonly) {
  907. map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
  908. }
  909. /*
  910. * Try the mapping, if it fails with EBUSY, unmap the region and try
  911. * again. This shouldn't be necessary, but we sometimes see it in
  912. * the the VGA ROM space.
  913. */
  914. if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
  915. (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
  916. ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
  917. return 0;
  918. }
  919. DPRINTF("VFIO_MAP_DMA: %d\n", -errno);
  920. return -errno;
  921. }
  922. static bool vfio_listener_skipped_section(MemoryRegionSection *section)
  923. {
  924. return !memory_region_is_ram(section->mr);
  925. }
  926. static void vfio_listener_region_add(MemoryListener *listener,
  927. MemoryRegionSection *section)
  928. {
  929. VFIOContainer *container = container_of(listener, VFIOContainer,
  930. iommu_data.listener);
  931. hwaddr iova, end;
  932. void *vaddr;
  933. int ret;
  934. if (vfio_listener_skipped_section(section)) {
  935. DPRINTF("vfio: SKIPPING region_add %"HWADDR_PRIx" - %"PRIx64"\n",
  936. section->offset_within_address_space,
  937. section->offset_within_address_space + section->size - 1);
  938. return;
  939. }
  940. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  941. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  942. error_report("%s received unaligned region", __func__);
  943. return;
  944. }
  945. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  946. end = (section->offset_within_address_space + section->size) &
  947. TARGET_PAGE_MASK;
  948. if (iova >= end) {
  949. return;
  950. }
  951. vaddr = memory_region_get_ram_ptr(section->mr) +
  952. section->offset_within_region +
  953. (iova - section->offset_within_address_space);
  954. DPRINTF("vfio: region_add %"HWADDR_PRIx" - %"HWADDR_PRIx" [%p]\n",
  955. iova, end - 1, vaddr);
  956. ret = vfio_dma_map(container, iova, end - iova, vaddr, section->readonly);
  957. if (ret) {
  958. error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
  959. "0x%"HWADDR_PRIx", %p) = %d (%m)",
  960. container, iova, end - iova, vaddr, ret);
  961. }
  962. }
  963. static void vfio_listener_region_del(MemoryListener *listener,
  964. MemoryRegionSection *section)
  965. {
  966. VFIOContainer *container = container_of(listener, VFIOContainer,
  967. iommu_data.listener);
  968. hwaddr iova, end;
  969. int ret;
  970. if (vfio_listener_skipped_section(section)) {
  971. DPRINTF("vfio: SKIPPING region_del %"HWADDR_PRIx" - %"PRIx64"\n",
  972. section->offset_within_address_space,
  973. section->offset_within_address_space + section->size - 1);
  974. return;
  975. }
  976. if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
  977. (section->offset_within_region & ~TARGET_PAGE_MASK))) {
  978. error_report("%s received unaligned region", __func__);
  979. return;
  980. }
  981. iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
  982. end = (section->offset_within_address_space + section->size) &
  983. TARGET_PAGE_MASK;
  984. if (iova >= end) {
  985. return;
  986. }
  987. DPRINTF("vfio: region_del %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
  988. iova, end - 1);
  989. ret = vfio_dma_unmap(container, iova, end - iova);
  990. if (ret) {
  991. error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
  992. "0x%"HWADDR_PRIx") = %d (%m)",
  993. container, iova, end - iova, ret);
  994. }
  995. }
  996. static MemoryListener vfio_memory_listener = {
  997. .region_add = vfio_listener_region_add,
  998. .region_del = vfio_listener_region_del,
  999. };
  1000. static void vfio_listener_release(VFIOContainer *container)
  1001. {
  1002. memory_listener_unregister(&container->iommu_data.listener);
  1003. }
  1004. /*
  1005. * Interrupt setup
  1006. */
  1007. static void vfio_disable_interrupts(VFIODevice *vdev)
  1008. {
  1009. switch (vdev->interrupt) {
  1010. case VFIO_INT_INTx:
  1011. vfio_disable_intx(vdev);
  1012. break;
  1013. case VFIO_INT_MSI:
  1014. vfio_disable_msi(vdev);
  1015. break;
  1016. case VFIO_INT_MSIX:
  1017. vfio_disable_msix(vdev);
  1018. break;
  1019. }
  1020. }
  1021. static int vfio_setup_msi(VFIODevice *vdev, int pos)
  1022. {
  1023. uint16_t ctrl;
  1024. bool msi_64bit, msi_maskbit;
  1025. int ret, entries;
  1026. if (pread(vdev->fd, &ctrl, sizeof(ctrl),
  1027. vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
  1028. return -errno;
  1029. }
  1030. ctrl = le16_to_cpu(ctrl);
  1031. msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
  1032. msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
  1033. entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
  1034. DPRINTF("%04x:%02x:%02x.%x PCI MSI CAP @0x%x\n", vdev->host.domain,
  1035. vdev->host.bus, vdev->host.slot, vdev->host.function, pos);
  1036. ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
  1037. if (ret < 0) {
  1038. if (ret == -ENOTSUP) {
  1039. return 0;
  1040. }
  1041. error_report("vfio: msi_init failed");
  1042. return ret;
  1043. }
  1044. vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
  1045. return 0;
  1046. }
  1047. /*
  1048. * We don't have any control over how pci_add_capability() inserts
  1049. * capabilities into the chain. In order to setup MSI-X we need a
  1050. * MemoryRegion for the BAR. In order to setup the BAR and not
  1051. * attempt to mmap the MSI-X table area, which VFIO won't allow, we
  1052. * need to first look for where the MSI-X table lives. So we
  1053. * unfortunately split MSI-X setup across two functions.
  1054. */
  1055. static int vfio_early_setup_msix(VFIODevice *vdev)
  1056. {
  1057. uint8_t pos;
  1058. uint16_t ctrl;
  1059. uint32_t table, pba;
  1060. pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
  1061. if (!pos) {
  1062. return 0;
  1063. }
  1064. if (pread(vdev->fd, &ctrl, sizeof(ctrl),
  1065. vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
  1066. return -errno;
  1067. }
  1068. if (pread(vdev->fd, &table, sizeof(table),
  1069. vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
  1070. return -errno;
  1071. }
  1072. if (pread(vdev->fd, &pba, sizeof(pba),
  1073. vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
  1074. return -errno;
  1075. }
  1076. ctrl = le16_to_cpu(ctrl);
  1077. table = le32_to_cpu(table);
  1078. pba = le32_to_cpu(pba);
  1079. vdev->msix = g_malloc0(sizeof(*(vdev->msix)));
  1080. vdev->msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
  1081. vdev->msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
  1082. vdev->msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
  1083. vdev->msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
  1084. vdev->msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
  1085. DPRINTF("%04x:%02x:%02x.%x "
  1086. "PCI MSI-X CAP @0x%x, BAR %d, offset 0x%x, entries %d\n",
  1087. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1088. vdev->host.function, pos, vdev->msix->table_bar,
  1089. vdev->msix->table_offset, vdev->msix->entries);
  1090. return 0;
  1091. }
  1092. static int vfio_setup_msix(VFIODevice *vdev, int pos)
  1093. {
  1094. int ret;
  1095. ret = msix_init(&vdev->pdev, vdev->msix->entries,
  1096. &vdev->bars[vdev->msix->table_bar].mem,
  1097. vdev->msix->table_bar, vdev->msix->table_offset,
  1098. &vdev->bars[vdev->msix->pba_bar].mem,
  1099. vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
  1100. if (ret < 0) {
  1101. if (ret == -ENOTSUP) {
  1102. return 0;
  1103. }
  1104. error_report("vfio: msix_init failed");
  1105. return ret;
  1106. }
  1107. return 0;
  1108. }
  1109. static void vfio_teardown_msi(VFIODevice *vdev)
  1110. {
  1111. msi_uninit(&vdev->pdev);
  1112. if (vdev->msix) {
  1113. msix_uninit(&vdev->pdev, &vdev->bars[vdev->msix->table_bar].mem,
  1114. &vdev->bars[vdev->msix->pba_bar].mem);
  1115. }
  1116. }
  1117. /*
  1118. * Resource setup
  1119. */
  1120. static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled)
  1121. {
  1122. int i;
  1123. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1124. VFIOBAR *bar = &vdev->bars[i];
  1125. if (!bar->size) {
  1126. continue;
  1127. }
  1128. memory_region_set_enabled(&bar->mmap_mem, enabled);
  1129. if (vdev->msix && vdev->msix->table_bar == i) {
  1130. memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
  1131. }
  1132. }
  1133. }
  1134. static void vfio_unmap_bar(VFIODevice *vdev, int nr)
  1135. {
  1136. VFIOBAR *bar = &vdev->bars[nr];
  1137. if (!bar->size) {
  1138. return;
  1139. }
  1140. memory_region_del_subregion(&bar->mem, &bar->mmap_mem);
  1141. munmap(bar->mmap, memory_region_size(&bar->mmap_mem));
  1142. if (vdev->msix && vdev->msix->table_bar == nr) {
  1143. memory_region_del_subregion(&bar->mem, &vdev->msix->mmap_mem);
  1144. munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
  1145. }
  1146. memory_region_destroy(&bar->mem);
  1147. }
  1148. static int vfio_mmap_bar(VFIOBAR *bar, MemoryRegion *mem, MemoryRegion *submem,
  1149. void **map, size_t size, off_t offset,
  1150. const char *name)
  1151. {
  1152. int ret = 0;
  1153. if (size && bar->flags & VFIO_REGION_INFO_FLAG_MMAP) {
  1154. int prot = 0;
  1155. if (bar->flags & VFIO_REGION_INFO_FLAG_READ) {
  1156. prot |= PROT_READ;
  1157. }
  1158. if (bar->flags & VFIO_REGION_INFO_FLAG_WRITE) {
  1159. prot |= PROT_WRITE;
  1160. }
  1161. *map = mmap(NULL, size, prot, MAP_SHARED,
  1162. bar->fd, bar->fd_offset + offset);
  1163. if (*map == MAP_FAILED) {
  1164. *map = NULL;
  1165. ret = -errno;
  1166. goto empty_region;
  1167. }
  1168. memory_region_init_ram_ptr(submem, name, size, *map);
  1169. } else {
  1170. empty_region:
  1171. /* Create a zero sized sub-region to make cleanup easy. */
  1172. memory_region_init(submem, name, 0);
  1173. }
  1174. memory_region_add_subregion(mem, offset, submem);
  1175. return ret;
  1176. }
  1177. static void vfio_map_bar(VFIODevice *vdev, int nr)
  1178. {
  1179. VFIOBAR *bar = &vdev->bars[nr];
  1180. unsigned size = bar->size;
  1181. char name[64];
  1182. uint32_t pci_bar;
  1183. uint8_t type;
  1184. int ret;
  1185. /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
  1186. if (!size) {
  1187. return;
  1188. }
  1189. snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
  1190. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1191. vdev->host.function, nr);
  1192. /* Determine what type of BAR this is for registration */
  1193. ret = pread(vdev->fd, &pci_bar, sizeof(pci_bar),
  1194. vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
  1195. if (ret != sizeof(pci_bar)) {
  1196. error_report("vfio: Failed to read BAR %d (%m)", nr);
  1197. return;
  1198. }
  1199. pci_bar = le32_to_cpu(pci_bar);
  1200. type = pci_bar & (pci_bar & PCI_BASE_ADDRESS_SPACE_IO ?
  1201. ~PCI_BASE_ADDRESS_IO_MASK : ~PCI_BASE_ADDRESS_MEM_MASK);
  1202. /* A "slow" read/write mapping underlies all BARs */
  1203. memory_region_init_io(&bar->mem, &vfio_bar_ops, bar, name, size);
  1204. pci_register_bar(&vdev->pdev, nr, type, &bar->mem);
  1205. /*
  1206. * We can't mmap areas overlapping the MSIX vector table, so we
  1207. * potentially insert a direct-mapped subregion before and after it.
  1208. */
  1209. if (vdev->msix && vdev->msix->table_bar == nr) {
  1210. size = vdev->msix->table_offset & TARGET_PAGE_MASK;
  1211. }
  1212. strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
  1213. if (vfio_mmap_bar(bar, &bar->mem,
  1214. &bar->mmap_mem, &bar->mmap, size, 0, name)) {
  1215. error_report("%s unsupported. Performance may be slow", name);
  1216. }
  1217. if (vdev->msix && vdev->msix->table_bar == nr) {
  1218. unsigned start;
  1219. start = TARGET_PAGE_ALIGN(vdev->msix->table_offset +
  1220. (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
  1221. size = start < bar->size ? bar->size - start : 0;
  1222. strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
  1223. /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
  1224. if (vfio_mmap_bar(bar, &bar->mem, &vdev->msix->mmap_mem,
  1225. &vdev->msix->mmap, size, start, name)) {
  1226. error_report("%s unsupported. Performance may be slow", name);
  1227. }
  1228. }
  1229. }
  1230. static void vfio_map_bars(VFIODevice *vdev)
  1231. {
  1232. int i;
  1233. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1234. vfio_map_bar(vdev, i);
  1235. }
  1236. }
  1237. static void vfio_unmap_bars(VFIODevice *vdev)
  1238. {
  1239. int i;
  1240. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1241. vfio_unmap_bar(vdev, i);
  1242. }
  1243. }
  1244. /*
  1245. * General setup
  1246. */
  1247. static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
  1248. {
  1249. uint8_t tmp, next = 0xff;
  1250. for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
  1251. tmp = pdev->config[tmp + 1]) {
  1252. if (tmp > pos && tmp < next) {
  1253. next = tmp;
  1254. }
  1255. }
  1256. return next - pos;
  1257. }
  1258. static int vfio_add_std_cap(VFIODevice *vdev, uint8_t pos)
  1259. {
  1260. PCIDevice *pdev = &vdev->pdev;
  1261. uint8_t cap_id, next, size;
  1262. int ret;
  1263. cap_id = pdev->config[pos];
  1264. next = pdev->config[pos + 1];
  1265. /*
  1266. * If it becomes important to configure capabilities to their actual
  1267. * size, use this as the default when it's something we don't recognize.
  1268. * Since QEMU doesn't actually handle many of the config accesses,
  1269. * exact size doesn't seem worthwhile.
  1270. */
  1271. size = vfio_std_cap_max_size(pdev, pos);
  1272. /*
  1273. * pci_add_capability always inserts the new capability at the head
  1274. * of the chain. Therefore to end up with a chain that matches the
  1275. * physical device, we insert from the end by making this recursive.
  1276. * This is also why we pre-caclulate size above as cached config space
  1277. * will be changed as we unwind the stack.
  1278. */
  1279. if (next) {
  1280. ret = vfio_add_std_cap(vdev, next);
  1281. if (ret) {
  1282. return ret;
  1283. }
  1284. } else {
  1285. pdev->config[PCI_CAPABILITY_LIST] = 0; /* Begin the rebuild */
  1286. }
  1287. switch (cap_id) {
  1288. case PCI_CAP_ID_MSI:
  1289. ret = vfio_setup_msi(vdev, pos);
  1290. break;
  1291. case PCI_CAP_ID_MSIX:
  1292. ret = vfio_setup_msix(vdev, pos);
  1293. break;
  1294. default:
  1295. ret = pci_add_capability(pdev, cap_id, pos, size);
  1296. break;
  1297. }
  1298. if (ret < 0) {
  1299. error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
  1300. "0x%x[0x%x]@0x%x: %d", vdev->host.domain,
  1301. vdev->host.bus, vdev->host.slot, vdev->host.function,
  1302. cap_id, size, pos, ret);
  1303. return ret;
  1304. }
  1305. return 0;
  1306. }
  1307. static int vfio_add_capabilities(VFIODevice *vdev)
  1308. {
  1309. PCIDevice *pdev = &vdev->pdev;
  1310. if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
  1311. !pdev->config[PCI_CAPABILITY_LIST]) {
  1312. return 0; /* Nothing to add */
  1313. }
  1314. return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
  1315. }
  1316. static int vfio_load_rom(VFIODevice *vdev)
  1317. {
  1318. uint64_t size = vdev->rom_size;
  1319. char name[32];
  1320. off_t off = 0, voff = vdev->rom_offset;
  1321. ssize_t bytes;
  1322. void *ptr;
  1323. /* If loading ROM from file, pci handles it */
  1324. if (vdev->pdev.romfile || !vdev->pdev.rom_bar || !size) {
  1325. return 0;
  1326. }
  1327. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  1328. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1329. snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
  1330. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1331. vdev->host.function);
  1332. memory_region_init_ram(&vdev->pdev.rom, name, size);
  1333. ptr = memory_region_get_ram_ptr(&vdev->pdev.rom);
  1334. memset(ptr, 0xff, size);
  1335. while (size) {
  1336. bytes = pread(vdev->fd, ptr + off, size, voff + off);
  1337. if (bytes == 0) {
  1338. break; /* expect that we could get back less than the ROM BAR */
  1339. } else if (bytes > 0) {
  1340. off += bytes;
  1341. size -= bytes;
  1342. } else {
  1343. if (errno == EINTR || errno == EAGAIN) {
  1344. continue;
  1345. }
  1346. error_report("vfio: Error reading device ROM: %m");
  1347. memory_region_destroy(&vdev->pdev.rom);
  1348. return -errno;
  1349. }
  1350. }
  1351. pci_register_bar(&vdev->pdev, PCI_ROM_SLOT, 0, &vdev->pdev.rom);
  1352. vdev->pdev.has_rom = true;
  1353. return 0;
  1354. }
  1355. static int vfio_connect_container(VFIOGroup *group)
  1356. {
  1357. VFIOContainer *container;
  1358. int ret, fd;
  1359. if (group->container) {
  1360. return 0;
  1361. }
  1362. QLIST_FOREACH(container, &container_list, next) {
  1363. if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
  1364. group->container = container;
  1365. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1366. return 0;
  1367. }
  1368. }
  1369. fd = qemu_open("/dev/vfio/vfio", O_RDWR);
  1370. if (fd < 0) {
  1371. error_report("vfio: failed to open /dev/vfio/vfio: %m");
  1372. return -errno;
  1373. }
  1374. ret = ioctl(fd, VFIO_GET_API_VERSION);
  1375. if (ret != VFIO_API_VERSION) {
  1376. error_report("vfio: supported vfio version: %d, "
  1377. "reported version: %d", VFIO_API_VERSION, ret);
  1378. close(fd);
  1379. return -EINVAL;
  1380. }
  1381. container = g_malloc0(sizeof(*container));
  1382. container->fd = fd;
  1383. if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
  1384. ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
  1385. if (ret) {
  1386. error_report("vfio: failed to set group container: %m");
  1387. g_free(container);
  1388. close(fd);
  1389. return -errno;
  1390. }
  1391. ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
  1392. if (ret) {
  1393. error_report("vfio: failed to set iommu for container: %m");
  1394. g_free(container);
  1395. close(fd);
  1396. return -errno;
  1397. }
  1398. container->iommu_data.listener = vfio_memory_listener;
  1399. container->iommu_data.release = vfio_listener_release;
  1400. memory_listener_register(&container->iommu_data.listener, &address_space_memory);
  1401. } else {
  1402. error_report("vfio: No available IOMMU models");
  1403. g_free(container);
  1404. close(fd);
  1405. return -EINVAL;
  1406. }
  1407. QLIST_INIT(&container->group_list);
  1408. QLIST_INSERT_HEAD(&container_list, container, next);
  1409. group->container = container;
  1410. QLIST_INSERT_HEAD(&container->group_list, group, container_next);
  1411. return 0;
  1412. }
  1413. static void vfio_disconnect_container(VFIOGroup *group)
  1414. {
  1415. VFIOContainer *container = group->container;
  1416. if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
  1417. error_report("vfio: error disconnecting group %d from container",
  1418. group->groupid);
  1419. }
  1420. QLIST_REMOVE(group, container_next);
  1421. group->container = NULL;
  1422. if (QLIST_EMPTY(&container->group_list)) {
  1423. if (container->iommu_data.release) {
  1424. container->iommu_data.release(container);
  1425. }
  1426. QLIST_REMOVE(container, next);
  1427. DPRINTF("vfio_disconnect_container: close container->fd\n");
  1428. close(container->fd);
  1429. g_free(container);
  1430. }
  1431. }
  1432. static VFIOGroup *vfio_get_group(int groupid)
  1433. {
  1434. VFIOGroup *group;
  1435. char path[32];
  1436. struct vfio_group_status status = { .argsz = sizeof(status) };
  1437. QLIST_FOREACH(group, &group_list, next) {
  1438. if (group->groupid == groupid) {
  1439. return group;
  1440. }
  1441. }
  1442. group = g_malloc0(sizeof(*group));
  1443. snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
  1444. group->fd = qemu_open(path, O_RDWR);
  1445. if (group->fd < 0) {
  1446. error_report("vfio: error opening %s: %m", path);
  1447. g_free(group);
  1448. return NULL;
  1449. }
  1450. if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
  1451. error_report("vfio: error getting group status: %m");
  1452. close(group->fd);
  1453. g_free(group);
  1454. return NULL;
  1455. }
  1456. if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
  1457. error_report("vfio: error, group %d is not viable, please ensure "
  1458. "all devices within the iommu_group are bound to their "
  1459. "vfio bus driver.", groupid);
  1460. close(group->fd);
  1461. g_free(group);
  1462. return NULL;
  1463. }
  1464. group->groupid = groupid;
  1465. QLIST_INIT(&group->device_list);
  1466. if (vfio_connect_container(group)) {
  1467. error_report("vfio: failed to setup container for group %d", groupid);
  1468. close(group->fd);
  1469. g_free(group);
  1470. return NULL;
  1471. }
  1472. QLIST_INSERT_HEAD(&group_list, group, next);
  1473. return group;
  1474. }
  1475. static void vfio_put_group(VFIOGroup *group)
  1476. {
  1477. if (!QLIST_EMPTY(&group->device_list)) {
  1478. return;
  1479. }
  1480. vfio_disconnect_container(group);
  1481. QLIST_REMOVE(group, next);
  1482. DPRINTF("vfio_put_group: close group->fd\n");
  1483. close(group->fd);
  1484. g_free(group);
  1485. }
  1486. static int vfio_get_device(VFIOGroup *group, const char *name, VFIODevice *vdev)
  1487. {
  1488. struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
  1489. struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
  1490. int ret, i;
  1491. ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
  1492. if (ret < 0) {
  1493. error_report("vfio: error getting device %s from group %d: %m",
  1494. name, group->groupid);
  1495. error_printf("Verify all devices in group %d are bound to vfio-pci "
  1496. "or pci-stub and not already in use\n", group->groupid);
  1497. return ret;
  1498. }
  1499. vdev->fd = ret;
  1500. vdev->group = group;
  1501. QLIST_INSERT_HEAD(&group->device_list, vdev, next);
  1502. /* Sanity check device */
  1503. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_INFO, &dev_info);
  1504. if (ret) {
  1505. error_report("vfio: error getting device info: %m");
  1506. goto error;
  1507. }
  1508. DPRINTF("Device %s flags: %u, regions: %u, irgs: %u\n", name,
  1509. dev_info.flags, dev_info.num_regions, dev_info.num_irqs);
  1510. if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {
  1511. error_report("vfio: Um, this isn't a PCI device");
  1512. goto error;
  1513. }
  1514. vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
  1515. if (!vdev->reset_works) {
  1516. error_report("Warning, device %s does not support reset", name);
  1517. }
  1518. if (dev_info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
  1519. error_report("vfio: unexpected number of io regions %u",
  1520. dev_info.num_regions);
  1521. goto error;
  1522. }
  1523. if (dev_info.num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
  1524. error_report("vfio: unexpected number of irqs %u", dev_info.num_irqs);
  1525. goto error;
  1526. }
  1527. for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
  1528. reg_info.index = i;
  1529. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1530. if (ret) {
  1531. error_report("vfio: Error getting region %d info: %m", i);
  1532. goto error;
  1533. }
  1534. DPRINTF("Device %s region %d:\n", name, i);
  1535. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1536. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1537. (unsigned long)reg_info.flags);
  1538. vdev->bars[i].flags = reg_info.flags;
  1539. vdev->bars[i].size = reg_info.size;
  1540. vdev->bars[i].fd_offset = reg_info.offset;
  1541. vdev->bars[i].fd = vdev->fd;
  1542. vdev->bars[i].nr = i;
  1543. }
  1544. reg_info.index = VFIO_PCI_ROM_REGION_INDEX;
  1545. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1546. if (ret) {
  1547. error_report("vfio: Error getting ROM info: %m");
  1548. goto error;
  1549. }
  1550. DPRINTF("Device %s ROM:\n", name);
  1551. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1552. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1553. (unsigned long)reg_info.flags);
  1554. vdev->rom_size = reg_info.size;
  1555. vdev->rom_offset = reg_info.offset;
  1556. reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
  1557. ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
  1558. if (ret) {
  1559. error_report("vfio: Error getting config info: %m");
  1560. goto error;
  1561. }
  1562. DPRINTF("Device %s config:\n", name);
  1563. DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
  1564. (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
  1565. (unsigned long)reg_info.flags);
  1566. vdev->config_size = reg_info.size;
  1567. if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
  1568. vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
  1569. }
  1570. vdev->config_offset = reg_info.offset;
  1571. error:
  1572. if (ret) {
  1573. QLIST_REMOVE(vdev, next);
  1574. vdev->group = NULL;
  1575. close(vdev->fd);
  1576. }
  1577. return ret;
  1578. }
  1579. static void vfio_put_device(VFIODevice *vdev)
  1580. {
  1581. QLIST_REMOVE(vdev, next);
  1582. vdev->group = NULL;
  1583. DPRINTF("vfio_put_device: close vdev->fd\n");
  1584. close(vdev->fd);
  1585. if (vdev->msix) {
  1586. g_free(vdev->msix);
  1587. vdev->msix = NULL;
  1588. }
  1589. }
  1590. static int vfio_initfn(PCIDevice *pdev)
  1591. {
  1592. VFIODevice *pvdev, *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1593. VFIOGroup *group;
  1594. char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
  1595. ssize_t len;
  1596. struct stat st;
  1597. int groupid;
  1598. int ret;
  1599. /* Check that the host device exists */
  1600. snprintf(path, sizeof(path),
  1601. "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
  1602. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1603. vdev->host.function);
  1604. if (stat(path, &st) < 0) {
  1605. error_report("vfio: error: no such host device: %s", path);
  1606. return -errno;
  1607. }
  1608. strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
  1609. len = readlink(path, iommu_group_path, PATH_MAX);
  1610. if (len <= 0) {
  1611. error_report("vfio: error no iommu_group for device");
  1612. return -errno;
  1613. }
  1614. iommu_group_path[len] = 0;
  1615. group_name = basename(iommu_group_path);
  1616. if (sscanf(group_name, "%d", &groupid) != 1) {
  1617. error_report("vfio: error reading %s: %m", path);
  1618. return -errno;
  1619. }
  1620. DPRINTF("%s(%04x:%02x:%02x.%x) group %d\n", __func__, vdev->host.domain,
  1621. vdev->host.bus, vdev->host.slot, vdev->host.function, groupid);
  1622. group = vfio_get_group(groupid);
  1623. if (!group) {
  1624. error_report("vfio: failed to get group %d", groupid);
  1625. return -ENOENT;
  1626. }
  1627. snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
  1628. vdev->host.domain, vdev->host.bus, vdev->host.slot,
  1629. vdev->host.function);
  1630. QLIST_FOREACH(pvdev, &group->device_list, next) {
  1631. if (pvdev->host.domain == vdev->host.domain &&
  1632. pvdev->host.bus == vdev->host.bus &&
  1633. pvdev->host.slot == vdev->host.slot &&
  1634. pvdev->host.function == vdev->host.function) {
  1635. error_report("vfio: error: device %s is already attached", path);
  1636. vfio_put_group(group);
  1637. return -EBUSY;
  1638. }
  1639. }
  1640. ret = vfio_get_device(group, path, vdev);
  1641. if (ret) {
  1642. error_report("vfio: failed to get device %s", path);
  1643. vfio_put_group(group);
  1644. return ret;
  1645. }
  1646. /* Get a copy of config space */
  1647. ret = pread(vdev->fd, vdev->pdev.config,
  1648. MIN(pci_config_size(&vdev->pdev), vdev->config_size),
  1649. vdev->config_offset);
  1650. if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
  1651. ret = ret < 0 ? -errno : -EFAULT;
  1652. error_report("vfio: Failed to read device config space");
  1653. goto out_put;
  1654. }
  1655. /*
  1656. * Clear host resource mapping info. If we choose not to register a
  1657. * BAR, such as might be the case with the option ROM, we can get
  1658. * confusing, unwritable, residual addresses from the host here.
  1659. */
  1660. memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
  1661. memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
  1662. vfio_load_rom(vdev);
  1663. ret = vfio_early_setup_msix(vdev);
  1664. if (ret) {
  1665. goto out_put;
  1666. }
  1667. vfio_map_bars(vdev);
  1668. ret = vfio_add_capabilities(vdev);
  1669. if (ret) {
  1670. goto out_teardown;
  1671. }
  1672. if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
  1673. vdev->intx.mmap_timer = qemu_new_timer_ms(vm_clock,
  1674. vfio_intx_mmap_enable, vdev);
  1675. pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_update_irq);
  1676. ret = vfio_enable_intx(vdev);
  1677. if (ret) {
  1678. goto out_teardown;
  1679. }
  1680. }
  1681. return 0;
  1682. out_teardown:
  1683. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  1684. vfio_teardown_msi(vdev);
  1685. vfio_unmap_bars(vdev);
  1686. out_put:
  1687. vfio_put_device(vdev);
  1688. vfio_put_group(group);
  1689. return ret;
  1690. }
  1691. static void vfio_exitfn(PCIDevice *pdev)
  1692. {
  1693. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1694. VFIOGroup *group = vdev->group;
  1695. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  1696. vfio_disable_interrupts(vdev);
  1697. if (vdev->intx.mmap_timer) {
  1698. qemu_free_timer(vdev->intx.mmap_timer);
  1699. }
  1700. vfio_teardown_msi(vdev);
  1701. vfio_unmap_bars(vdev);
  1702. vfio_put_device(vdev);
  1703. vfio_put_group(group);
  1704. }
  1705. static void vfio_pci_reset(DeviceState *dev)
  1706. {
  1707. PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
  1708. VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
  1709. uint16_t cmd;
  1710. DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
  1711. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1712. vfio_disable_interrupts(vdev);
  1713. /*
  1714. * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
  1715. * Also put INTx Disable in known state.
  1716. */
  1717. cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
  1718. cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
  1719. PCI_COMMAND_INTX_DISABLE);
  1720. vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
  1721. if (vdev->reset_works) {
  1722. if (ioctl(vdev->fd, VFIO_DEVICE_RESET)) {
  1723. error_report("vfio: Error unable to reset physical device "
  1724. "(%04x:%02x:%02x.%x): %m", vdev->host.domain,
  1725. vdev->host.bus, vdev->host.slot, vdev->host.function);
  1726. }
  1727. }
  1728. vfio_enable_intx(vdev);
  1729. }
  1730. static Property vfio_pci_dev_properties[] = {
  1731. DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host),
  1732. DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIODevice,
  1733. intx.mmap_timeout, 1100),
  1734. /*
  1735. * TODO - support passed fds... is this necessary?
  1736. * DEFINE_PROP_STRING("vfiofd", VFIODevice, vfiofd_name),
  1737. * DEFINE_PROP_STRING("vfiogroupfd, VFIODevice, vfiogroupfd_name),
  1738. */
  1739. DEFINE_PROP_END_OF_LIST(),
  1740. };
  1741. static const VMStateDescription vfio_pci_vmstate = {
  1742. .name = "vfio-pci",
  1743. .unmigratable = 1,
  1744. };
  1745. static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
  1746. {
  1747. DeviceClass *dc = DEVICE_CLASS(klass);
  1748. PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
  1749. dc->reset = vfio_pci_reset;
  1750. dc->props = vfio_pci_dev_properties;
  1751. dc->vmsd = &vfio_pci_vmstate;
  1752. dc->desc = "VFIO-based PCI device assignment";
  1753. pdc->init = vfio_initfn;
  1754. pdc->exit = vfio_exitfn;
  1755. pdc->config_read = vfio_pci_read_config;
  1756. pdc->config_write = vfio_pci_write_config;
  1757. pdc->is_express = 1; /* We might be */
  1758. }
  1759. static const TypeInfo vfio_pci_dev_info = {
  1760. .name = "vfio-pci",
  1761. .parent = TYPE_PCI_DEVICE,
  1762. .instance_size = sizeof(VFIODevice),
  1763. .class_init = vfio_pci_dev_class_init,
  1764. };
  1765. static void register_vfio_pci_dev_type(void)
  1766. {
  1767. type_register_static(&vfio_pci_dev_info);
  1768. }
  1769. type_init(register_vfio_pci_dev_type)