pci.c 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  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 "qemu/osdep.h"
  21. #include CONFIG_DEVICES /* CONFIG_IOMMUFD */
  22. #include <linux/vfio.h>
  23. #include <sys/ioctl.h>
  24. #include "hw/hw.h"
  25. #include "hw/pci/msi.h"
  26. #include "hw/pci/msix.h"
  27. #include "hw/pci/pci_bridge.h"
  28. #include "hw/qdev-properties.h"
  29. #include "hw/qdev-properties-system.h"
  30. #include "migration/vmstate.h"
  31. #include "qobject/qdict.h"
  32. #include "qemu/error-report.h"
  33. #include "qemu/main-loop.h"
  34. #include "qemu/module.h"
  35. #include "qemu/range.h"
  36. #include "qemu/units.h"
  37. #include "system/kvm.h"
  38. #include "system/runstate.h"
  39. #include "pci.h"
  40. #include "trace.h"
  41. #include "qapi/error.h"
  42. #include "migration/blocker.h"
  43. #include "migration/qemu-file.h"
  44. #include "system/iommufd.h"
  45. #define TYPE_VFIO_PCI_NOHOTPLUG "vfio-pci-nohotplug"
  46. /* Protected by BQL */
  47. static KVMRouteChange vfio_route_change;
  48. static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
  49. static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
  50. static void vfio_msi_disable_common(VFIOPCIDevice *vdev);
  51. /*
  52. * Disabling BAR mmaping can be slow, but toggling it around INTx can
  53. * also be a huge overhead. We try to get the best of both worlds by
  54. * waiting until an interrupt to disable mmaps (subsequent transitions
  55. * to the same state are effectively no overhead). If the interrupt has
  56. * been serviced and the time gap is long enough, we re-enable mmaps for
  57. * performance. This works well for things like graphics cards, which
  58. * may not use their interrupt at all and are penalized to an unusable
  59. * level by read/write BAR traps. Other devices, like NICs, have more
  60. * regular interrupts and see much better latency by staying in non-mmap
  61. * mode. We therefore set the default mmap_timeout such that a ping
  62. * is just enough to keep the mmap disabled. Users can experiment with
  63. * other options with the x-intx-mmap-timeout-ms parameter (a value of
  64. * zero disables the timer).
  65. */
  66. static void vfio_intx_mmap_enable(void *opaque)
  67. {
  68. VFIOPCIDevice *vdev = opaque;
  69. if (vdev->intx.pending) {
  70. timer_mod(vdev->intx.mmap_timer,
  71. qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
  72. return;
  73. }
  74. vfio_mmap_set_enabled(vdev, true);
  75. }
  76. static void vfio_intx_interrupt(void *opaque)
  77. {
  78. VFIOPCIDevice *vdev = opaque;
  79. if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
  80. return;
  81. }
  82. trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
  83. vdev->intx.pending = true;
  84. pci_irq_assert(&vdev->pdev);
  85. vfio_mmap_set_enabled(vdev, false);
  86. if (vdev->intx.mmap_timeout) {
  87. timer_mod(vdev->intx.mmap_timer,
  88. qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
  89. }
  90. }
  91. static void vfio_intx_eoi(VFIODevice *vbasedev)
  92. {
  93. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  94. if (!vdev->intx.pending) {
  95. return;
  96. }
  97. trace_vfio_intx_eoi(vbasedev->name);
  98. vdev->intx.pending = false;
  99. pci_irq_deassert(&vdev->pdev);
  100. vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  101. }
  102. static bool vfio_intx_enable_kvm(VFIOPCIDevice *vdev, Error **errp)
  103. {
  104. #ifdef CONFIG_KVM
  105. int irq_fd = event_notifier_get_fd(&vdev->intx.interrupt);
  106. if (vdev->no_kvm_intx || !kvm_irqfds_enabled() ||
  107. vdev->intx.route.mode != PCI_INTX_ENABLED ||
  108. !kvm_resamplefds_enabled()) {
  109. return true;
  110. }
  111. /* Get to a known interrupt state */
  112. qemu_set_fd_handler(irq_fd, NULL, NULL, vdev);
  113. vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  114. vdev->intx.pending = false;
  115. pci_irq_deassert(&vdev->pdev);
  116. /* Get an eventfd for resample/unmask */
  117. if (event_notifier_init(&vdev->intx.unmask, 0)) {
  118. error_setg(errp, "event_notifier_init failed eoi");
  119. goto fail;
  120. }
  121. if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state,
  122. &vdev->intx.interrupt,
  123. &vdev->intx.unmask,
  124. vdev->intx.route.irq)) {
  125. error_setg_errno(errp, errno, "failed to setup resample irqfd");
  126. goto fail_irqfd;
  127. }
  128. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
  129. VFIO_IRQ_SET_ACTION_UNMASK,
  130. event_notifier_get_fd(&vdev->intx.unmask),
  131. errp)) {
  132. goto fail_vfio;
  133. }
  134. /* Let'em rip */
  135. vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  136. vdev->intx.kvm_accel = true;
  137. trace_vfio_intx_enable_kvm(vdev->vbasedev.name);
  138. return true;
  139. fail_vfio:
  140. kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
  141. vdev->intx.route.irq);
  142. fail_irqfd:
  143. event_notifier_cleanup(&vdev->intx.unmask);
  144. fail:
  145. qemu_set_fd_handler(irq_fd, vfio_intx_interrupt, NULL, vdev);
  146. vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  147. return false;
  148. #else
  149. return true;
  150. #endif
  151. }
  152. static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev)
  153. {
  154. #ifdef CONFIG_KVM
  155. if (!vdev->intx.kvm_accel) {
  156. return;
  157. }
  158. /*
  159. * Get to a known state, hardware masked, QEMU ready to accept new
  160. * interrupts, QEMU IRQ de-asserted.
  161. */
  162. vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  163. vdev->intx.pending = false;
  164. pci_irq_deassert(&vdev->pdev);
  165. /* Tell KVM to stop listening for an INTx irqfd */
  166. if (kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
  167. vdev->intx.route.irq)) {
  168. error_report("vfio: Error: Failed to disable INTx irqfd: %m");
  169. }
  170. /* We only need to close the eventfd for VFIO to cleanup the kernel side */
  171. event_notifier_cleanup(&vdev->intx.unmask);
  172. /* QEMU starts listening for interrupt events. */
  173. qemu_set_fd_handler(event_notifier_get_fd(&vdev->intx.interrupt),
  174. vfio_intx_interrupt, NULL, vdev);
  175. vdev->intx.kvm_accel = false;
  176. /* If we've missed an event, let it re-fire through QEMU */
  177. vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  178. trace_vfio_intx_disable_kvm(vdev->vbasedev.name);
  179. #endif
  180. }
  181. static void vfio_intx_update(VFIOPCIDevice *vdev, PCIINTxRoute *route)
  182. {
  183. Error *err = NULL;
  184. trace_vfio_intx_update(vdev->vbasedev.name,
  185. vdev->intx.route.irq, route->irq);
  186. vfio_intx_disable_kvm(vdev);
  187. vdev->intx.route = *route;
  188. if (route->mode != PCI_INTX_ENABLED) {
  189. return;
  190. }
  191. if (!vfio_intx_enable_kvm(vdev, &err)) {
  192. warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  193. }
  194. /* Re-enable the interrupt in cased we missed an EOI */
  195. vfio_intx_eoi(&vdev->vbasedev);
  196. }
  197. static void vfio_intx_routing_notifier(PCIDevice *pdev)
  198. {
  199. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  200. PCIINTxRoute route;
  201. if (vdev->interrupt != VFIO_INT_INTx) {
  202. return;
  203. }
  204. route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
  205. if (pci_intx_route_changed(&vdev->intx.route, &route)) {
  206. vfio_intx_update(vdev, &route);
  207. }
  208. }
  209. static void vfio_irqchip_change(Notifier *notify, void *data)
  210. {
  211. VFIOPCIDevice *vdev = container_of(notify, VFIOPCIDevice,
  212. irqchip_change_notifier);
  213. vfio_intx_update(vdev, &vdev->intx.route);
  214. }
  215. static bool vfio_intx_enable(VFIOPCIDevice *vdev, Error **errp)
  216. {
  217. uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
  218. Error *err = NULL;
  219. int32_t fd;
  220. int ret;
  221. if (!pin) {
  222. return true;
  223. }
  224. vfio_disable_interrupts(vdev);
  225. vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
  226. pci_config_set_interrupt_pin(vdev->pdev.config, pin);
  227. #ifdef CONFIG_KVM
  228. /*
  229. * Only conditional to avoid generating error messages on platforms
  230. * where we won't actually use the result anyway.
  231. */
  232. if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
  233. vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
  234. vdev->intx.pin);
  235. }
  236. #endif
  237. ret = event_notifier_init(&vdev->intx.interrupt, 0);
  238. if (ret) {
  239. error_setg_errno(errp, -ret, "event_notifier_init failed");
  240. return false;
  241. }
  242. fd = event_notifier_get_fd(&vdev->intx.interrupt);
  243. qemu_set_fd_handler(fd, vfio_intx_interrupt, NULL, vdev);
  244. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
  245. VFIO_IRQ_SET_ACTION_TRIGGER, fd, errp)) {
  246. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  247. event_notifier_cleanup(&vdev->intx.interrupt);
  248. return false;
  249. }
  250. if (!vfio_intx_enable_kvm(vdev, &err)) {
  251. warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  252. }
  253. vdev->interrupt = VFIO_INT_INTx;
  254. trace_vfio_intx_enable(vdev->vbasedev.name);
  255. return true;
  256. }
  257. static void vfio_intx_disable(VFIOPCIDevice *vdev)
  258. {
  259. int fd;
  260. timer_del(vdev->intx.mmap_timer);
  261. vfio_intx_disable_kvm(vdev);
  262. vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
  263. vdev->intx.pending = false;
  264. pci_irq_deassert(&vdev->pdev);
  265. vfio_mmap_set_enabled(vdev, true);
  266. fd = event_notifier_get_fd(&vdev->intx.interrupt);
  267. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  268. event_notifier_cleanup(&vdev->intx.interrupt);
  269. vdev->interrupt = VFIO_INT_NONE;
  270. trace_vfio_intx_disable(vdev->vbasedev.name);
  271. }
  272. /*
  273. * MSI/X
  274. */
  275. static void vfio_msi_interrupt(void *opaque)
  276. {
  277. VFIOMSIVector *vector = opaque;
  278. VFIOPCIDevice *vdev = vector->vdev;
  279. MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector);
  280. void (*notify)(PCIDevice *dev, unsigned vector);
  281. MSIMessage msg;
  282. int nr = vector - vdev->msi_vectors;
  283. if (!event_notifier_test_and_clear(&vector->interrupt)) {
  284. return;
  285. }
  286. if (vdev->interrupt == VFIO_INT_MSIX) {
  287. get_msg = msix_get_message;
  288. notify = msix_notify;
  289. /* A masked vector firing needs to use the PBA, enable it */
  290. if (msix_is_masked(&vdev->pdev, nr)) {
  291. set_bit(nr, vdev->msix->pending);
  292. memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, true);
  293. trace_vfio_msix_pba_enable(vdev->vbasedev.name);
  294. }
  295. } else if (vdev->interrupt == VFIO_INT_MSI) {
  296. get_msg = msi_get_message;
  297. notify = msi_notify;
  298. } else {
  299. abort();
  300. }
  301. msg = get_msg(&vdev->pdev, nr);
  302. trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
  303. notify(&vdev->pdev, nr);
  304. }
  305. /*
  306. * Get MSI-X enabled, but no vector enabled, by setting vector 0 with an invalid
  307. * fd to kernel.
  308. */
  309. static int vfio_enable_msix_no_vec(VFIOPCIDevice *vdev)
  310. {
  311. g_autofree struct vfio_irq_set *irq_set = NULL;
  312. int ret = 0, argsz;
  313. int32_t *fd;
  314. argsz = sizeof(*irq_set) + sizeof(*fd);
  315. irq_set = g_malloc0(argsz);
  316. irq_set->argsz = argsz;
  317. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
  318. VFIO_IRQ_SET_ACTION_TRIGGER;
  319. irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
  320. irq_set->start = 0;
  321. irq_set->count = 1;
  322. fd = (int32_t *)&irq_set->data;
  323. *fd = -1;
  324. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
  325. return ret;
  326. }
  327. static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
  328. {
  329. struct vfio_irq_set *irq_set;
  330. int ret = 0, i, argsz;
  331. int32_t *fds;
  332. /*
  333. * If dynamic MSI-X allocation is supported, the vectors to be allocated
  334. * and enabled can be scattered. Before kernel enabling MSI-X, setting
  335. * nr_vectors causes all these vectors to be allocated on host.
  336. *
  337. * To keep allocation as needed, use vector 0 with an invalid fd to get
  338. * MSI-X enabled first, then set vectors with a potentially sparse set of
  339. * eventfds to enable interrupts only when enabled in guest.
  340. */
  341. if (msix && !vdev->msix->noresize) {
  342. ret = vfio_enable_msix_no_vec(vdev);
  343. if (ret) {
  344. return ret;
  345. }
  346. }
  347. argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
  348. irq_set = g_malloc0(argsz);
  349. irq_set->argsz = argsz;
  350. irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
  351. irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
  352. irq_set->start = 0;
  353. irq_set->count = vdev->nr_vectors;
  354. fds = (int32_t *)&irq_set->data;
  355. for (i = 0; i < vdev->nr_vectors; i++) {
  356. int fd = -1;
  357. /*
  358. * MSI vs MSI-X - The guest has direct access to MSI mask and pending
  359. * bits, therefore we always use the KVM signaling path when setup.
  360. * MSI-X mask and pending bits are emulated, so we want to use the
  361. * KVM signaling path only when configured and unmasked.
  362. */
  363. if (vdev->msi_vectors[i].use) {
  364. if (vdev->msi_vectors[i].virq < 0 ||
  365. (msix && msix_is_masked(&vdev->pdev, i))) {
  366. fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
  367. } else {
  368. fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
  369. }
  370. }
  371. fds[i] = fd;
  372. }
  373. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
  374. g_free(irq_set);
  375. return ret;
  376. }
  377. static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector,
  378. int vector_n, bool msix)
  379. {
  380. if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi)) {
  381. return;
  382. }
  383. vector->virq = kvm_irqchip_add_msi_route(&vfio_route_change,
  384. vector_n, &vdev->pdev);
  385. }
  386. static void vfio_connect_kvm_msi_virq(VFIOMSIVector *vector)
  387. {
  388. if (vector->virq < 0) {
  389. return;
  390. }
  391. if (event_notifier_init(&vector->kvm_interrupt, 0)) {
  392. goto fail_notifier;
  393. }
  394. if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
  395. NULL, vector->virq) < 0) {
  396. goto fail_kvm;
  397. }
  398. return;
  399. fail_kvm:
  400. event_notifier_cleanup(&vector->kvm_interrupt);
  401. fail_notifier:
  402. kvm_irqchip_release_virq(kvm_state, vector->virq);
  403. vector->virq = -1;
  404. }
  405. static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
  406. {
  407. kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
  408. vector->virq);
  409. kvm_irqchip_release_virq(kvm_state, vector->virq);
  410. vector->virq = -1;
  411. event_notifier_cleanup(&vector->kvm_interrupt);
  412. }
  413. static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg,
  414. PCIDevice *pdev)
  415. {
  416. kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg, pdev);
  417. kvm_irqchip_commit_routes(kvm_state);
  418. }
  419. static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
  420. MSIMessage *msg, IOHandler *handler)
  421. {
  422. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  423. VFIOMSIVector *vector;
  424. int ret;
  425. bool resizing = !!(vdev->nr_vectors < nr + 1);
  426. trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
  427. vector = &vdev->msi_vectors[nr];
  428. if (!vector->use) {
  429. vector->vdev = vdev;
  430. vector->virq = -1;
  431. if (event_notifier_init(&vector->interrupt, 0)) {
  432. error_report("vfio: Error: event_notifier_init failed");
  433. }
  434. vector->use = true;
  435. msix_vector_use(pdev, nr);
  436. }
  437. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  438. handler, NULL, vector);
  439. /*
  440. * Attempt to enable route through KVM irqchip,
  441. * default to userspace handling if unavailable.
  442. */
  443. if (vector->virq >= 0) {
  444. if (!msg) {
  445. vfio_remove_kvm_msi_virq(vector);
  446. } else {
  447. vfio_update_kvm_msi_virq(vector, *msg, pdev);
  448. }
  449. } else {
  450. if (msg) {
  451. if (vdev->defer_kvm_irq_routing) {
  452. vfio_add_kvm_msi_virq(vdev, vector, nr, true);
  453. } else {
  454. vfio_route_change = kvm_irqchip_begin_route_changes(kvm_state);
  455. vfio_add_kvm_msi_virq(vdev, vector, nr, true);
  456. kvm_irqchip_commit_route_changes(&vfio_route_change);
  457. vfio_connect_kvm_msi_virq(vector);
  458. }
  459. }
  460. }
  461. /*
  462. * When dynamic allocation is not supported, we don't want to have the
  463. * host allocate all possible MSI vectors for a device if they're not
  464. * in use, so we shutdown and incrementally increase them as needed.
  465. * nr_vectors represents the total number of vectors allocated.
  466. *
  467. * When dynamic allocation is supported, let the host only allocate
  468. * and enable a vector when it is in use in guest. nr_vectors represents
  469. * the upper bound of vectors being enabled (but not all of the ranges
  470. * is allocated or enabled).
  471. */
  472. if (resizing) {
  473. vdev->nr_vectors = nr + 1;
  474. }
  475. if (!vdev->defer_kvm_irq_routing) {
  476. if (vdev->msix->noresize && resizing) {
  477. vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
  478. ret = vfio_enable_vectors(vdev, true);
  479. if (ret) {
  480. error_report("vfio: failed to enable vectors, %d", ret);
  481. }
  482. } else {
  483. Error *err = NULL;
  484. int32_t fd;
  485. if (vector->virq >= 0) {
  486. fd = event_notifier_get_fd(&vector->kvm_interrupt);
  487. } else {
  488. fd = event_notifier_get_fd(&vector->interrupt);
  489. }
  490. if (!vfio_set_irq_signaling(&vdev->vbasedev,
  491. VFIO_PCI_MSIX_IRQ_INDEX, nr,
  492. VFIO_IRQ_SET_ACTION_TRIGGER, fd,
  493. &err)) {
  494. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  495. }
  496. }
  497. }
  498. /* Disable PBA emulation when nothing more is pending. */
  499. clear_bit(nr, vdev->msix->pending);
  500. if (find_first_bit(vdev->msix->pending,
  501. vdev->nr_vectors) == vdev->nr_vectors) {
  502. memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
  503. trace_vfio_msix_pba_disable(vdev->vbasedev.name);
  504. }
  505. return 0;
  506. }
  507. static int vfio_msix_vector_use(PCIDevice *pdev,
  508. unsigned int nr, MSIMessage msg)
  509. {
  510. return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
  511. }
  512. static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
  513. {
  514. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  515. VFIOMSIVector *vector = &vdev->msi_vectors[nr];
  516. trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
  517. /*
  518. * There are still old guests that mask and unmask vectors on every
  519. * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of
  520. * the KVM setup in place, simply switch VFIO to use the non-bypass
  521. * eventfd. We'll then fire the interrupt through QEMU and the MSI-X
  522. * core will mask the interrupt and set pending bits, allowing it to
  523. * be re-asserted on unmask. Nothing to do if already using QEMU mode.
  524. */
  525. if (vector->virq >= 0) {
  526. int32_t fd = event_notifier_get_fd(&vector->interrupt);
  527. Error *err = NULL;
  528. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX,
  529. nr, VFIO_IRQ_SET_ACTION_TRIGGER, fd,
  530. &err)) {
  531. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  532. }
  533. }
  534. }
  535. static void vfio_prepare_kvm_msi_virq_batch(VFIOPCIDevice *vdev)
  536. {
  537. assert(!vdev->defer_kvm_irq_routing);
  538. vdev->defer_kvm_irq_routing = true;
  539. vfio_route_change = kvm_irqchip_begin_route_changes(kvm_state);
  540. }
  541. static void vfio_commit_kvm_msi_virq_batch(VFIOPCIDevice *vdev)
  542. {
  543. int i;
  544. assert(vdev->defer_kvm_irq_routing);
  545. vdev->defer_kvm_irq_routing = false;
  546. kvm_irqchip_commit_route_changes(&vfio_route_change);
  547. for (i = 0; i < vdev->nr_vectors; i++) {
  548. vfio_connect_kvm_msi_virq(&vdev->msi_vectors[i]);
  549. }
  550. }
  551. static void vfio_msix_enable(VFIOPCIDevice *vdev)
  552. {
  553. int ret;
  554. vfio_disable_interrupts(vdev);
  555. vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->msix->entries);
  556. vdev->interrupt = VFIO_INT_MSIX;
  557. /*
  558. * Setting vector notifiers triggers synchronous vector-use
  559. * callbacks for each active vector. Deferring to commit the KVM
  560. * routes once rather than per vector provides a substantial
  561. * performance improvement.
  562. */
  563. vfio_prepare_kvm_msi_virq_batch(vdev);
  564. if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
  565. vfio_msix_vector_release, NULL)) {
  566. error_report("vfio: msix_set_vector_notifiers failed");
  567. }
  568. vfio_commit_kvm_msi_virq_batch(vdev);
  569. if (vdev->nr_vectors) {
  570. ret = vfio_enable_vectors(vdev, true);
  571. if (ret) {
  572. error_report("vfio: failed to enable vectors, %d", ret);
  573. }
  574. } else {
  575. /*
  576. * Some communication channels between VF & PF or PF & fw rely on the
  577. * physical state of the device and expect that enabling MSI-X from the
  578. * guest enables the same on the host. When our guest is Linux, the
  579. * guest driver call to pci_enable_msix() sets the enabling bit in the
  580. * MSI-X capability, but leaves the vector table masked. We therefore
  581. * can't rely on a vector_use callback (from request_irq() in the guest)
  582. * to switch the physical device into MSI-X mode because that may come a
  583. * long time after pci_enable_msix(). This code sets vector 0 with an
  584. * invalid fd to make the physical device MSI-X enabled, but with no
  585. * vectors enabled, just like the guest view.
  586. */
  587. ret = vfio_enable_msix_no_vec(vdev);
  588. if (ret) {
  589. error_report("vfio: failed to enable MSI-X, %d", ret);
  590. }
  591. }
  592. trace_vfio_msix_enable(vdev->vbasedev.name);
  593. }
  594. static void vfio_msi_enable(VFIOPCIDevice *vdev)
  595. {
  596. int ret, i;
  597. vfio_disable_interrupts(vdev);
  598. vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
  599. retry:
  600. /*
  601. * Setting vector notifiers needs to enable route for each vector.
  602. * Deferring to commit the KVM routes once rather than per vector
  603. * provides a substantial performance improvement.
  604. */
  605. vfio_prepare_kvm_msi_virq_batch(vdev);
  606. vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->nr_vectors);
  607. for (i = 0; i < vdev->nr_vectors; i++) {
  608. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  609. vector->vdev = vdev;
  610. vector->virq = -1;
  611. vector->use = true;
  612. if (event_notifier_init(&vector->interrupt, 0)) {
  613. error_report("vfio: Error: event_notifier_init failed");
  614. }
  615. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  616. vfio_msi_interrupt, NULL, vector);
  617. /*
  618. * Attempt to enable route through KVM irqchip,
  619. * default to userspace handling if unavailable.
  620. */
  621. vfio_add_kvm_msi_virq(vdev, vector, i, false);
  622. }
  623. vfio_commit_kvm_msi_virq_batch(vdev);
  624. /* Set interrupt type prior to possible interrupts */
  625. vdev->interrupt = VFIO_INT_MSI;
  626. ret = vfio_enable_vectors(vdev, false);
  627. if (ret) {
  628. if (ret < 0) {
  629. error_report("vfio: Error: Failed to setup MSI fds: %m");
  630. } else {
  631. error_report("vfio: Error: Failed to enable %d "
  632. "MSI vectors, retry with %d", vdev->nr_vectors, ret);
  633. }
  634. vfio_msi_disable_common(vdev);
  635. if (ret > 0) {
  636. vdev->nr_vectors = ret;
  637. goto retry;
  638. }
  639. /*
  640. * Failing to setup MSI doesn't really fall within any specification.
  641. * Let's try leaving interrupts disabled and hope the guest figures
  642. * out to fall back to INTx for this device.
  643. */
  644. error_report("vfio: Error: Failed to enable MSI");
  645. return;
  646. }
  647. trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);
  648. }
  649. static void vfio_msi_disable_common(VFIOPCIDevice *vdev)
  650. {
  651. int i;
  652. for (i = 0; i < vdev->nr_vectors; i++) {
  653. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  654. if (vdev->msi_vectors[i].use) {
  655. if (vector->virq >= 0) {
  656. vfio_remove_kvm_msi_virq(vector);
  657. }
  658. qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
  659. NULL, NULL, NULL);
  660. event_notifier_cleanup(&vector->interrupt);
  661. }
  662. }
  663. g_free(vdev->msi_vectors);
  664. vdev->msi_vectors = NULL;
  665. vdev->nr_vectors = 0;
  666. vdev->interrupt = VFIO_INT_NONE;
  667. }
  668. static void vfio_msix_disable(VFIOPCIDevice *vdev)
  669. {
  670. Error *err = NULL;
  671. int i;
  672. msix_unset_vector_notifiers(&vdev->pdev);
  673. /*
  674. * MSI-X will only release vectors if MSI-X is still enabled on the
  675. * device, check through the rest and release it ourselves if necessary.
  676. */
  677. for (i = 0; i < vdev->nr_vectors; i++) {
  678. if (vdev->msi_vectors[i].use) {
  679. vfio_msix_vector_release(&vdev->pdev, i);
  680. msix_vector_unuse(&vdev->pdev, i);
  681. }
  682. }
  683. /*
  684. * Always clear MSI-X IRQ index. A PF device could have enabled
  685. * MSI-X with no vectors. See vfio_msix_enable().
  686. */
  687. vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
  688. vfio_msi_disable_common(vdev);
  689. if (!vfio_intx_enable(vdev, &err)) {
  690. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  691. }
  692. memset(vdev->msix->pending, 0,
  693. BITS_TO_LONGS(vdev->msix->entries) * sizeof(unsigned long));
  694. trace_vfio_msix_disable(vdev->vbasedev.name);
  695. }
  696. static void vfio_msi_disable(VFIOPCIDevice *vdev)
  697. {
  698. Error *err = NULL;
  699. vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
  700. vfio_msi_disable_common(vdev);
  701. vfio_intx_enable(vdev, &err);
  702. if (err) {
  703. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  704. }
  705. trace_vfio_msi_disable(vdev->vbasedev.name);
  706. }
  707. static void vfio_update_msi(VFIOPCIDevice *vdev)
  708. {
  709. int i;
  710. for (i = 0; i < vdev->nr_vectors; i++) {
  711. VFIOMSIVector *vector = &vdev->msi_vectors[i];
  712. MSIMessage msg;
  713. if (!vector->use || vector->virq < 0) {
  714. continue;
  715. }
  716. msg = msi_get_message(&vdev->pdev, i);
  717. vfio_update_kvm_msi_virq(vector, msg, &vdev->pdev);
  718. }
  719. }
  720. static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
  721. {
  722. g_autofree struct vfio_region_info *reg_info = NULL;
  723. uint64_t size;
  724. off_t off = 0;
  725. ssize_t bytes;
  726. if (vfio_get_region_info(&vdev->vbasedev,
  727. VFIO_PCI_ROM_REGION_INDEX, &reg_info)) {
  728. error_report("vfio: Error getting ROM info: %m");
  729. return;
  730. }
  731. trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info->size,
  732. (unsigned long)reg_info->offset,
  733. (unsigned long)reg_info->flags);
  734. vdev->rom_size = size = reg_info->size;
  735. vdev->rom_offset = reg_info->offset;
  736. if (!vdev->rom_size) {
  737. vdev->rom_read_failed = true;
  738. error_report("vfio-pci: Cannot read device rom at "
  739. "%s", vdev->vbasedev.name);
  740. error_printf("Device option ROM contents are probably invalid "
  741. "(check dmesg).\nSkip option ROM probe with rombar=0, "
  742. "or load from file with romfile=\n");
  743. return;
  744. }
  745. vdev->rom = g_malloc(size);
  746. memset(vdev->rom, 0xff, size);
  747. while (size) {
  748. bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
  749. size, vdev->rom_offset + off);
  750. if (bytes == 0) {
  751. break;
  752. } else if (bytes > 0) {
  753. off += bytes;
  754. size -= bytes;
  755. } else {
  756. if (errno == EINTR || errno == EAGAIN) {
  757. continue;
  758. }
  759. error_report("vfio: Error reading device ROM: %m");
  760. break;
  761. }
  762. }
  763. /*
  764. * Test the ROM signature against our device, if the vendor is correct
  765. * but the device ID doesn't match, store the correct device ID and
  766. * recompute the checksum. Intel IGD devices need this and are known
  767. * to have bogus checksums so we can't simply adjust the checksum.
  768. */
  769. if (pci_get_word(vdev->rom) == 0xaa55 &&
  770. pci_get_word(vdev->rom + 0x18) + 8 < vdev->rom_size &&
  771. !memcmp(vdev->rom + pci_get_word(vdev->rom + 0x18), "PCIR", 4)) {
  772. uint16_t vid, did;
  773. vid = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 4);
  774. did = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6);
  775. if (vid == vdev->vendor_id && did != vdev->device_id) {
  776. int i;
  777. uint8_t csum, *data = vdev->rom;
  778. pci_set_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6,
  779. vdev->device_id);
  780. data[6] = 0;
  781. for (csum = 0, i = 0; i < vdev->rom_size; i++) {
  782. csum += data[i];
  783. }
  784. data[6] = -csum;
  785. }
  786. }
  787. }
  788. static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
  789. {
  790. VFIOPCIDevice *vdev = opaque;
  791. union {
  792. uint8_t byte;
  793. uint16_t word;
  794. uint32_t dword;
  795. uint64_t qword;
  796. } val;
  797. uint64_t data = 0;
  798. /* Load the ROM lazily when the guest tries to read it */
  799. if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
  800. vfio_pci_load_rom(vdev);
  801. }
  802. memcpy(&val, vdev->rom + addr,
  803. (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
  804. switch (size) {
  805. case 1:
  806. data = val.byte;
  807. break;
  808. case 2:
  809. data = le16_to_cpu(val.word);
  810. break;
  811. case 4:
  812. data = le32_to_cpu(val.dword);
  813. break;
  814. default:
  815. hw_error("vfio: unsupported read size, %d bytes\n", size);
  816. break;
  817. }
  818. trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
  819. return data;
  820. }
  821. static void vfio_rom_write(void *opaque, hwaddr addr,
  822. uint64_t data, unsigned size)
  823. {
  824. }
  825. static const MemoryRegionOps vfio_rom_ops = {
  826. .read = vfio_rom_read,
  827. .write = vfio_rom_write,
  828. .endianness = DEVICE_LITTLE_ENDIAN,
  829. };
  830. static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
  831. {
  832. uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
  833. off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
  834. char *name;
  835. int fd = vdev->vbasedev.fd;
  836. if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
  837. /* Since pci handles romfile, just print a message and return */
  838. if (vfio_opt_rom_in_denylist(vdev) && vdev->pdev.romfile) {
  839. warn_report("Device at %s is known to cause system instability"
  840. " issues during option rom execution",
  841. vdev->vbasedev.name);
  842. error_printf("Proceeding anyway since user specified romfile\n");
  843. }
  844. return;
  845. }
  846. /*
  847. * Use the same size ROM BAR as the physical device. The contents
  848. * will get filled in later when the guest tries to read it.
  849. */
  850. if (pread(fd, &orig, 4, offset) != 4 ||
  851. pwrite(fd, &size, 4, offset) != 4 ||
  852. pread(fd, &size, 4, offset) != 4 ||
  853. pwrite(fd, &orig, 4, offset) != 4) {
  854. error_report("%s(%s) failed: %m", __func__, vdev->vbasedev.name);
  855. return;
  856. }
  857. size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
  858. if (!size) {
  859. return;
  860. }
  861. if (vfio_opt_rom_in_denylist(vdev)) {
  862. if (vdev->pdev.rom_bar > 0) {
  863. warn_report("Device at %s is known to cause system instability"
  864. " issues during option rom execution",
  865. vdev->vbasedev.name);
  866. error_printf("Proceeding anyway since user specified"
  867. " positive value for rombar\n");
  868. } else {
  869. warn_report("Rom loading for device at %s has been disabled"
  870. " due to system instability issues",
  871. vdev->vbasedev.name);
  872. error_printf("Specify rombar=1 or romfile to force\n");
  873. return;
  874. }
  875. }
  876. trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
  877. name = g_strdup_printf("vfio[%s].rom", vdev->vbasedev.name);
  878. memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
  879. &vfio_rom_ops, vdev, name, size);
  880. g_free(name);
  881. pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
  882. PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
  883. vdev->rom_read_failed = false;
  884. }
  885. void vfio_vga_write(void *opaque, hwaddr addr,
  886. uint64_t data, unsigned size)
  887. {
  888. VFIOVGARegion *region = opaque;
  889. VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
  890. union {
  891. uint8_t byte;
  892. uint16_t word;
  893. uint32_t dword;
  894. uint64_t qword;
  895. } buf;
  896. off_t offset = vga->fd_offset + region->offset + addr;
  897. switch (size) {
  898. case 1:
  899. buf.byte = data;
  900. break;
  901. case 2:
  902. buf.word = cpu_to_le16(data);
  903. break;
  904. case 4:
  905. buf.dword = cpu_to_le32(data);
  906. break;
  907. default:
  908. hw_error("vfio: unsupported write size, %d bytes", size);
  909. break;
  910. }
  911. if (pwrite(vga->fd, &buf, size, offset) != size) {
  912. error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
  913. __func__, region->offset + addr, data, size);
  914. }
  915. trace_vfio_vga_write(region->offset + addr, data, size);
  916. }
  917. uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
  918. {
  919. VFIOVGARegion *region = opaque;
  920. VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
  921. union {
  922. uint8_t byte;
  923. uint16_t word;
  924. uint32_t dword;
  925. uint64_t qword;
  926. } buf;
  927. uint64_t data = 0;
  928. off_t offset = vga->fd_offset + region->offset + addr;
  929. if (pread(vga->fd, &buf, size, offset) != size) {
  930. error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
  931. __func__, region->offset + addr, size);
  932. return (uint64_t)-1;
  933. }
  934. switch (size) {
  935. case 1:
  936. data = buf.byte;
  937. break;
  938. case 2:
  939. data = le16_to_cpu(buf.word);
  940. break;
  941. case 4:
  942. data = le32_to_cpu(buf.dword);
  943. break;
  944. default:
  945. hw_error("vfio: unsupported read size, %d bytes", size);
  946. break;
  947. }
  948. trace_vfio_vga_read(region->offset + addr, size, data);
  949. return data;
  950. }
  951. static const MemoryRegionOps vfio_vga_ops = {
  952. .read = vfio_vga_read,
  953. .write = vfio_vga_write,
  954. .endianness = DEVICE_LITTLE_ENDIAN,
  955. };
  956. /*
  957. * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page
  958. * size if the BAR is in an exclusive page in host so that we could map
  959. * this BAR to guest. But this sub-page BAR may not occupy an exclusive
  960. * page in guest. So we should set the priority of the expanded memory
  961. * region to zero in case of overlap with BARs which share the same page
  962. * with the sub-page BAR in guest. Besides, we should also recover the
  963. * size of this sub-page BAR when its base address is changed in guest
  964. * and not page aligned any more.
  965. */
  966. static void vfio_sub_page_bar_update_mapping(PCIDevice *pdev, int bar)
  967. {
  968. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  969. VFIORegion *region = &vdev->bars[bar].region;
  970. MemoryRegion *mmap_mr, *region_mr, *base_mr;
  971. PCIIORegion *r;
  972. pcibus_t bar_addr;
  973. uint64_t size = region->size;
  974. /* Make sure that the whole region is allowed to be mmapped */
  975. if (region->nr_mmaps != 1 || !region->mmaps[0].mmap ||
  976. region->mmaps[0].size != region->size) {
  977. return;
  978. }
  979. r = &pdev->io_regions[bar];
  980. bar_addr = r->addr;
  981. base_mr = vdev->bars[bar].mr;
  982. region_mr = region->mem;
  983. mmap_mr = &region->mmaps[0].mem;
  984. /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */
  985. if (bar_addr != PCI_BAR_UNMAPPED &&
  986. !(bar_addr & ~qemu_real_host_page_mask())) {
  987. size = qemu_real_host_page_size();
  988. }
  989. memory_region_transaction_begin();
  990. if (vdev->bars[bar].size < size) {
  991. memory_region_set_size(base_mr, size);
  992. }
  993. memory_region_set_size(region_mr, size);
  994. memory_region_set_size(mmap_mr, size);
  995. if (size != vdev->bars[bar].size && memory_region_is_mapped(base_mr)) {
  996. memory_region_del_subregion(r->address_space, base_mr);
  997. memory_region_add_subregion_overlap(r->address_space,
  998. bar_addr, base_mr, 0);
  999. }
  1000. memory_region_transaction_commit();
  1001. }
  1002. /*
  1003. * PCI config space
  1004. */
  1005. uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
  1006. {
  1007. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  1008. uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
  1009. memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
  1010. emu_bits = le32_to_cpu(emu_bits);
  1011. if (emu_bits) {
  1012. emu_val = pci_default_read_config(pdev, addr, len);
  1013. }
  1014. if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
  1015. ssize_t ret;
  1016. ret = pread(vdev->vbasedev.fd, &phys_val, len,
  1017. vdev->config_offset + addr);
  1018. if (ret != len) {
  1019. error_report("%s(%s, 0x%x, 0x%x) failed: %m",
  1020. __func__, vdev->vbasedev.name, addr, len);
  1021. return -errno;
  1022. }
  1023. phys_val = le32_to_cpu(phys_val);
  1024. }
  1025. val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
  1026. trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
  1027. return val;
  1028. }
  1029. void vfio_pci_write_config(PCIDevice *pdev,
  1030. uint32_t addr, uint32_t val, int len)
  1031. {
  1032. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  1033. uint32_t val_le = cpu_to_le32(val);
  1034. trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
  1035. /* Write everything to VFIO, let it filter out what we can't write */
  1036. if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
  1037. != len) {
  1038. error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %m",
  1039. __func__, vdev->vbasedev.name, addr, val, len);
  1040. }
  1041. /* MSI/MSI-X Enabling/Disabling */
  1042. if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
  1043. ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
  1044. int is_enabled, was_enabled = msi_enabled(pdev);
  1045. pci_default_write_config(pdev, addr, val, len);
  1046. is_enabled = msi_enabled(pdev);
  1047. if (!was_enabled) {
  1048. if (is_enabled) {
  1049. vfio_msi_enable(vdev);
  1050. }
  1051. } else {
  1052. if (!is_enabled) {
  1053. vfio_msi_disable(vdev);
  1054. } else {
  1055. vfio_update_msi(vdev);
  1056. }
  1057. }
  1058. } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
  1059. ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
  1060. int is_enabled, was_enabled = msix_enabled(pdev);
  1061. pci_default_write_config(pdev, addr, val, len);
  1062. is_enabled = msix_enabled(pdev);
  1063. if (!was_enabled && is_enabled) {
  1064. vfio_msix_enable(vdev);
  1065. } else if (was_enabled && !is_enabled) {
  1066. vfio_msix_disable(vdev);
  1067. }
  1068. } else if (ranges_overlap(addr, len, PCI_BASE_ADDRESS_0, 24) ||
  1069. range_covers_byte(addr, len, PCI_COMMAND)) {
  1070. pcibus_t old_addr[PCI_NUM_REGIONS - 1];
  1071. int bar;
  1072. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  1073. old_addr[bar] = pdev->io_regions[bar].addr;
  1074. }
  1075. pci_default_write_config(pdev, addr, val, len);
  1076. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  1077. if (old_addr[bar] != pdev->io_regions[bar].addr &&
  1078. vdev->bars[bar].region.size > 0 &&
  1079. vdev->bars[bar].region.size < qemu_real_host_page_size()) {
  1080. vfio_sub_page_bar_update_mapping(pdev, bar);
  1081. }
  1082. }
  1083. } else {
  1084. /* Write everything to QEMU to keep emulated bits correct */
  1085. pci_default_write_config(pdev, addr, val, len);
  1086. }
  1087. }
  1088. /*
  1089. * Interrupt setup
  1090. */
  1091. static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
  1092. {
  1093. /*
  1094. * More complicated than it looks. Disabling MSI/X transitions the
  1095. * device to INTx mode (if supported). Therefore we need to first
  1096. * disable MSI/X and then cleanup by disabling INTx.
  1097. */
  1098. if (vdev->interrupt == VFIO_INT_MSIX) {
  1099. vfio_msix_disable(vdev);
  1100. } else if (vdev->interrupt == VFIO_INT_MSI) {
  1101. vfio_msi_disable(vdev);
  1102. }
  1103. if (vdev->interrupt == VFIO_INT_INTx) {
  1104. vfio_intx_disable(vdev);
  1105. }
  1106. }
  1107. static bool vfio_msi_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
  1108. {
  1109. uint16_t ctrl;
  1110. bool msi_64bit, msi_maskbit;
  1111. int ret, entries;
  1112. Error *err = NULL;
  1113. if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
  1114. vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
  1115. error_setg_errno(errp, errno, "failed reading MSI PCI_CAP_FLAGS");
  1116. return false;
  1117. }
  1118. ctrl = le16_to_cpu(ctrl);
  1119. msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
  1120. msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
  1121. entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
  1122. trace_vfio_msi_setup(vdev->vbasedev.name, pos);
  1123. ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit, &err);
  1124. if (ret < 0) {
  1125. if (ret == -ENOTSUP) {
  1126. return true;
  1127. }
  1128. error_propagate_prepend(errp, err, "msi_init failed: ");
  1129. return false;
  1130. }
  1131. vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
  1132. return true;
  1133. }
  1134. static void vfio_pci_fixup_msix_region(VFIOPCIDevice *vdev)
  1135. {
  1136. off_t start, end;
  1137. VFIORegion *region = &vdev->bars[vdev->msix->table_bar].region;
  1138. /*
  1139. * If the host driver allows mapping of a MSIX data, we are going to
  1140. * do map the entire BAR and emulate MSIX table on top of that.
  1141. */
  1142. if (vfio_has_region_cap(&vdev->vbasedev, region->nr,
  1143. VFIO_REGION_INFO_CAP_MSIX_MAPPABLE)) {
  1144. return;
  1145. }
  1146. /*
  1147. * We expect to find a single mmap covering the whole BAR, anything else
  1148. * means it's either unsupported or already setup.
  1149. */
  1150. if (region->nr_mmaps != 1 || region->mmaps[0].offset ||
  1151. region->size != region->mmaps[0].size) {
  1152. return;
  1153. }
  1154. /* MSI-X table start and end aligned to host page size */
  1155. start = vdev->msix->table_offset & qemu_real_host_page_mask();
  1156. end = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
  1157. (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
  1158. /*
  1159. * Does the MSI-X table cover the beginning of the BAR? The whole BAR?
  1160. * NB - Host page size is necessarily a power of two and so is the PCI
  1161. * BAR (not counting EA yet), therefore if we have host page aligned
  1162. * @start and @end, then any remainder of the BAR before or after those
  1163. * must be at least host page sized and therefore mmap'able.
  1164. */
  1165. if (!start) {
  1166. if (end >= region->size) {
  1167. region->nr_mmaps = 0;
  1168. g_free(region->mmaps);
  1169. region->mmaps = NULL;
  1170. trace_vfio_msix_fixup(vdev->vbasedev.name,
  1171. vdev->msix->table_bar, 0, 0);
  1172. } else {
  1173. region->mmaps[0].offset = end;
  1174. region->mmaps[0].size = region->size - end;
  1175. trace_vfio_msix_fixup(vdev->vbasedev.name,
  1176. vdev->msix->table_bar, region->mmaps[0].offset,
  1177. region->mmaps[0].offset + region->mmaps[0].size);
  1178. }
  1179. /* Maybe it's aligned at the end of the BAR */
  1180. } else if (end >= region->size) {
  1181. region->mmaps[0].size = start;
  1182. trace_vfio_msix_fixup(vdev->vbasedev.name,
  1183. vdev->msix->table_bar, region->mmaps[0].offset,
  1184. region->mmaps[0].offset + region->mmaps[0].size);
  1185. /* Otherwise it must split the BAR */
  1186. } else {
  1187. region->nr_mmaps = 2;
  1188. region->mmaps = g_renew(VFIOMmap, region->mmaps, 2);
  1189. memcpy(&region->mmaps[1], &region->mmaps[0], sizeof(VFIOMmap));
  1190. region->mmaps[0].size = start;
  1191. trace_vfio_msix_fixup(vdev->vbasedev.name,
  1192. vdev->msix->table_bar, region->mmaps[0].offset,
  1193. region->mmaps[0].offset + region->mmaps[0].size);
  1194. region->mmaps[1].offset = end;
  1195. region->mmaps[1].size = region->size - end;
  1196. trace_vfio_msix_fixup(vdev->vbasedev.name,
  1197. vdev->msix->table_bar, region->mmaps[1].offset,
  1198. region->mmaps[1].offset + region->mmaps[1].size);
  1199. }
  1200. }
  1201. static bool vfio_pci_relocate_msix(VFIOPCIDevice *vdev, Error **errp)
  1202. {
  1203. int target_bar = -1;
  1204. size_t msix_sz;
  1205. if (!vdev->msix || vdev->msix_relo == OFF_AUTO_PCIBAR_OFF) {
  1206. return true;
  1207. }
  1208. /* The actual minimum size of MSI-X structures */
  1209. msix_sz = (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE) +
  1210. (QEMU_ALIGN_UP(vdev->msix->entries, 64) / 8);
  1211. /* Round up to host pages, we don't want to share a page */
  1212. msix_sz = REAL_HOST_PAGE_ALIGN(msix_sz);
  1213. /* PCI BARs must be a power of 2 */
  1214. msix_sz = pow2ceil(msix_sz);
  1215. if (vdev->msix_relo == OFF_AUTO_PCIBAR_AUTO) {
  1216. /*
  1217. * TODO: Lookup table for known devices.
  1218. *
  1219. * Logically we might use an algorithm here to select the BAR adding
  1220. * the least additional MMIO space, but we cannot programmatically
  1221. * predict the driver dependency on BAR ordering or sizing, therefore
  1222. * 'auto' becomes a lookup for combinations reported to work.
  1223. */
  1224. if (target_bar < 0) {
  1225. error_setg(errp, "No automatic MSI-X relocation available for "
  1226. "device %04x:%04x", vdev->vendor_id, vdev->device_id);
  1227. return false;
  1228. }
  1229. } else {
  1230. target_bar = (int)(vdev->msix_relo - OFF_AUTO_PCIBAR_BAR0);
  1231. }
  1232. /* I/O port BARs cannot host MSI-X structures */
  1233. if (vdev->bars[target_bar].ioport) {
  1234. error_setg(errp, "Invalid MSI-X relocation BAR %d, "
  1235. "I/O port BAR", target_bar);
  1236. return false;
  1237. }
  1238. /* Cannot use a BAR in the "shadow" of a 64-bit BAR */
  1239. if (!vdev->bars[target_bar].size &&
  1240. target_bar > 0 && vdev->bars[target_bar - 1].mem64) {
  1241. error_setg(errp, "Invalid MSI-X relocation BAR %d, "
  1242. "consumed by 64-bit BAR %d", target_bar, target_bar - 1);
  1243. return false;
  1244. }
  1245. /* 2GB max size for 32-bit BARs, cannot double if already > 1G */
  1246. if (vdev->bars[target_bar].size > 1 * GiB &&
  1247. !vdev->bars[target_bar].mem64) {
  1248. error_setg(errp, "Invalid MSI-X relocation BAR %d, "
  1249. "no space to extend 32-bit BAR", target_bar);
  1250. return false;
  1251. }
  1252. /*
  1253. * If adding a new BAR, test if we can make it 64bit. We make it
  1254. * prefetchable since QEMU MSI-X emulation has no read side effects
  1255. * and doing so makes mapping more flexible.
  1256. */
  1257. if (!vdev->bars[target_bar].size) {
  1258. if (target_bar < (PCI_ROM_SLOT - 1) &&
  1259. !vdev->bars[target_bar + 1].size) {
  1260. vdev->bars[target_bar].mem64 = true;
  1261. vdev->bars[target_bar].type = PCI_BASE_ADDRESS_MEM_TYPE_64;
  1262. }
  1263. vdev->bars[target_bar].type |= PCI_BASE_ADDRESS_MEM_PREFETCH;
  1264. vdev->bars[target_bar].size = msix_sz;
  1265. vdev->msix->table_offset = 0;
  1266. } else {
  1267. vdev->bars[target_bar].size = MAX(vdev->bars[target_bar].size * 2,
  1268. msix_sz * 2);
  1269. /*
  1270. * Due to above size calc, MSI-X always starts halfway into the BAR,
  1271. * which will always be a separate host page.
  1272. */
  1273. vdev->msix->table_offset = vdev->bars[target_bar].size / 2;
  1274. }
  1275. vdev->msix->table_bar = target_bar;
  1276. vdev->msix->pba_bar = target_bar;
  1277. /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */
  1278. vdev->msix->pba_offset = vdev->msix->table_offset +
  1279. (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE);
  1280. trace_vfio_msix_relo(vdev->vbasedev.name,
  1281. vdev->msix->table_bar, vdev->msix->table_offset);
  1282. return true;
  1283. }
  1284. /*
  1285. * We don't have any control over how pci_add_capability() inserts
  1286. * capabilities into the chain. In order to setup MSI-X we need a
  1287. * MemoryRegion for the BAR. In order to setup the BAR and not
  1288. * attempt to mmap the MSI-X table area, which VFIO won't allow, we
  1289. * need to first look for where the MSI-X table lives. So we
  1290. * unfortunately split MSI-X setup across two functions.
  1291. */
  1292. static bool vfio_msix_early_setup(VFIOPCIDevice *vdev, Error **errp)
  1293. {
  1294. uint8_t pos;
  1295. uint16_t ctrl;
  1296. uint32_t table, pba;
  1297. int ret, fd = vdev->vbasedev.fd;
  1298. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
  1299. .index = VFIO_PCI_MSIX_IRQ_INDEX };
  1300. VFIOMSIXInfo *msix;
  1301. pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
  1302. if (!pos) {
  1303. return true;
  1304. }
  1305. if (pread(fd, &ctrl, sizeof(ctrl),
  1306. vdev->config_offset + pos + PCI_MSIX_FLAGS) != sizeof(ctrl)) {
  1307. error_setg_errno(errp, errno, "failed to read PCI MSIX FLAGS");
  1308. return false;
  1309. }
  1310. if (pread(fd, &table, sizeof(table),
  1311. vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
  1312. error_setg_errno(errp, errno, "failed to read PCI MSIX TABLE");
  1313. return false;
  1314. }
  1315. if (pread(fd, &pba, sizeof(pba),
  1316. vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
  1317. error_setg_errno(errp, errno, "failed to read PCI MSIX PBA");
  1318. return false;
  1319. }
  1320. ctrl = le16_to_cpu(ctrl);
  1321. table = le32_to_cpu(table);
  1322. pba = le32_to_cpu(pba);
  1323. msix = g_malloc0(sizeof(*msix));
  1324. msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
  1325. msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
  1326. msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
  1327. msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
  1328. msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
  1329. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
  1330. if (ret < 0) {
  1331. error_setg_errno(errp, -ret, "failed to get MSI-X irq info");
  1332. g_free(msix);
  1333. return false;
  1334. }
  1335. msix->noresize = !!(irq_info.flags & VFIO_IRQ_INFO_NORESIZE);
  1336. /*
  1337. * Test the size of the pba_offset variable and catch if it extends outside
  1338. * of the specified BAR. If it is the case, we need to apply a hardware
  1339. * specific quirk if the device is known or we have a broken configuration.
  1340. */
  1341. if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) {
  1342. /*
  1343. * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
  1344. * adapters. The T5 hardware returns an incorrect value of 0x8000 for
  1345. * the VF PBA offset while the BAR itself is only 8k. The correct value
  1346. * is 0x1000, so we hard code that here.
  1347. */
  1348. if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO &&
  1349. (vdev->device_id & 0xff00) == 0x5800) {
  1350. msix->pba_offset = 0x1000;
  1351. /*
  1352. * BAIDU KUNLUN Virtual Function devices for KUNLUN AI processor
  1353. * return an incorrect value of 0x460000 for the VF PBA offset while
  1354. * the BAR itself is only 0x10000. The correct value is 0xb400.
  1355. */
  1356. } else if (vfio_pci_is(vdev, PCI_VENDOR_ID_BAIDU,
  1357. PCI_DEVICE_ID_KUNLUN_VF)) {
  1358. msix->pba_offset = 0xb400;
  1359. } else if (vdev->msix_relo == OFF_AUTO_PCIBAR_OFF) {
  1360. error_setg(errp, "hardware reports invalid configuration, "
  1361. "MSIX PBA outside of specified BAR");
  1362. g_free(msix);
  1363. return false;
  1364. }
  1365. }
  1366. trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar,
  1367. msix->table_offset, msix->entries,
  1368. msix->noresize);
  1369. vdev->msix = msix;
  1370. vfio_pci_fixup_msix_region(vdev);
  1371. return vfio_pci_relocate_msix(vdev, errp);
  1372. }
  1373. static bool vfio_msix_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
  1374. {
  1375. int ret;
  1376. Error *err = NULL;
  1377. vdev->msix->pending = g_new0(unsigned long,
  1378. BITS_TO_LONGS(vdev->msix->entries));
  1379. ret = msix_init(&vdev->pdev, vdev->msix->entries,
  1380. vdev->bars[vdev->msix->table_bar].mr,
  1381. vdev->msix->table_bar, vdev->msix->table_offset,
  1382. vdev->bars[vdev->msix->pba_bar].mr,
  1383. vdev->msix->pba_bar, vdev->msix->pba_offset, pos,
  1384. &err);
  1385. if (ret < 0) {
  1386. if (ret == -ENOTSUP) {
  1387. warn_report_err(err);
  1388. return true;
  1389. }
  1390. error_propagate(errp, err);
  1391. return false;
  1392. }
  1393. /*
  1394. * The PCI spec suggests that devices provide additional alignment for
  1395. * MSI-X structures and avoid overlapping non-MSI-X related registers.
  1396. * For an assigned device, this hopefully means that emulation of MSI-X
  1397. * structures does not affect the performance of the device. If devices
  1398. * fail to provide that alignment, a significant performance penalty may
  1399. * result, for instance Mellanox MT27500 VFs:
  1400. * http://www.spinics.net/lists/kvm/msg125881.html
  1401. *
  1402. * The PBA is simply not that important for such a serious regression and
  1403. * most drivers do not appear to look at it. The solution for this is to
  1404. * disable the PBA MemoryRegion unless it's being used. We disable it
  1405. * here and only enable it if a masked vector fires through QEMU. As the
  1406. * vector-use notifier is called, which occurs on unmask, we test whether
  1407. * PBA emulation is needed and again disable if not.
  1408. */
  1409. memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
  1410. /*
  1411. * The emulated machine may provide a paravirt interface for MSIX setup
  1412. * so it is not strictly necessary to emulate MSIX here. This becomes
  1413. * helpful when frequently accessed MMIO registers are located in
  1414. * subpages adjacent to the MSIX table but the MSIX data containing page
  1415. * cannot be mapped because of a host page size bigger than the MSIX table
  1416. * alignment.
  1417. */
  1418. if (object_property_get_bool(OBJECT(qdev_get_machine()),
  1419. "vfio-no-msix-emulation", NULL)) {
  1420. memory_region_set_enabled(&vdev->pdev.msix_table_mmio, false);
  1421. }
  1422. return true;
  1423. }
  1424. static void vfio_teardown_msi(VFIOPCIDevice *vdev)
  1425. {
  1426. msi_uninit(&vdev->pdev);
  1427. if (vdev->msix) {
  1428. msix_uninit(&vdev->pdev,
  1429. vdev->bars[vdev->msix->table_bar].mr,
  1430. vdev->bars[vdev->msix->pba_bar].mr);
  1431. g_free(vdev->msix->pending);
  1432. }
  1433. }
  1434. /*
  1435. * Resource setup
  1436. */
  1437. static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
  1438. {
  1439. int i;
  1440. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1441. vfio_region_mmaps_set_enabled(&vdev->bars[i].region, enabled);
  1442. }
  1443. }
  1444. static void vfio_bar_prepare(VFIOPCIDevice *vdev, int nr)
  1445. {
  1446. VFIOBAR *bar = &vdev->bars[nr];
  1447. uint32_t pci_bar;
  1448. int ret;
  1449. /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
  1450. if (!bar->region.size) {
  1451. return;
  1452. }
  1453. /* Determine what type of BAR this is for registration */
  1454. ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
  1455. vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
  1456. if (ret != sizeof(pci_bar)) {
  1457. error_report("vfio: Failed to read BAR %d (%m)", nr);
  1458. return;
  1459. }
  1460. pci_bar = le32_to_cpu(pci_bar);
  1461. bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
  1462. bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
  1463. bar->type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
  1464. ~PCI_BASE_ADDRESS_MEM_MASK);
  1465. bar->size = bar->region.size;
  1466. }
  1467. static void vfio_bars_prepare(VFIOPCIDevice *vdev)
  1468. {
  1469. int i;
  1470. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1471. vfio_bar_prepare(vdev, i);
  1472. }
  1473. }
  1474. static void vfio_bar_register(VFIOPCIDevice *vdev, int nr)
  1475. {
  1476. VFIOBAR *bar = &vdev->bars[nr];
  1477. char *name;
  1478. if (!bar->size) {
  1479. return;
  1480. }
  1481. bar->mr = g_new0(MemoryRegion, 1);
  1482. name = g_strdup_printf("%s base BAR %d", vdev->vbasedev.name, nr);
  1483. memory_region_init_io(bar->mr, OBJECT(vdev), NULL, NULL, name, bar->size);
  1484. g_free(name);
  1485. if (bar->region.size) {
  1486. memory_region_add_subregion(bar->mr, 0, bar->region.mem);
  1487. if (vfio_region_mmap(&bar->region)) {
  1488. error_report("Failed to mmap %s BAR %d. Performance may be slow",
  1489. vdev->vbasedev.name, nr);
  1490. }
  1491. }
  1492. pci_register_bar(&vdev->pdev, nr, bar->type, bar->mr);
  1493. }
  1494. static void vfio_bars_register(VFIOPCIDevice *vdev)
  1495. {
  1496. int i;
  1497. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1498. vfio_bar_register(vdev, i);
  1499. }
  1500. }
  1501. static void vfio_bars_exit(VFIOPCIDevice *vdev)
  1502. {
  1503. int i;
  1504. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1505. VFIOBAR *bar = &vdev->bars[i];
  1506. vfio_bar_quirk_exit(vdev, i);
  1507. vfio_region_exit(&bar->region);
  1508. if (bar->region.size) {
  1509. memory_region_del_subregion(bar->mr, bar->region.mem);
  1510. }
  1511. }
  1512. if (vdev->vga) {
  1513. pci_unregister_vga(&vdev->pdev);
  1514. vfio_vga_quirk_exit(vdev);
  1515. }
  1516. }
  1517. static void vfio_bars_finalize(VFIOPCIDevice *vdev)
  1518. {
  1519. int i;
  1520. for (i = 0; i < PCI_ROM_SLOT; i++) {
  1521. VFIOBAR *bar = &vdev->bars[i];
  1522. vfio_bar_quirk_finalize(vdev, i);
  1523. vfio_region_finalize(&bar->region);
  1524. if (bar->mr) {
  1525. assert(bar->size);
  1526. object_unparent(OBJECT(bar->mr));
  1527. g_free(bar->mr);
  1528. bar->mr = NULL;
  1529. }
  1530. }
  1531. if (vdev->vga) {
  1532. vfio_vga_quirk_finalize(vdev);
  1533. for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
  1534. object_unparent(OBJECT(&vdev->vga->region[i].mem));
  1535. }
  1536. g_free(vdev->vga);
  1537. }
  1538. }
  1539. /*
  1540. * General setup
  1541. */
  1542. static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
  1543. {
  1544. uint8_t tmp;
  1545. uint16_t next = PCI_CONFIG_SPACE_SIZE;
  1546. for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
  1547. tmp = pdev->config[tmp + PCI_CAP_LIST_NEXT]) {
  1548. if (tmp > pos && tmp < next) {
  1549. next = tmp;
  1550. }
  1551. }
  1552. return next - pos;
  1553. }
  1554. static uint16_t vfio_ext_cap_max_size(const uint8_t *config, uint16_t pos)
  1555. {
  1556. uint16_t tmp, next = PCIE_CONFIG_SPACE_SIZE;
  1557. for (tmp = PCI_CONFIG_SPACE_SIZE; tmp;
  1558. tmp = PCI_EXT_CAP_NEXT(pci_get_long(config + tmp))) {
  1559. if (tmp > pos && tmp < next) {
  1560. next = tmp;
  1561. }
  1562. }
  1563. return next - pos;
  1564. }
  1565. static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
  1566. {
  1567. pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
  1568. }
  1569. static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
  1570. uint16_t val, uint16_t mask)
  1571. {
  1572. vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
  1573. vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
  1574. vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
  1575. }
  1576. static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
  1577. {
  1578. pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
  1579. }
  1580. static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
  1581. uint32_t val, uint32_t mask)
  1582. {
  1583. vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
  1584. vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
  1585. vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
  1586. }
  1587. static void vfio_pci_enable_rp_atomics(VFIOPCIDevice *vdev)
  1588. {
  1589. struct vfio_device_info_cap_pci_atomic_comp *cap;
  1590. g_autofree struct vfio_device_info *info = NULL;
  1591. PCIBus *bus = pci_get_bus(&vdev->pdev);
  1592. PCIDevice *parent = bus->parent_dev;
  1593. struct vfio_info_cap_header *hdr;
  1594. uint32_t mask = 0;
  1595. uint8_t *pos;
  1596. /*
  1597. * PCIe Atomic Ops completer support is only added automatically for single
  1598. * function devices downstream of a root port supporting DEVCAP2. Support
  1599. * is added during realize and, if added, removed during device exit. The
  1600. * single function requirement avoids conflicting requirements should a
  1601. * slot be composed of multiple devices with differing capabilities.
  1602. */
  1603. if (pci_bus_is_root(bus) || !parent || !parent->exp.exp_cap ||
  1604. pcie_cap_get_type(parent) != PCI_EXP_TYPE_ROOT_PORT ||
  1605. pcie_cap_get_version(parent) != PCI_EXP_FLAGS_VER2 ||
  1606. vdev->pdev.devfn ||
  1607. vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
  1608. return;
  1609. }
  1610. pos = parent->config + parent->exp.exp_cap + PCI_EXP_DEVCAP2;
  1611. /* Abort if there'a already an Atomic Ops configuration on the root port */
  1612. if (pci_get_long(pos) & (PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
  1613. PCI_EXP_DEVCAP2_ATOMIC_COMP64 |
  1614. PCI_EXP_DEVCAP2_ATOMIC_COMP128)) {
  1615. return;
  1616. }
  1617. info = vfio_get_device_info(vdev->vbasedev.fd);
  1618. if (!info) {
  1619. return;
  1620. }
  1621. hdr = vfio_get_device_info_cap(info, VFIO_DEVICE_INFO_CAP_PCI_ATOMIC_COMP);
  1622. if (!hdr) {
  1623. return;
  1624. }
  1625. cap = (void *)hdr;
  1626. if (cap->flags & VFIO_PCI_ATOMIC_COMP32) {
  1627. mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP32;
  1628. }
  1629. if (cap->flags & VFIO_PCI_ATOMIC_COMP64) {
  1630. mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP64;
  1631. }
  1632. if (cap->flags & VFIO_PCI_ATOMIC_COMP128) {
  1633. mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP128;
  1634. }
  1635. if (!mask) {
  1636. return;
  1637. }
  1638. pci_long_test_and_set_mask(pos, mask);
  1639. vdev->clear_parent_atomics_on_exit = true;
  1640. }
  1641. static void vfio_pci_disable_rp_atomics(VFIOPCIDevice *vdev)
  1642. {
  1643. if (vdev->clear_parent_atomics_on_exit) {
  1644. PCIDevice *parent = pci_get_bus(&vdev->pdev)->parent_dev;
  1645. uint8_t *pos = parent->config + parent->exp.exp_cap + PCI_EXP_DEVCAP2;
  1646. pci_long_test_and_clear_mask(pos, PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
  1647. PCI_EXP_DEVCAP2_ATOMIC_COMP64 |
  1648. PCI_EXP_DEVCAP2_ATOMIC_COMP128);
  1649. }
  1650. }
  1651. static bool vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,
  1652. Error **errp)
  1653. {
  1654. uint16_t flags;
  1655. uint8_t type;
  1656. flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
  1657. type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
  1658. if (type != PCI_EXP_TYPE_ENDPOINT &&
  1659. type != PCI_EXP_TYPE_LEG_END &&
  1660. type != PCI_EXP_TYPE_RC_END) {
  1661. error_setg(errp, "assignment of PCIe type 0x%x "
  1662. "devices is not currently supported", type);
  1663. return false;
  1664. }
  1665. if (!pci_bus_is_express(pci_get_bus(&vdev->pdev))) {
  1666. PCIBus *bus = pci_get_bus(&vdev->pdev);
  1667. PCIDevice *bridge;
  1668. /*
  1669. * Traditionally PCI device assignment exposes the PCIe capability
  1670. * as-is on non-express buses. The reason being that some drivers
  1671. * simply assume that it's there, for example tg3. However when
  1672. * we're running on a native PCIe machine type, like Q35, we need
  1673. * to hide the PCIe capability. The reason for this is twofold;
  1674. * first Windows guests get a Code 10 error when the PCIe capability
  1675. * is exposed in this configuration. Therefore express devices won't
  1676. * work at all unless they're attached to express buses in the VM.
  1677. * Second, a native PCIe machine introduces the possibility of fine
  1678. * granularity IOMMUs supporting both translation and isolation.
  1679. * Guest code to discover the IOMMU visibility of a device, such as
  1680. * IOMMU grouping code on Linux, is very aware of device types and
  1681. * valid transitions between bus types. An express device on a non-
  1682. * express bus is not a valid combination on bare metal systems.
  1683. *
  1684. * Drivers that require a PCIe capability to make the device
  1685. * functional are simply going to need to have their devices placed
  1686. * on a PCIe bus in the VM.
  1687. */
  1688. while (!pci_bus_is_root(bus)) {
  1689. bridge = pci_bridge_get_device(bus);
  1690. bus = pci_get_bus(bridge);
  1691. }
  1692. if (pci_bus_is_express(bus)) {
  1693. return true;
  1694. }
  1695. } else if (pci_bus_is_root(pci_get_bus(&vdev->pdev))) {
  1696. /*
  1697. * On a Root Complex bus Endpoints become Root Complex Integrated
  1698. * Endpoints, which changes the type and clears the LNK & LNK2 fields.
  1699. */
  1700. if (type == PCI_EXP_TYPE_ENDPOINT) {
  1701. vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
  1702. PCI_EXP_TYPE_RC_END << 4,
  1703. PCI_EXP_FLAGS_TYPE);
  1704. /* Link Capabilities, Status, and Control goes away */
  1705. if (size > PCI_EXP_LNKCTL) {
  1706. vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
  1707. vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
  1708. vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
  1709. #ifndef PCI_EXP_LNKCAP2
  1710. #define PCI_EXP_LNKCAP2 44
  1711. #endif
  1712. #ifndef PCI_EXP_LNKSTA2
  1713. #define PCI_EXP_LNKSTA2 50
  1714. #endif
  1715. /* Link 2 Capabilities, Status, and Control goes away */
  1716. if (size > PCI_EXP_LNKCAP2) {
  1717. vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
  1718. vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
  1719. vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
  1720. }
  1721. }
  1722. } else if (type == PCI_EXP_TYPE_LEG_END) {
  1723. /*
  1724. * Legacy endpoints don't belong on the root complex. Windows
  1725. * seems to be happier with devices if we skip the capability.
  1726. */
  1727. return true;
  1728. }
  1729. } else {
  1730. /*
  1731. * Convert Root Complex Integrated Endpoints to regular endpoints.
  1732. * These devices don't support LNK/LNK2 capabilities, so make them up.
  1733. */
  1734. if (type == PCI_EXP_TYPE_RC_END) {
  1735. vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
  1736. PCI_EXP_TYPE_ENDPOINT << 4,
  1737. PCI_EXP_FLAGS_TYPE);
  1738. vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
  1739. QEMU_PCI_EXP_LNKCAP_MLW(QEMU_PCI_EXP_LNK_X1) |
  1740. QEMU_PCI_EXP_LNKCAP_MLS(QEMU_PCI_EXP_LNK_2_5GT), ~0);
  1741. vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
  1742. }
  1743. vfio_pci_enable_rp_atomics(vdev);
  1744. }
  1745. /*
  1746. * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0
  1747. * (Niantic errate #35) causing Windows to error with a Code 10 for the
  1748. * device on Q35. Fixup any such devices to report version 1. If we
  1749. * were to remove the capability entirely the guest would lose extended
  1750. * config space.
  1751. */
  1752. if ((flags & PCI_EXP_FLAGS_VERS) == 0) {
  1753. vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
  1754. 1, PCI_EXP_FLAGS_VERS);
  1755. }
  1756. pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,
  1757. errp);
  1758. if (pos < 0) {
  1759. return false;
  1760. }
  1761. vdev->pdev.exp.exp_cap = pos;
  1762. return true;
  1763. }
  1764. static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
  1765. {
  1766. uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
  1767. if (cap & PCI_EXP_DEVCAP_FLR) {
  1768. trace_vfio_check_pcie_flr(vdev->vbasedev.name);
  1769. vdev->has_flr = true;
  1770. }
  1771. }
  1772. static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
  1773. {
  1774. uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
  1775. if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
  1776. trace_vfio_check_pm_reset(vdev->vbasedev.name);
  1777. vdev->has_pm_reset = true;
  1778. }
  1779. }
  1780. static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
  1781. {
  1782. uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
  1783. if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
  1784. trace_vfio_check_af_flr(vdev->vbasedev.name);
  1785. vdev->has_flr = true;
  1786. }
  1787. }
  1788. static bool vfio_add_vendor_specific_cap(VFIOPCIDevice *vdev, int pos,
  1789. uint8_t size, Error **errp)
  1790. {
  1791. PCIDevice *pdev = &vdev->pdev;
  1792. pos = pci_add_capability(pdev, PCI_CAP_ID_VNDR, pos, size, errp);
  1793. if (pos < 0) {
  1794. return false;
  1795. }
  1796. /*
  1797. * Exempt config space check for Vendor Specific Information during
  1798. * restore/load.
  1799. * Config space check is still enforced for 3 byte VSC header.
  1800. */
  1801. if (vdev->skip_vsc_check && size > 3) {
  1802. memset(pdev->cmask + pos + 3, 0, size - 3);
  1803. }
  1804. return true;
  1805. }
  1806. static bool vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos, Error **errp)
  1807. {
  1808. ERRP_GUARD();
  1809. PCIDevice *pdev = &vdev->pdev;
  1810. uint8_t cap_id, next, size;
  1811. bool ret;
  1812. cap_id = pdev->config[pos];
  1813. next = pdev->config[pos + PCI_CAP_LIST_NEXT];
  1814. /*
  1815. * If it becomes important to configure capabilities to their actual
  1816. * size, use this as the default when it's something we don't recognize.
  1817. * Since QEMU doesn't actually handle many of the config accesses,
  1818. * exact size doesn't seem worthwhile.
  1819. */
  1820. size = vfio_std_cap_max_size(pdev, pos);
  1821. /*
  1822. * pci_add_capability always inserts the new capability at the head
  1823. * of the chain. Therefore to end up with a chain that matches the
  1824. * physical device, we insert from the end by making this recursive.
  1825. * This is also why we pre-calculate size above as cached config space
  1826. * will be changed as we unwind the stack.
  1827. */
  1828. if (next) {
  1829. if (!vfio_add_std_cap(vdev, next, errp)) {
  1830. return false;
  1831. }
  1832. } else {
  1833. /* Begin the rebuild, use QEMU emulated list bits */
  1834. pdev->config[PCI_CAPABILITY_LIST] = 0;
  1835. vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
  1836. vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
  1837. if (!vfio_add_virt_caps(vdev, errp)) {
  1838. return false;
  1839. }
  1840. }
  1841. /* Scale down size, esp in case virt caps were added above */
  1842. size = MIN(size, vfio_std_cap_max_size(pdev, pos));
  1843. /* Use emulated next pointer to allow dropping caps */
  1844. pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff);
  1845. switch (cap_id) {
  1846. case PCI_CAP_ID_MSI:
  1847. ret = vfio_msi_setup(vdev, pos, errp);
  1848. break;
  1849. case PCI_CAP_ID_EXP:
  1850. vfio_check_pcie_flr(vdev, pos);
  1851. ret = vfio_setup_pcie_cap(vdev, pos, size, errp);
  1852. break;
  1853. case PCI_CAP_ID_MSIX:
  1854. ret = vfio_msix_setup(vdev, pos, errp);
  1855. break;
  1856. case PCI_CAP_ID_PM:
  1857. vfio_check_pm_reset(vdev, pos);
  1858. ret = pci_pm_init(pdev, pos, errp) >= 0;
  1859. /*
  1860. * PCI-core config space emulation needs write access to the power
  1861. * state enabled for tracking BAR mapping relative to PM state.
  1862. */
  1863. pci_set_word(pdev->wmask + pos + PCI_PM_CTRL, PCI_PM_CTRL_STATE_MASK);
  1864. break;
  1865. case PCI_CAP_ID_AF:
  1866. vfio_check_af_flr(vdev, pos);
  1867. ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0;
  1868. break;
  1869. case PCI_CAP_ID_VNDR:
  1870. ret = vfio_add_vendor_specific_cap(vdev, pos, size, errp);
  1871. break;
  1872. default:
  1873. ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0;
  1874. break;
  1875. }
  1876. if (!ret) {
  1877. error_prepend(errp,
  1878. "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
  1879. cap_id, size, pos);
  1880. }
  1881. return ret;
  1882. }
  1883. static int vfio_setup_rebar_ecap(VFIOPCIDevice *vdev, uint16_t pos)
  1884. {
  1885. uint32_t ctrl;
  1886. int i, nbar;
  1887. ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL);
  1888. nbar = (ctrl & PCI_REBAR_CTRL_NBAR_MASK) >> PCI_REBAR_CTRL_NBAR_SHIFT;
  1889. for (i = 0; i < nbar; i++) {
  1890. uint32_t cap;
  1891. int size;
  1892. ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL + (i * 8));
  1893. size = (ctrl & PCI_REBAR_CTRL_BAR_SIZE) >> PCI_REBAR_CTRL_BAR_SHIFT;
  1894. /* The cap register reports sizes 1MB to 128TB, with 4 reserved bits */
  1895. cap = size <= 27 ? 1U << (size + 4) : 0;
  1896. /*
  1897. * The PCIe spec (v6.0.1, 7.8.6) requires HW to support at least one
  1898. * size in the range 1MB to 512GB. We intend to mask all sizes except
  1899. * the one currently enabled in the size field, therefore if it's
  1900. * outside the range, hide the whole capability as this virtualization
  1901. * trick won't work. If >512GB resizable BARs start to appear, we
  1902. * might need an opt-in or reservation scheme in the kernel.
  1903. */
  1904. if (!(cap & PCI_REBAR_CAP_SIZES)) {
  1905. return -EINVAL;
  1906. }
  1907. /* Hide all sizes reported in the ctrl reg per above requirement. */
  1908. ctrl &= (PCI_REBAR_CTRL_BAR_SIZE |
  1909. PCI_REBAR_CTRL_NBAR_MASK |
  1910. PCI_REBAR_CTRL_BAR_IDX);
  1911. /*
  1912. * The BAR size field is RW, however we've mangled the capability
  1913. * register such that we only report a single size, ie. the current
  1914. * BAR size. A write of an unsupported value is undefined, therefore
  1915. * the register field is essentially RO.
  1916. */
  1917. vfio_add_emulated_long(vdev, pos + PCI_REBAR_CAP + (i * 8), cap, ~0);
  1918. vfio_add_emulated_long(vdev, pos + PCI_REBAR_CTRL + (i * 8), ctrl, ~0);
  1919. }
  1920. return 0;
  1921. }
  1922. static void vfio_add_ext_cap(VFIOPCIDevice *vdev)
  1923. {
  1924. PCIDevice *pdev = &vdev->pdev;
  1925. uint32_t header;
  1926. uint16_t cap_id, next, size;
  1927. uint8_t cap_ver;
  1928. uint8_t *config;
  1929. /* Only add extended caps if we have them and the guest can see them */
  1930. if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) ||
  1931. !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) {
  1932. return;
  1933. }
  1934. /*
  1935. * pcie_add_capability always inserts the new capability at the tail
  1936. * of the chain. Therefore to end up with a chain that matches the
  1937. * physical device, we cache the config space to avoid overwriting
  1938. * the original config space when we parse the extended capabilities.
  1939. */
  1940. config = g_memdup(pdev->config, vdev->config_size);
  1941. /*
  1942. * Extended capabilities are chained with each pointing to the next, so we
  1943. * can drop anything other than the head of the chain simply by modifying
  1944. * the previous next pointer. Seed the head of the chain here such that
  1945. * we can simply skip any capabilities we want to drop below, regardless
  1946. * of their position in the chain. If this stub capability still exists
  1947. * after we add the capabilities we want to expose, update the capability
  1948. * ID to zero. Note that we cannot seed with the capability header being
  1949. * zero as this conflicts with definition of an absent capability chain
  1950. * and prevents capabilities beyond the head of the list from being added.
  1951. * By replacing the dummy capability ID with zero after walking the device
  1952. * chain, we also transparently mark extended capabilities as absent if
  1953. * no capabilities were added. Note that the PCIe spec defines an absence
  1954. * of extended capabilities to be determined by a value of zero for the
  1955. * capability ID, version, AND next pointer. A non-zero next pointer
  1956. * should be sufficient to indicate additional capabilities are present,
  1957. * which will occur if we call pcie_add_capability() below. The entire
  1958. * first dword is emulated to support this.
  1959. *
  1960. * NB. The kernel side does similar masking, so be prepared that our
  1961. * view of the device may also contain a capability ID zero in the head
  1962. * of the chain. Skip it for the same reason that we cannot seed the
  1963. * chain with a zero capability.
  1964. */
  1965. pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE,
  1966. PCI_EXT_CAP(0xFFFF, 0, 0));
  1967. pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0);
  1968. pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0);
  1969. for (next = PCI_CONFIG_SPACE_SIZE; next;
  1970. next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) {
  1971. header = pci_get_long(config + next);
  1972. cap_id = PCI_EXT_CAP_ID(header);
  1973. cap_ver = PCI_EXT_CAP_VER(header);
  1974. /*
  1975. * If it becomes important to configure extended capabilities to their
  1976. * actual size, use this as the default when it's something we don't
  1977. * recognize. Since QEMU doesn't actually handle many of the config
  1978. * accesses, exact size doesn't seem worthwhile.
  1979. */
  1980. size = vfio_ext_cap_max_size(config, next);
  1981. /* Use emulated next pointer to allow dropping extended caps */
  1982. pci_long_test_and_set_mask(vdev->emulated_config_bits + next,
  1983. PCI_EXT_CAP_NEXT_MASK);
  1984. switch (cap_id) {
  1985. case 0: /* kernel masked capability */
  1986. case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */
  1987. case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */
  1988. trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next);
  1989. break;
  1990. case PCI_EXT_CAP_ID_REBAR:
  1991. if (!vfio_setup_rebar_ecap(vdev, next)) {
  1992. pcie_add_capability(pdev, cap_id, cap_ver, next, size);
  1993. }
  1994. break;
  1995. default:
  1996. pcie_add_capability(pdev, cap_id, cap_ver, next, size);
  1997. }
  1998. }
  1999. /* Cleanup chain head ID if necessary */
  2000. if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) {
  2001. pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0);
  2002. }
  2003. g_free(config);
  2004. return;
  2005. }
  2006. static bool vfio_add_capabilities(VFIOPCIDevice *vdev, Error **errp)
  2007. {
  2008. PCIDevice *pdev = &vdev->pdev;
  2009. if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
  2010. !pdev->config[PCI_CAPABILITY_LIST]) {
  2011. return true; /* Nothing to add */
  2012. }
  2013. if (!vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp)) {
  2014. return false;
  2015. }
  2016. vfio_add_ext_cap(vdev);
  2017. return true;
  2018. }
  2019. void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
  2020. {
  2021. PCIDevice *pdev = &vdev->pdev;
  2022. uint16_t cmd;
  2023. vfio_disable_interrupts(vdev);
  2024. /*
  2025. * Stop any ongoing DMA by disconnecting I/O, MMIO, and bus master.
  2026. * Also put INTx Disable in known state.
  2027. */
  2028. cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
  2029. cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
  2030. PCI_COMMAND_INTX_DISABLE);
  2031. vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
  2032. /* Make sure the device is in D0 */
  2033. if (pdev->pm_cap) {
  2034. uint16_t pmcsr;
  2035. uint8_t state;
  2036. pmcsr = vfio_pci_read_config(pdev, pdev->pm_cap + PCI_PM_CTRL, 2);
  2037. state = pmcsr & PCI_PM_CTRL_STATE_MASK;
  2038. if (state) {
  2039. pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
  2040. vfio_pci_write_config(pdev, pdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
  2041. /* vfio handles the necessary delay here */
  2042. pmcsr = vfio_pci_read_config(pdev, pdev->pm_cap + PCI_PM_CTRL, 2);
  2043. state = pmcsr & PCI_PM_CTRL_STATE_MASK;
  2044. if (state) {
  2045. error_report("vfio: Unable to power on device, stuck in D%d",
  2046. state);
  2047. }
  2048. }
  2049. }
  2050. }
  2051. void vfio_pci_post_reset(VFIOPCIDevice *vdev)
  2052. {
  2053. Error *err = NULL;
  2054. int nr;
  2055. if (!vfio_intx_enable(vdev, &err)) {
  2056. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2057. }
  2058. for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) {
  2059. off_t addr = vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr);
  2060. uint32_t val = 0;
  2061. uint32_t len = sizeof(val);
  2062. if (pwrite(vdev->vbasedev.fd, &val, len, addr) != len) {
  2063. error_report("%s(%s) reset bar %d failed: %m", __func__,
  2064. vdev->vbasedev.name, nr);
  2065. }
  2066. }
  2067. vfio_quirk_reset(vdev);
  2068. }
  2069. bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
  2070. {
  2071. char tmp[13];
  2072. sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
  2073. addr->bus, addr->slot, addr->function);
  2074. return (strcmp(tmp, name) == 0);
  2075. }
  2076. int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,
  2077. struct vfio_pci_hot_reset_info **info_p)
  2078. {
  2079. struct vfio_pci_hot_reset_info *info;
  2080. int ret, count;
  2081. assert(info_p && !*info_p);
  2082. info = g_malloc0(sizeof(*info));
  2083. info->argsz = sizeof(*info);
  2084. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
  2085. if (ret && errno != ENOSPC) {
  2086. ret = -errno;
  2087. g_free(info);
  2088. if (!vdev->has_pm_reset) {
  2089. error_report("vfio: Cannot reset device %s, "
  2090. "no available reset mechanism.", vdev->vbasedev.name);
  2091. }
  2092. return ret;
  2093. }
  2094. count = info->count;
  2095. info = g_realloc(info, sizeof(*info) + (count * sizeof(info->devices[0])));
  2096. info->argsz = sizeof(*info) + (count * sizeof(info->devices[0]));
  2097. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
  2098. if (ret) {
  2099. ret = -errno;
  2100. g_free(info);
  2101. error_report("vfio: hot reset info failed: %m");
  2102. return ret;
  2103. }
  2104. *info_p = info;
  2105. return 0;
  2106. }
  2107. static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
  2108. {
  2109. VFIODevice *vbasedev = &vdev->vbasedev;
  2110. const VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(vbasedev->bcontainer);
  2111. return vioc->pci_hot_reset(vbasedev, single);
  2112. }
  2113. /*
  2114. * We want to differentiate hot reset of multiple in-use devices vs hot reset
  2115. * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
  2116. * of doing hot resets when there is only a single device per bus. The in-use
  2117. * here refers to how many VFIODevices are affected. A hot reset that affects
  2118. * multiple devices, but only a single in-use device, means that we can call
  2119. * it from our bus ->reset() callback since the extent is effectively a single
  2120. * device. This allows us to make use of it in the hotplug path. When there
  2121. * are multiple in-use devices, we can only trigger the hot reset during a
  2122. * system reset and thus from our reset handler. We separate _one vs _multi
  2123. * here so that we don't overlap and do a double reset on the system reset
  2124. * path where both our reset handler and ->reset() callback are used. Calling
  2125. * _one() will only do a hot reset for the one in-use devices case, calling
  2126. * _multi() will do nothing if a _one() would have been sufficient.
  2127. */
  2128. static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
  2129. {
  2130. return vfio_pci_hot_reset(vdev, true);
  2131. }
  2132. static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
  2133. {
  2134. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2135. return vfio_pci_hot_reset(vdev, false);
  2136. }
  2137. static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
  2138. {
  2139. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2140. if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
  2141. vbasedev->needs_reset = true;
  2142. }
  2143. }
  2144. static Object *vfio_pci_get_object(VFIODevice *vbasedev)
  2145. {
  2146. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2147. return OBJECT(vdev);
  2148. }
  2149. static bool vfio_msix_present(void *opaque, int version_id)
  2150. {
  2151. PCIDevice *pdev = opaque;
  2152. return msix_present(pdev);
  2153. }
  2154. static bool vfio_display_migration_needed(void *opaque)
  2155. {
  2156. VFIOPCIDevice *vdev = opaque;
  2157. /*
  2158. * We need to migrate the VFIODisplay object if ramfb *migration* was
  2159. * explicitly requested (in which case we enforced both ramfb=on and
  2160. * display=on), or ramfb migration was left at the default "auto"
  2161. * setting, and *ramfb* was explicitly requested (in which case we
  2162. * enforced display=on).
  2163. */
  2164. return vdev->ramfb_migrate == ON_OFF_AUTO_ON ||
  2165. (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO && vdev->enable_ramfb);
  2166. }
  2167. static const VMStateDescription vmstate_vfio_display = {
  2168. .name = "VFIOPCIDevice/VFIODisplay",
  2169. .version_id = 1,
  2170. .minimum_version_id = 1,
  2171. .needed = vfio_display_migration_needed,
  2172. .fields = (const VMStateField[]){
  2173. VMSTATE_STRUCT_POINTER(dpy, VFIOPCIDevice, vfio_display_vmstate,
  2174. VFIODisplay),
  2175. VMSTATE_END_OF_LIST()
  2176. }
  2177. };
  2178. static const VMStateDescription vmstate_vfio_pci_config = {
  2179. .name = "VFIOPCIDevice",
  2180. .version_id = 1,
  2181. .minimum_version_id = 1,
  2182. .fields = (const VMStateField[]) {
  2183. VMSTATE_PCI_DEVICE(pdev, VFIOPCIDevice),
  2184. VMSTATE_MSIX_TEST(pdev, VFIOPCIDevice, vfio_msix_present),
  2185. VMSTATE_END_OF_LIST()
  2186. },
  2187. .subsections = (const VMStateDescription * const []) {
  2188. &vmstate_vfio_display,
  2189. NULL
  2190. }
  2191. };
  2192. static int vfio_pci_save_config(VFIODevice *vbasedev, QEMUFile *f, Error **errp)
  2193. {
  2194. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2195. return vmstate_save_state_with_err(f, &vmstate_vfio_pci_config, vdev, NULL,
  2196. errp);
  2197. }
  2198. static int vfio_pci_load_config(VFIODevice *vbasedev, QEMUFile *f)
  2199. {
  2200. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2201. PCIDevice *pdev = &vdev->pdev;
  2202. pcibus_t old_addr[PCI_NUM_REGIONS - 1];
  2203. int bar, ret;
  2204. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  2205. old_addr[bar] = pdev->io_regions[bar].addr;
  2206. }
  2207. ret = vmstate_load_state(f, &vmstate_vfio_pci_config, vdev, 1);
  2208. if (ret) {
  2209. return ret;
  2210. }
  2211. vfio_pci_write_config(pdev, PCI_COMMAND,
  2212. pci_get_word(pdev->config + PCI_COMMAND), 2);
  2213. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  2214. /*
  2215. * The address may not be changed in some scenarios
  2216. * (e.g. the VF driver isn't loaded in VM).
  2217. */
  2218. if (old_addr[bar] != pdev->io_regions[bar].addr &&
  2219. vdev->bars[bar].region.size > 0 &&
  2220. vdev->bars[bar].region.size < qemu_real_host_page_size()) {
  2221. vfio_sub_page_bar_update_mapping(pdev, bar);
  2222. }
  2223. }
  2224. if (msi_enabled(pdev)) {
  2225. vfio_msi_enable(vdev);
  2226. } else if (msix_enabled(pdev)) {
  2227. vfio_msix_enable(vdev);
  2228. }
  2229. return ret;
  2230. }
  2231. static VFIODeviceOps vfio_pci_ops = {
  2232. .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
  2233. .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
  2234. .vfio_eoi = vfio_intx_eoi,
  2235. .vfio_get_object = vfio_pci_get_object,
  2236. .vfio_save_config = vfio_pci_save_config,
  2237. .vfio_load_config = vfio_pci_load_config,
  2238. };
  2239. bool vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp)
  2240. {
  2241. VFIODevice *vbasedev = &vdev->vbasedev;
  2242. g_autofree struct vfio_region_info *reg_info = NULL;
  2243. int ret;
  2244. ret = vfio_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, &reg_info);
  2245. if (ret) {
  2246. error_setg_errno(errp, -ret,
  2247. "failed getting region info for VGA region index %d",
  2248. VFIO_PCI_VGA_REGION_INDEX);
  2249. return false;
  2250. }
  2251. if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) ||
  2252. !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) ||
  2253. reg_info->size < 0xbffff + 1) {
  2254. error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx",
  2255. (unsigned long)reg_info->flags,
  2256. (unsigned long)reg_info->size);
  2257. return false;
  2258. }
  2259. vdev->vga = g_new0(VFIOVGA, 1);
  2260. vdev->vga->fd_offset = reg_info->offset;
  2261. vdev->vga->fd = vdev->vbasedev.fd;
  2262. vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
  2263. vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
  2264. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks);
  2265. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
  2266. OBJECT(vdev), &vfio_vga_ops,
  2267. &vdev->vga->region[QEMU_PCI_VGA_MEM],
  2268. "vfio-vga-mmio@0xa0000",
  2269. QEMU_PCI_VGA_MEM_SIZE);
  2270. vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
  2271. vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
  2272. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks);
  2273. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
  2274. OBJECT(vdev), &vfio_vga_ops,
  2275. &vdev->vga->region[QEMU_PCI_VGA_IO_LO],
  2276. "vfio-vga-io@0x3b0",
  2277. QEMU_PCI_VGA_IO_LO_SIZE);
  2278. vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
  2279. vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
  2280. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks);
  2281. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
  2282. OBJECT(vdev), &vfio_vga_ops,
  2283. &vdev->vga->region[QEMU_PCI_VGA_IO_HI],
  2284. "vfio-vga-io@0x3c0",
  2285. QEMU_PCI_VGA_IO_HI_SIZE);
  2286. pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
  2287. &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
  2288. &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem);
  2289. return true;
  2290. }
  2291. static bool vfio_populate_device(VFIOPCIDevice *vdev, Error **errp)
  2292. {
  2293. VFIODevice *vbasedev = &vdev->vbasedev;
  2294. g_autofree struct vfio_region_info *reg_info = NULL;
  2295. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
  2296. int i, ret = -1;
  2297. /* Sanity check device */
  2298. if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
  2299. error_setg(errp, "this isn't a PCI device");
  2300. return false;
  2301. }
  2302. if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
  2303. error_setg(errp, "unexpected number of io regions %u",
  2304. vbasedev->num_regions);
  2305. return false;
  2306. }
  2307. if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
  2308. error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs);
  2309. return false;
  2310. }
  2311. for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
  2312. char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i);
  2313. ret = vfio_region_setup(OBJECT(vdev), vbasedev,
  2314. &vdev->bars[i].region, i, name);
  2315. g_free(name);
  2316. if (ret) {
  2317. error_setg_errno(errp, -ret, "failed to get region %d info", i);
  2318. return false;
  2319. }
  2320. QLIST_INIT(&vdev->bars[i].quirks);
  2321. }
  2322. ret = vfio_get_region_info(vbasedev,
  2323. VFIO_PCI_CONFIG_REGION_INDEX, &reg_info);
  2324. if (ret) {
  2325. error_setg_errno(errp, -ret, "failed to get config info");
  2326. return false;
  2327. }
  2328. trace_vfio_populate_device_config(vdev->vbasedev.name,
  2329. (unsigned long)reg_info->size,
  2330. (unsigned long)reg_info->offset,
  2331. (unsigned long)reg_info->flags);
  2332. vdev->config_size = reg_info->size;
  2333. if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
  2334. vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
  2335. }
  2336. vdev->config_offset = reg_info->offset;
  2337. if (vdev->features & VFIO_FEATURE_ENABLE_VGA) {
  2338. if (!vfio_populate_vga(vdev, errp)) {
  2339. error_append_hint(errp, "device does not support "
  2340. "requested feature x-vga\n");
  2341. return false;
  2342. }
  2343. }
  2344. irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
  2345. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
  2346. if (ret) {
  2347. /* This can fail for an old kernel or legacy PCI dev */
  2348. trace_vfio_populate_device_get_irq_info_failure(strerror(errno));
  2349. } else if (irq_info.count == 1) {
  2350. vdev->pci_aer = true;
  2351. } else {
  2352. warn_report(VFIO_MSG_PREFIX
  2353. "Could not enable error recovery for the device",
  2354. vbasedev->name);
  2355. }
  2356. return true;
  2357. }
  2358. static void vfio_pci_put_device(VFIOPCIDevice *vdev)
  2359. {
  2360. vfio_detach_device(&vdev->vbasedev);
  2361. g_free(vdev->vbasedev.name);
  2362. g_free(vdev->msix);
  2363. }
  2364. static void vfio_err_notifier_handler(void *opaque)
  2365. {
  2366. VFIOPCIDevice *vdev = opaque;
  2367. if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
  2368. return;
  2369. }
  2370. /*
  2371. * TBD. Retrieve the error details and decide what action
  2372. * needs to be taken. One of the actions could be to pass
  2373. * the error to the guest and have the guest driver recover
  2374. * from the error. This requires that PCIe capabilities be
  2375. * exposed to the guest. For now, we just terminate the
  2376. * guest to contain the error.
  2377. */
  2378. error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name);
  2379. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2380. }
  2381. /*
  2382. * Registers error notifier for devices supporting error recovery.
  2383. * If we encounter a failure in this function, we report an error
  2384. * and continue after disabling error recovery support for the
  2385. * device.
  2386. */
  2387. static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
  2388. {
  2389. Error *err = NULL;
  2390. int32_t fd;
  2391. if (!vdev->pci_aer) {
  2392. return;
  2393. }
  2394. if (event_notifier_init(&vdev->err_notifier, 0)) {
  2395. error_report("vfio: Unable to init event notifier for error detection");
  2396. vdev->pci_aer = false;
  2397. return;
  2398. }
  2399. fd = event_notifier_get_fd(&vdev->err_notifier);
  2400. qemu_set_fd_handler(fd, vfio_err_notifier_handler, NULL, vdev);
  2401. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
  2402. VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
  2403. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2404. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  2405. event_notifier_cleanup(&vdev->err_notifier);
  2406. vdev->pci_aer = false;
  2407. }
  2408. }
  2409. static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
  2410. {
  2411. Error *err = NULL;
  2412. if (!vdev->pci_aer) {
  2413. return;
  2414. }
  2415. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
  2416. VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
  2417. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2418. }
  2419. qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
  2420. NULL, NULL, vdev);
  2421. event_notifier_cleanup(&vdev->err_notifier);
  2422. }
  2423. static void vfio_req_notifier_handler(void *opaque)
  2424. {
  2425. VFIOPCIDevice *vdev = opaque;
  2426. Error *err = NULL;
  2427. if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
  2428. return;
  2429. }
  2430. qdev_unplug(DEVICE(vdev), &err);
  2431. if (err) {
  2432. warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2433. }
  2434. }
  2435. static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
  2436. {
  2437. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
  2438. .index = VFIO_PCI_REQ_IRQ_INDEX };
  2439. Error *err = NULL;
  2440. int32_t fd;
  2441. if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
  2442. return;
  2443. }
  2444. if (ioctl(vdev->vbasedev.fd,
  2445. VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
  2446. return;
  2447. }
  2448. if (event_notifier_init(&vdev->req_notifier, 0)) {
  2449. error_report("vfio: Unable to init event notifier for device request");
  2450. return;
  2451. }
  2452. fd = event_notifier_get_fd(&vdev->req_notifier);
  2453. qemu_set_fd_handler(fd, vfio_req_notifier_handler, NULL, vdev);
  2454. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
  2455. VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
  2456. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2457. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  2458. event_notifier_cleanup(&vdev->req_notifier);
  2459. } else {
  2460. vdev->req_enabled = true;
  2461. }
  2462. }
  2463. static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
  2464. {
  2465. Error *err = NULL;
  2466. if (!vdev->req_enabled) {
  2467. return;
  2468. }
  2469. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
  2470. VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
  2471. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2472. }
  2473. qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
  2474. NULL, NULL, vdev);
  2475. event_notifier_cleanup(&vdev->req_notifier);
  2476. vdev->req_enabled = false;
  2477. }
  2478. static void vfio_realize(PCIDevice *pdev, Error **errp)
  2479. {
  2480. ERRP_GUARD();
  2481. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  2482. VFIODevice *vbasedev = &vdev->vbasedev;
  2483. int i, ret;
  2484. char uuid[UUID_STR_LEN];
  2485. g_autofree char *name = NULL;
  2486. if (vbasedev->fd < 0 && !vbasedev->sysfsdev) {
  2487. if (!(~vdev->host.domain || ~vdev->host.bus ||
  2488. ~vdev->host.slot || ~vdev->host.function)) {
  2489. error_setg(errp, "No provided host device");
  2490. error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
  2491. #ifdef CONFIG_IOMMUFD
  2492. "or -device vfio-pci,fd=DEVICE_FD "
  2493. #endif
  2494. "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
  2495. return;
  2496. }
  2497. vbasedev->sysfsdev =
  2498. g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
  2499. vdev->host.domain, vdev->host.bus,
  2500. vdev->host.slot, vdev->host.function);
  2501. }
  2502. if (!vfio_device_get_name(vbasedev, errp)) {
  2503. return;
  2504. }
  2505. /*
  2506. * Mediated devices *might* operate compatibly with discarding of RAM, but
  2507. * we cannot know for certain, it depends on whether the mdev vendor driver
  2508. * stays in sync with the active working set of the guest driver. Prevent
  2509. * the x-balloon-allowed option unless this is minimally an mdev device.
  2510. */
  2511. vbasedev->mdev = vfio_device_is_mdev(vbasedev);
  2512. trace_vfio_mdev(vbasedev->name, vbasedev->mdev);
  2513. if (vbasedev->ram_block_discard_allowed && !vbasedev->mdev) {
  2514. error_setg(errp, "x-balloon-allowed only potentially compatible "
  2515. "with mdev devices");
  2516. goto error;
  2517. }
  2518. if (!qemu_uuid_is_null(&vdev->vf_token)) {
  2519. qemu_uuid_unparse(&vdev->vf_token, uuid);
  2520. name = g_strdup_printf("%s vf_token=%s", vbasedev->name, uuid);
  2521. } else {
  2522. name = g_strdup(vbasedev->name);
  2523. }
  2524. if (!vfio_attach_device(name, vbasedev,
  2525. pci_device_iommu_address_space(pdev), errp)) {
  2526. goto error;
  2527. }
  2528. if (!vfio_populate_device(vdev, errp)) {
  2529. goto error;
  2530. }
  2531. /* Get a copy of config space */
  2532. ret = pread(vbasedev->fd, vdev->pdev.config,
  2533. MIN(pci_config_size(&vdev->pdev), vdev->config_size),
  2534. vdev->config_offset);
  2535. if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
  2536. ret = ret < 0 ? -errno : -EFAULT;
  2537. error_setg_errno(errp, -ret, "failed to read device config space");
  2538. goto error;
  2539. }
  2540. /* vfio emulates a lot for us, but some bits need extra love */
  2541. vdev->emulated_config_bits = g_malloc0(vdev->config_size);
  2542. /* QEMU can choose to expose the ROM or not */
  2543. memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
  2544. /* QEMU can also add or extend BARs */
  2545. memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4);
  2546. /*
  2547. * The PCI spec reserves vendor ID 0xffff as an invalid value. The
  2548. * device ID is managed by the vendor and need only be a 16-bit value.
  2549. * Allow any 16-bit value for subsystem so they can be hidden or changed.
  2550. */
  2551. if (vdev->vendor_id != PCI_ANY_ID) {
  2552. if (vdev->vendor_id >= 0xffff) {
  2553. error_setg(errp, "invalid PCI vendor ID provided");
  2554. goto error;
  2555. }
  2556. vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
  2557. trace_vfio_pci_emulated_vendor_id(vbasedev->name, vdev->vendor_id);
  2558. } else {
  2559. vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
  2560. }
  2561. if (vdev->device_id != PCI_ANY_ID) {
  2562. if (vdev->device_id > 0xffff) {
  2563. error_setg(errp, "invalid PCI device ID provided");
  2564. goto error;
  2565. }
  2566. vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
  2567. trace_vfio_pci_emulated_device_id(vbasedev->name, vdev->device_id);
  2568. } else {
  2569. vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
  2570. }
  2571. if (vdev->sub_vendor_id != PCI_ANY_ID) {
  2572. if (vdev->sub_vendor_id > 0xffff) {
  2573. error_setg(errp, "invalid PCI subsystem vendor ID provided");
  2574. goto error;
  2575. }
  2576. vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
  2577. vdev->sub_vendor_id, ~0);
  2578. trace_vfio_pci_emulated_sub_vendor_id(vbasedev->name,
  2579. vdev->sub_vendor_id);
  2580. }
  2581. if (vdev->sub_device_id != PCI_ANY_ID) {
  2582. if (vdev->sub_device_id > 0xffff) {
  2583. error_setg(errp, "invalid PCI subsystem device ID provided");
  2584. goto error;
  2585. }
  2586. vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
  2587. trace_vfio_pci_emulated_sub_device_id(vbasedev->name,
  2588. vdev->sub_device_id);
  2589. }
  2590. /* QEMU can change multi-function devices to single function, or reverse */
  2591. vdev->emulated_config_bits[PCI_HEADER_TYPE] =
  2592. PCI_HEADER_TYPE_MULTI_FUNCTION;
  2593. /* Restore or clear multifunction, this is always controlled by QEMU */
  2594. if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
  2595. vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
  2596. } else {
  2597. vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
  2598. }
  2599. /*
  2600. * Clear host resource mapping info. If we choose not to register a
  2601. * BAR, such as might be the case with the option ROM, we can get
  2602. * confusing, unwritable, residual addresses from the host here.
  2603. */
  2604. memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
  2605. memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
  2606. vfio_pci_size_rom(vdev);
  2607. vfio_bars_prepare(vdev);
  2608. if (!vfio_msix_early_setup(vdev, errp)) {
  2609. goto error;
  2610. }
  2611. vfio_bars_register(vdev);
  2612. if (!vbasedev->mdev &&
  2613. !pci_device_set_iommu_device(pdev, vbasedev->hiod, errp)) {
  2614. error_prepend(errp, "Failed to set vIOMMU: ");
  2615. goto out_teardown;
  2616. }
  2617. if (!vfio_add_capabilities(vdev, errp)) {
  2618. goto out_unset_idev;
  2619. }
  2620. if (!vfio_config_quirk_setup(vdev, errp)) {
  2621. goto out_unset_idev;
  2622. }
  2623. if (vdev->vga) {
  2624. vfio_vga_quirk_setup(vdev);
  2625. }
  2626. for (i = 0; i < PCI_ROM_SLOT; i++) {
  2627. vfio_bar_quirk_setup(vdev, i);
  2628. }
  2629. /* QEMU emulates all of MSI & MSIX */
  2630. if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
  2631. memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
  2632. MSIX_CAP_LENGTH);
  2633. }
  2634. if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
  2635. memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
  2636. vdev->msi_cap_size);
  2637. }
  2638. if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
  2639. vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
  2640. vfio_intx_mmap_enable, vdev);
  2641. pci_device_set_intx_routing_notifier(&vdev->pdev,
  2642. vfio_intx_routing_notifier);
  2643. vdev->irqchip_change_notifier.notify = vfio_irqchip_change;
  2644. kvm_irqchip_add_change_notifier(&vdev->irqchip_change_notifier);
  2645. if (!vfio_intx_enable(vdev, errp)) {
  2646. goto out_deregister;
  2647. }
  2648. }
  2649. if (vdev->display != ON_OFF_AUTO_OFF) {
  2650. if (!vfio_display_probe(vdev, errp)) {
  2651. goto out_deregister;
  2652. }
  2653. }
  2654. if (vdev->enable_ramfb && vdev->dpy == NULL) {
  2655. error_setg(errp, "ramfb=on requires display=on");
  2656. goto out_deregister;
  2657. }
  2658. if (vdev->display_xres || vdev->display_yres) {
  2659. if (vdev->dpy == NULL) {
  2660. error_setg(errp, "xres and yres properties require display=on");
  2661. goto out_deregister;
  2662. }
  2663. if (vdev->dpy->edid_regs == NULL) {
  2664. error_setg(errp, "xres and yres properties need edid support");
  2665. goto out_deregister;
  2666. }
  2667. }
  2668. if (vdev->ramfb_migrate == ON_OFF_AUTO_ON && !vdev->enable_ramfb) {
  2669. warn_report("x-ramfb-migrate=on but ramfb=off. "
  2670. "Forcing x-ramfb-migrate to off.");
  2671. vdev->ramfb_migrate = ON_OFF_AUTO_OFF;
  2672. }
  2673. if (vbasedev->enable_migration == ON_OFF_AUTO_OFF) {
  2674. if (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO) {
  2675. vdev->ramfb_migrate = ON_OFF_AUTO_OFF;
  2676. } else if (vdev->ramfb_migrate == ON_OFF_AUTO_ON) {
  2677. error_setg(errp, "x-ramfb-migrate requires enable-migration");
  2678. goto out_deregister;
  2679. }
  2680. }
  2681. if (!pdev->failover_pair_id) {
  2682. if (!vfio_migration_realize(vbasedev, errp)) {
  2683. goto out_deregister;
  2684. }
  2685. }
  2686. vfio_register_err_notifier(vdev);
  2687. vfio_register_req_notifier(vdev);
  2688. vfio_setup_resetfn_quirk(vdev);
  2689. return;
  2690. out_deregister:
  2691. if (vdev->interrupt == VFIO_INT_INTx) {
  2692. vfio_intx_disable(vdev);
  2693. }
  2694. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  2695. if (vdev->irqchip_change_notifier.notify) {
  2696. kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
  2697. }
  2698. if (vdev->intx.mmap_timer) {
  2699. timer_free(vdev->intx.mmap_timer);
  2700. }
  2701. out_unset_idev:
  2702. if (!vbasedev->mdev) {
  2703. pci_device_unset_iommu_device(pdev);
  2704. }
  2705. out_teardown:
  2706. vfio_teardown_msi(vdev);
  2707. vfio_bars_exit(vdev);
  2708. error:
  2709. error_prepend(errp, VFIO_MSG_PREFIX, vbasedev->name);
  2710. }
  2711. static void vfio_instance_finalize(Object *obj)
  2712. {
  2713. VFIOPCIDevice *vdev = VFIO_PCI(obj);
  2714. vfio_display_finalize(vdev);
  2715. vfio_bars_finalize(vdev);
  2716. g_free(vdev->emulated_config_bits);
  2717. g_free(vdev->rom);
  2718. /*
  2719. * XXX Leaking igd_opregion is not an oversight, we can't remove the
  2720. * fw_cfg entry therefore leaking this allocation seems like the safest
  2721. * option.
  2722. *
  2723. * g_free(vdev->igd_opregion);
  2724. */
  2725. vfio_pci_put_device(vdev);
  2726. }
  2727. static void vfio_exitfn(PCIDevice *pdev)
  2728. {
  2729. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  2730. VFIODevice *vbasedev = &vdev->vbasedev;
  2731. vfio_unregister_req_notifier(vdev);
  2732. vfio_unregister_err_notifier(vdev);
  2733. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  2734. if (vdev->irqchip_change_notifier.notify) {
  2735. kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
  2736. }
  2737. vfio_disable_interrupts(vdev);
  2738. if (vdev->intx.mmap_timer) {
  2739. timer_free(vdev->intx.mmap_timer);
  2740. }
  2741. vfio_teardown_msi(vdev);
  2742. vfio_pci_disable_rp_atomics(vdev);
  2743. vfio_bars_exit(vdev);
  2744. vfio_migration_exit(vbasedev);
  2745. if (!vbasedev->mdev) {
  2746. pci_device_unset_iommu_device(pdev);
  2747. }
  2748. }
  2749. static void vfio_pci_reset(DeviceState *dev)
  2750. {
  2751. VFIOPCIDevice *vdev = VFIO_PCI(dev);
  2752. trace_vfio_pci_reset(vdev->vbasedev.name);
  2753. vfio_pci_pre_reset(vdev);
  2754. if (vdev->display != ON_OFF_AUTO_OFF) {
  2755. vfio_display_reset(vdev);
  2756. }
  2757. if (vdev->resetfn && !vdev->resetfn(vdev)) {
  2758. goto post_reset;
  2759. }
  2760. if (vdev->vbasedev.reset_works &&
  2761. (vdev->has_flr || !vdev->has_pm_reset) &&
  2762. !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
  2763. trace_vfio_pci_reset_flr(vdev->vbasedev.name);
  2764. goto post_reset;
  2765. }
  2766. /* See if we can do our own bus reset */
  2767. if (!vfio_pci_hot_reset_one(vdev)) {
  2768. goto post_reset;
  2769. }
  2770. /* If nothing else works and the device supports PM reset, use it */
  2771. if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
  2772. !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
  2773. trace_vfio_pci_reset_pm(vdev->vbasedev.name);
  2774. goto post_reset;
  2775. }
  2776. post_reset:
  2777. vfio_pci_post_reset(vdev);
  2778. }
  2779. static void vfio_instance_init(Object *obj)
  2780. {
  2781. PCIDevice *pci_dev = PCI_DEVICE(obj);
  2782. VFIOPCIDevice *vdev = VFIO_PCI(obj);
  2783. VFIODevice *vbasedev = &vdev->vbasedev;
  2784. device_add_bootindex_property(obj, &vdev->bootindex,
  2785. "bootindex", NULL,
  2786. &pci_dev->qdev);
  2787. vdev->host.domain = ~0U;
  2788. vdev->host.bus = ~0U;
  2789. vdev->host.slot = ~0U;
  2790. vdev->host.function = ~0U;
  2791. vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_PCI, &vfio_pci_ops,
  2792. DEVICE(vdev), false);
  2793. vdev->nv_gpudirect_clique = 0xFF;
  2794. /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
  2795. * line, therefore, no need to wait to realize like other devices */
  2796. pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
  2797. }
  2798. static PropertyInfo vfio_pci_migration_multifd_transfer_prop;
  2799. static const Property vfio_pci_dev_properties[] = {
  2800. DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
  2801. DEFINE_PROP_UUID_NODEFAULT("vf-token", VFIOPCIDevice, vf_token),
  2802. DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev),
  2803. DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice,
  2804. vbasedev.pre_copy_dirty_page_tracking,
  2805. ON_OFF_AUTO_ON),
  2806. DEFINE_PROP_ON_OFF_AUTO("x-device-dirty-page-tracking", VFIOPCIDevice,
  2807. vbasedev.device_dirty_page_tracking,
  2808. ON_OFF_AUTO_ON),
  2809. DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice,
  2810. display, ON_OFF_AUTO_OFF),
  2811. DEFINE_PROP_UINT32("xres", VFIOPCIDevice, display_xres, 0),
  2812. DEFINE_PROP_UINT32("yres", VFIOPCIDevice, display_yres, 0),
  2813. DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
  2814. intx.mmap_timeout, 1100),
  2815. DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
  2816. VFIO_FEATURE_ENABLE_VGA_BIT, false),
  2817. DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
  2818. VFIO_FEATURE_ENABLE_REQ_BIT, true),
  2819. DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features,
  2820. VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, false),
  2821. DEFINE_PROP_BIT("x-igd-lpc", VFIOPCIDevice, features,
  2822. VFIO_FEATURE_ENABLE_IGD_LPC_BIT, false),
  2823. DEFINE_PROP_ON_OFF_AUTO("x-igd-legacy-mode", VFIOPCIDevice,
  2824. igd_legacy_mode, ON_OFF_AUTO_AUTO),
  2825. DEFINE_PROP_ON_OFF_AUTO("enable-migration", VFIOPCIDevice,
  2826. vbasedev.enable_migration, ON_OFF_AUTO_AUTO),
  2827. DEFINE_PROP("x-migration-multifd-transfer", VFIOPCIDevice,
  2828. vbasedev.migration_multifd_transfer,
  2829. vfio_pci_migration_multifd_transfer_prop, OnOffAuto,
  2830. .set_default = true, .defval.i = ON_OFF_AUTO_AUTO),
  2831. DEFINE_PROP_BOOL("migration-events", VFIOPCIDevice,
  2832. vbasedev.migration_events, false),
  2833. DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
  2834. DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice,
  2835. vbasedev.ram_block_discard_allowed, false),
  2836. DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
  2837. DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
  2838. DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
  2839. DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice,
  2840. no_geforce_quirks, false),
  2841. DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice, no_kvm_ioeventfd,
  2842. false),
  2843. DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice, no_vfio_ioeventfd,
  2844. false),
  2845. DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID),
  2846. DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID),
  2847. DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice,
  2848. sub_vendor_id, PCI_ANY_ID),
  2849. DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice,
  2850. sub_device_id, PCI_ANY_ID),
  2851. DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0),
  2852. DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice,
  2853. nv_gpudirect_clique,
  2854. qdev_prop_nv_gpudirect_clique, uint8_t),
  2855. DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
  2856. OFF_AUTO_PCIBAR_OFF),
  2857. #ifdef CONFIG_IOMMUFD
  2858. DEFINE_PROP_LINK("iommufd", VFIOPCIDevice, vbasedev.iommufd,
  2859. TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
  2860. #endif
  2861. DEFINE_PROP_BOOL("skip-vsc-check", VFIOPCIDevice, skip_vsc_check, true),
  2862. };
  2863. #ifdef CONFIG_IOMMUFD
  2864. static void vfio_pci_set_fd(Object *obj, const char *str, Error **errp)
  2865. {
  2866. vfio_device_set_fd(&VFIO_PCI(obj)->vbasedev, str, errp);
  2867. }
  2868. #endif
  2869. static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
  2870. {
  2871. DeviceClass *dc = DEVICE_CLASS(klass);
  2872. PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
  2873. device_class_set_legacy_reset(dc, vfio_pci_reset);
  2874. device_class_set_props(dc, vfio_pci_dev_properties);
  2875. #ifdef CONFIG_IOMMUFD
  2876. object_class_property_add_str(klass, "fd", NULL, vfio_pci_set_fd);
  2877. #endif
  2878. dc->desc = "VFIO-based PCI device assignment";
  2879. set_bit(DEVICE_CATEGORY_MISC, dc->categories);
  2880. pdc->realize = vfio_realize;
  2881. pdc->exit = vfio_exitfn;
  2882. pdc->config_read = vfio_pci_read_config;
  2883. pdc->config_write = vfio_pci_write_config;
  2884. object_class_property_set_description(klass, /* 1.3 */
  2885. "host",
  2886. "Host PCI address [domain:]<bus:slot.function> of assigned device");
  2887. object_class_property_set_description(klass, /* 1.3 */
  2888. "x-intx-mmap-timeout-ms",
  2889. "When EOI is not provided by KVM/QEMU, wait time "
  2890. "(milliseconds) to re-enable device direct access "
  2891. "after INTx (DEBUG)");
  2892. object_class_property_set_description(klass, /* 1.5 */
  2893. "x-vga",
  2894. "Expose VGA address spaces for device");
  2895. object_class_property_set_description(klass, /* 2.3 */
  2896. "x-req",
  2897. "Disable device request notification support (DEBUG)");
  2898. object_class_property_set_description(klass, /* 2.4 and 2.5 */
  2899. "x-no-mmap",
  2900. "Disable MMAP for device. Allows to trace MMIO "
  2901. "accesses (DEBUG)");
  2902. object_class_property_set_description(klass, /* 2.5 */
  2903. "x-no-kvm-intx",
  2904. "Disable direct VFIO->KVM INTx injection. Allows to "
  2905. "trace INTx interrupts (DEBUG)");
  2906. object_class_property_set_description(klass, /* 2.5 */
  2907. "x-no-kvm-msi",
  2908. "Disable direct VFIO->KVM MSI injection. Allows to "
  2909. "trace MSI interrupts (DEBUG)");
  2910. object_class_property_set_description(klass, /* 2.5 */
  2911. "x-no-kvm-msix",
  2912. "Disable direct VFIO->KVM MSIx injection. Allows to "
  2913. "trace MSIx interrupts (DEBUG)");
  2914. object_class_property_set_description(klass, /* 2.5 */
  2915. "x-pci-vendor-id",
  2916. "Override PCI Vendor ID with provided value (DEBUG)");
  2917. object_class_property_set_description(klass, /* 2.5 */
  2918. "x-pci-device-id",
  2919. "Override PCI device ID with provided value (DEBUG)");
  2920. object_class_property_set_description(klass, /* 2.5 */
  2921. "x-pci-sub-vendor-id",
  2922. "Override PCI Subsystem Vendor ID with provided value "
  2923. "(DEBUG)");
  2924. object_class_property_set_description(klass, /* 2.5 */
  2925. "x-pci-sub-device-id",
  2926. "Override PCI Subsystem Device ID with provided value "
  2927. "(DEBUG)");
  2928. object_class_property_set_description(klass, /* 2.6 */
  2929. "sysfsdev",
  2930. "Host sysfs path of assigned device");
  2931. object_class_property_set_description(klass, /* 2.7 */
  2932. "x-igd-opregion",
  2933. "Expose host IGD OpRegion to guest");
  2934. object_class_property_set_description(klass, /* 2.7 (See c4c45e943e51) */
  2935. "x-igd-gms",
  2936. "Override IGD data stolen memory size (32MiB units)");
  2937. object_class_property_set_description(klass, /* 2.11 */
  2938. "x-nv-gpudirect-clique",
  2939. "Add NVIDIA GPUDirect capability indicating P2P DMA "
  2940. "clique for device [0-15]");
  2941. object_class_property_set_description(klass, /* 2.12 */
  2942. "x-no-geforce-quirks",
  2943. "Disable GeForce quirks (for NVIDIA Quadro/GRID/Tesla). "
  2944. "Improves performance");
  2945. object_class_property_set_description(klass, /* 2.12 */
  2946. "display",
  2947. "Enable display support for device, ex. vGPU");
  2948. object_class_property_set_description(klass, /* 2.12 */
  2949. "x-msix-relocation",
  2950. "Specify MSI-X MMIO relocation to the end of specified "
  2951. "existing BAR or new BAR to avoid virtualization overhead "
  2952. "due to adjacent device registers");
  2953. object_class_property_set_description(klass, /* 3.0 */
  2954. "x-no-kvm-ioeventfd",
  2955. "Disable registration of ioeventfds with KVM (DEBUG)");
  2956. object_class_property_set_description(klass, /* 3.0 */
  2957. "x-no-vfio-ioeventfd",
  2958. "Disable linking of KVM ioeventfds to VFIO ioeventfds "
  2959. "(DEBUG)");
  2960. object_class_property_set_description(klass, /* 3.1 */
  2961. "x-balloon-allowed",
  2962. "Override allowing ballooning with device (DEBUG, DANGER)");
  2963. object_class_property_set_description(klass, /* 3.2 */
  2964. "xres",
  2965. "Set X display resolution the vGPU should use");
  2966. object_class_property_set_description(klass, /* 3.2 */
  2967. "yres",
  2968. "Set Y display resolution the vGPU should use");
  2969. object_class_property_set_description(klass, /* 5.2 */
  2970. "x-pre-copy-dirty-page-tracking",
  2971. "Disable dirty pages tracking during iterative phase "
  2972. "(DEBUG)");
  2973. object_class_property_set_description(klass, /* 5.2, 8.0 non-experimetal */
  2974. "enable-migration",
  2975. "Enale device migration. Also requires a host VFIO PCI "
  2976. "variant or mdev driver with migration support enabled");
  2977. object_class_property_set_description(klass, /* 8.1 */
  2978. "vf-token",
  2979. "Specify UUID VF token. Required for VF when PF is owned "
  2980. "by another VFIO driver");
  2981. #ifdef CONFIG_IOMMUFD
  2982. object_class_property_set_description(klass, /* 9.0 */
  2983. "iommufd",
  2984. "Set host IOMMUFD backend device");
  2985. #endif
  2986. object_class_property_set_description(klass, /* 9.1 */
  2987. "x-device-dirty-page-tracking",
  2988. "Disable device dirty page tracking and use "
  2989. "container-based dirty page tracking");
  2990. object_class_property_set_description(klass, /* 9.1 */
  2991. "migration-events",
  2992. "Emit VFIO migration QAPI event when a VFIO device "
  2993. "changes its migration state. For management applications");
  2994. object_class_property_set_description(klass, /* 9.1 */
  2995. "skip-vsc-check",
  2996. "Skip config space check for Vendor Specific Capability. "
  2997. "Setting to false will enforce strict checking of VSC content "
  2998. "(DEBUG)");
  2999. object_class_property_set_description(klass, /* 10.0 */
  3000. "x-migration-multifd-transfer",
  3001. "Transfer this device state via "
  3002. "multifd channels when live migrating it");
  3003. }
  3004. static const TypeInfo vfio_pci_dev_info = {
  3005. .name = TYPE_VFIO_PCI,
  3006. .parent = TYPE_PCI_DEVICE,
  3007. .instance_size = sizeof(VFIOPCIDevice),
  3008. .class_init = vfio_pci_dev_class_init,
  3009. .instance_init = vfio_instance_init,
  3010. .instance_finalize = vfio_instance_finalize,
  3011. .interfaces = (InterfaceInfo[]) {
  3012. { INTERFACE_PCIE_DEVICE },
  3013. { INTERFACE_CONVENTIONAL_PCI_DEVICE },
  3014. { }
  3015. },
  3016. };
  3017. static const Property vfio_pci_dev_nohotplug_properties[] = {
  3018. DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice, enable_ramfb, false),
  3019. DEFINE_PROP_ON_OFF_AUTO("x-ramfb-migrate", VFIOPCIDevice, ramfb_migrate,
  3020. ON_OFF_AUTO_AUTO),
  3021. };
  3022. static void vfio_pci_nohotplug_dev_class_init(ObjectClass *klass, void *data)
  3023. {
  3024. DeviceClass *dc = DEVICE_CLASS(klass);
  3025. device_class_set_props(dc, vfio_pci_dev_nohotplug_properties);
  3026. dc->hotpluggable = false;
  3027. object_class_property_set_description(klass, /* 3.1 */
  3028. "ramfb",
  3029. "Enable ramfb to provide pre-boot graphics for devices "
  3030. "enabling display option");
  3031. object_class_property_set_description(klass, /* 8.2 */
  3032. "x-ramfb-migrate",
  3033. "Override default migration support for ramfb support "
  3034. "(DEBUG)");
  3035. }
  3036. static const TypeInfo vfio_pci_nohotplug_dev_info = {
  3037. .name = TYPE_VFIO_PCI_NOHOTPLUG,
  3038. .parent = TYPE_VFIO_PCI,
  3039. .instance_size = sizeof(VFIOPCIDevice),
  3040. .class_init = vfio_pci_nohotplug_dev_class_init,
  3041. };
  3042. static void register_vfio_pci_dev_type(void)
  3043. {
  3044. /*
  3045. * Ordinary ON_OFF_AUTO property isn't runtime-mutable, but source VM can
  3046. * run for a long time before being migrated so it is desirable to have a
  3047. * fallback mechanism to the old way of transferring VFIO device state if
  3048. * it turns to be necessary.
  3049. * The following makes this type of property have the same mutability level
  3050. * as ordinary migration parameters.
  3051. */
  3052. vfio_pci_migration_multifd_transfer_prop = qdev_prop_on_off_auto;
  3053. vfio_pci_migration_multifd_transfer_prop.realized_set_allowed = true;
  3054. type_register_static(&vfio_pci_dev_info);
  3055. type_register_static(&vfio_pci_nohotplug_dev_info);
  3056. }
  3057. type_init(register_vfio_pci_dev_type)