pci.c 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479
  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. vdev->pm_cap = pos;
  1859. ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0;
  1860. break;
  1861. case PCI_CAP_ID_AF:
  1862. vfio_check_af_flr(vdev, pos);
  1863. ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0;
  1864. break;
  1865. case PCI_CAP_ID_VNDR:
  1866. ret = vfio_add_vendor_specific_cap(vdev, pos, size, errp);
  1867. break;
  1868. default:
  1869. ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0;
  1870. break;
  1871. }
  1872. if (!ret) {
  1873. error_prepend(errp,
  1874. "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
  1875. cap_id, size, pos);
  1876. }
  1877. return ret;
  1878. }
  1879. static int vfio_setup_rebar_ecap(VFIOPCIDevice *vdev, uint16_t pos)
  1880. {
  1881. uint32_t ctrl;
  1882. int i, nbar;
  1883. ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL);
  1884. nbar = (ctrl & PCI_REBAR_CTRL_NBAR_MASK) >> PCI_REBAR_CTRL_NBAR_SHIFT;
  1885. for (i = 0; i < nbar; i++) {
  1886. uint32_t cap;
  1887. int size;
  1888. ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL + (i * 8));
  1889. size = (ctrl & PCI_REBAR_CTRL_BAR_SIZE) >> PCI_REBAR_CTRL_BAR_SHIFT;
  1890. /* The cap register reports sizes 1MB to 128TB, with 4 reserved bits */
  1891. cap = size <= 27 ? 1U << (size + 4) : 0;
  1892. /*
  1893. * The PCIe spec (v6.0.1, 7.8.6) requires HW to support at least one
  1894. * size in the range 1MB to 512GB. We intend to mask all sizes except
  1895. * the one currently enabled in the size field, therefore if it's
  1896. * outside the range, hide the whole capability as this virtualization
  1897. * trick won't work. If >512GB resizable BARs start to appear, we
  1898. * might need an opt-in or reservation scheme in the kernel.
  1899. */
  1900. if (!(cap & PCI_REBAR_CAP_SIZES)) {
  1901. return -EINVAL;
  1902. }
  1903. /* Hide all sizes reported in the ctrl reg per above requirement. */
  1904. ctrl &= (PCI_REBAR_CTRL_BAR_SIZE |
  1905. PCI_REBAR_CTRL_NBAR_MASK |
  1906. PCI_REBAR_CTRL_BAR_IDX);
  1907. /*
  1908. * The BAR size field is RW, however we've mangled the capability
  1909. * register such that we only report a single size, ie. the current
  1910. * BAR size. A write of an unsupported value is undefined, therefore
  1911. * the register field is essentially RO.
  1912. */
  1913. vfio_add_emulated_long(vdev, pos + PCI_REBAR_CAP + (i * 8), cap, ~0);
  1914. vfio_add_emulated_long(vdev, pos + PCI_REBAR_CTRL + (i * 8), ctrl, ~0);
  1915. }
  1916. return 0;
  1917. }
  1918. static void vfio_add_ext_cap(VFIOPCIDevice *vdev)
  1919. {
  1920. PCIDevice *pdev = &vdev->pdev;
  1921. uint32_t header;
  1922. uint16_t cap_id, next, size;
  1923. uint8_t cap_ver;
  1924. uint8_t *config;
  1925. /* Only add extended caps if we have them and the guest can see them */
  1926. if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) ||
  1927. !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) {
  1928. return;
  1929. }
  1930. /*
  1931. * pcie_add_capability always inserts the new capability at the tail
  1932. * of the chain. Therefore to end up with a chain that matches the
  1933. * physical device, we cache the config space to avoid overwriting
  1934. * the original config space when we parse the extended capabilities.
  1935. */
  1936. config = g_memdup(pdev->config, vdev->config_size);
  1937. /*
  1938. * Extended capabilities are chained with each pointing to the next, so we
  1939. * can drop anything other than the head of the chain simply by modifying
  1940. * the previous next pointer. Seed the head of the chain here such that
  1941. * we can simply skip any capabilities we want to drop below, regardless
  1942. * of their position in the chain. If this stub capability still exists
  1943. * after we add the capabilities we want to expose, update the capability
  1944. * ID to zero. Note that we cannot seed with the capability header being
  1945. * zero as this conflicts with definition of an absent capability chain
  1946. * and prevents capabilities beyond the head of the list from being added.
  1947. * By replacing the dummy capability ID with zero after walking the device
  1948. * chain, we also transparently mark extended capabilities as absent if
  1949. * no capabilities were added. Note that the PCIe spec defines an absence
  1950. * of extended capabilities to be determined by a value of zero for the
  1951. * capability ID, version, AND next pointer. A non-zero next pointer
  1952. * should be sufficient to indicate additional capabilities are present,
  1953. * which will occur if we call pcie_add_capability() below. The entire
  1954. * first dword is emulated to support this.
  1955. *
  1956. * NB. The kernel side does similar masking, so be prepared that our
  1957. * view of the device may also contain a capability ID zero in the head
  1958. * of the chain. Skip it for the same reason that we cannot seed the
  1959. * chain with a zero capability.
  1960. */
  1961. pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE,
  1962. PCI_EXT_CAP(0xFFFF, 0, 0));
  1963. pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0);
  1964. pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0);
  1965. for (next = PCI_CONFIG_SPACE_SIZE; next;
  1966. next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) {
  1967. header = pci_get_long(config + next);
  1968. cap_id = PCI_EXT_CAP_ID(header);
  1969. cap_ver = PCI_EXT_CAP_VER(header);
  1970. /*
  1971. * If it becomes important to configure extended capabilities to their
  1972. * actual size, use this as the default when it's something we don't
  1973. * recognize. Since QEMU doesn't actually handle many of the config
  1974. * accesses, exact size doesn't seem worthwhile.
  1975. */
  1976. size = vfio_ext_cap_max_size(config, next);
  1977. /* Use emulated next pointer to allow dropping extended caps */
  1978. pci_long_test_and_set_mask(vdev->emulated_config_bits + next,
  1979. PCI_EXT_CAP_NEXT_MASK);
  1980. switch (cap_id) {
  1981. case 0: /* kernel masked capability */
  1982. case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */
  1983. case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */
  1984. trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next);
  1985. break;
  1986. case PCI_EXT_CAP_ID_REBAR:
  1987. if (!vfio_setup_rebar_ecap(vdev, next)) {
  1988. pcie_add_capability(pdev, cap_id, cap_ver, next, size);
  1989. }
  1990. break;
  1991. default:
  1992. pcie_add_capability(pdev, cap_id, cap_ver, next, size);
  1993. }
  1994. }
  1995. /* Cleanup chain head ID if necessary */
  1996. if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) {
  1997. pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0);
  1998. }
  1999. g_free(config);
  2000. return;
  2001. }
  2002. static bool vfio_add_capabilities(VFIOPCIDevice *vdev, Error **errp)
  2003. {
  2004. PCIDevice *pdev = &vdev->pdev;
  2005. if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
  2006. !pdev->config[PCI_CAPABILITY_LIST]) {
  2007. return true; /* Nothing to add */
  2008. }
  2009. if (!vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp)) {
  2010. return false;
  2011. }
  2012. vfio_add_ext_cap(vdev);
  2013. return true;
  2014. }
  2015. void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
  2016. {
  2017. PCIDevice *pdev = &vdev->pdev;
  2018. uint16_t cmd;
  2019. vfio_disable_interrupts(vdev);
  2020. /* Make sure the device is in D0 */
  2021. if (vdev->pm_cap) {
  2022. uint16_t pmcsr;
  2023. uint8_t state;
  2024. pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
  2025. state = pmcsr & PCI_PM_CTRL_STATE_MASK;
  2026. if (state) {
  2027. pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
  2028. vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
  2029. /* vfio handles the necessary delay here */
  2030. pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
  2031. state = pmcsr & PCI_PM_CTRL_STATE_MASK;
  2032. if (state) {
  2033. error_report("vfio: Unable to power on device, stuck in D%d",
  2034. state);
  2035. }
  2036. }
  2037. }
  2038. /*
  2039. * Stop any ongoing DMA by disconnecting I/O, MMIO, and bus master.
  2040. * Also put INTx Disable in known state.
  2041. */
  2042. cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
  2043. cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
  2044. PCI_COMMAND_INTX_DISABLE);
  2045. vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
  2046. }
  2047. void vfio_pci_post_reset(VFIOPCIDevice *vdev)
  2048. {
  2049. Error *err = NULL;
  2050. int nr;
  2051. if (!vfio_intx_enable(vdev, &err)) {
  2052. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2053. }
  2054. for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) {
  2055. off_t addr = vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr);
  2056. uint32_t val = 0;
  2057. uint32_t len = sizeof(val);
  2058. if (pwrite(vdev->vbasedev.fd, &val, len, addr) != len) {
  2059. error_report("%s(%s) reset bar %d failed: %m", __func__,
  2060. vdev->vbasedev.name, nr);
  2061. }
  2062. }
  2063. vfio_quirk_reset(vdev);
  2064. }
  2065. bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
  2066. {
  2067. char tmp[13];
  2068. sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
  2069. addr->bus, addr->slot, addr->function);
  2070. return (strcmp(tmp, name) == 0);
  2071. }
  2072. int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev,
  2073. struct vfio_pci_hot_reset_info **info_p)
  2074. {
  2075. struct vfio_pci_hot_reset_info *info;
  2076. int ret, count;
  2077. assert(info_p && !*info_p);
  2078. info = g_malloc0(sizeof(*info));
  2079. info->argsz = sizeof(*info);
  2080. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
  2081. if (ret && errno != ENOSPC) {
  2082. ret = -errno;
  2083. g_free(info);
  2084. if (!vdev->has_pm_reset) {
  2085. error_report("vfio: Cannot reset device %s, "
  2086. "no available reset mechanism.", vdev->vbasedev.name);
  2087. }
  2088. return ret;
  2089. }
  2090. count = info->count;
  2091. info = g_realloc(info, sizeof(*info) + (count * sizeof(info->devices[0])));
  2092. info->argsz = sizeof(*info) + (count * sizeof(info->devices[0]));
  2093. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
  2094. if (ret) {
  2095. ret = -errno;
  2096. g_free(info);
  2097. error_report("vfio: hot reset info failed: %m");
  2098. return ret;
  2099. }
  2100. *info_p = info;
  2101. return 0;
  2102. }
  2103. static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
  2104. {
  2105. VFIODevice *vbasedev = &vdev->vbasedev;
  2106. const VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(vbasedev->bcontainer);
  2107. return vioc->pci_hot_reset(vbasedev, single);
  2108. }
  2109. /*
  2110. * We want to differentiate hot reset of multiple in-use devices vs hot reset
  2111. * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
  2112. * of doing hot resets when there is only a single device per bus. The in-use
  2113. * here refers to how many VFIODevices are affected. A hot reset that affects
  2114. * multiple devices, but only a single in-use device, means that we can call
  2115. * it from our bus ->reset() callback since the extent is effectively a single
  2116. * device. This allows us to make use of it in the hotplug path. When there
  2117. * are multiple in-use devices, we can only trigger the hot reset during a
  2118. * system reset and thus from our reset handler. We separate _one vs _multi
  2119. * here so that we don't overlap and do a double reset on the system reset
  2120. * path where both our reset handler and ->reset() callback are used. Calling
  2121. * _one() will only do a hot reset for the one in-use devices case, calling
  2122. * _multi() will do nothing if a _one() would have been sufficient.
  2123. */
  2124. static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
  2125. {
  2126. return vfio_pci_hot_reset(vdev, true);
  2127. }
  2128. static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
  2129. {
  2130. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2131. return vfio_pci_hot_reset(vdev, false);
  2132. }
  2133. static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
  2134. {
  2135. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2136. if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
  2137. vbasedev->needs_reset = true;
  2138. }
  2139. }
  2140. static Object *vfio_pci_get_object(VFIODevice *vbasedev)
  2141. {
  2142. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2143. return OBJECT(vdev);
  2144. }
  2145. static bool vfio_msix_present(void *opaque, int version_id)
  2146. {
  2147. PCIDevice *pdev = opaque;
  2148. return msix_present(pdev);
  2149. }
  2150. static bool vfio_display_migration_needed(void *opaque)
  2151. {
  2152. VFIOPCIDevice *vdev = opaque;
  2153. /*
  2154. * We need to migrate the VFIODisplay object if ramfb *migration* was
  2155. * explicitly requested (in which case we enforced both ramfb=on and
  2156. * display=on), or ramfb migration was left at the default "auto"
  2157. * setting, and *ramfb* was explicitly requested (in which case we
  2158. * enforced display=on).
  2159. */
  2160. return vdev->ramfb_migrate == ON_OFF_AUTO_ON ||
  2161. (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO && vdev->enable_ramfb);
  2162. }
  2163. static const VMStateDescription vmstate_vfio_display = {
  2164. .name = "VFIOPCIDevice/VFIODisplay",
  2165. .version_id = 1,
  2166. .minimum_version_id = 1,
  2167. .needed = vfio_display_migration_needed,
  2168. .fields = (const VMStateField[]){
  2169. VMSTATE_STRUCT_POINTER(dpy, VFIOPCIDevice, vfio_display_vmstate,
  2170. VFIODisplay),
  2171. VMSTATE_END_OF_LIST()
  2172. }
  2173. };
  2174. static const VMStateDescription vmstate_vfio_pci_config = {
  2175. .name = "VFIOPCIDevice",
  2176. .version_id = 1,
  2177. .minimum_version_id = 1,
  2178. .fields = (const VMStateField[]) {
  2179. VMSTATE_PCI_DEVICE(pdev, VFIOPCIDevice),
  2180. VMSTATE_MSIX_TEST(pdev, VFIOPCIDevice, vfio_msix_present),
  2181. VMSTATE_END_OF_LIST()
  2182. },
  2183. .subsections = (const VMStateDescription * const []) {
  2184. &vmstate_vfio_display,
  2185. NULL
  2186. }
  2187. };
  2188. static int vfio_pci_save_config(VFIODevice *vbasedev, QEMUFile *f, Error **errp)
  2189. {
  2190. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2191. return vmstate_save_state_with_err(f, &vmstate_vfio_pci_config, vdev, NULL,
  2192. errp);
  2193. }
  2194. static int vfio_pci_load_config(VFIODevice *vbasedev, QEMUFile *f)
  2195. {
  2196. VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
  2197. PCIDevice *pdev = &vdev->pdev;
  2198. pcibus_t old_addr[PCI_NUM_REGIONS - 1];
  2199. int bar, ret;
  2200. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  2201. old_addr[bar] = pdev->io_regions[bar].addr;
  2202. }
  2203. ret = vmstate_load_state(f, &vmstate_vfio_pci_config, vdev, 1);
  2204. if (ret) {
  2205. return ret;
  2206. }
  2207. vfio_pci_write_config(pdev, PCI_COMMAND,
  2208. pci_get_word(pdev->config + PCI_COMMAND), 2);
  2209. for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
  2210. /*
  2211. * The address may not be changed in some scenarios
  2212. * (e.g. the VF driver isn't loaded in VM).
  2213. */
  2214. if (old_addr[bar] != pdev->io_regions[bar].addr &&
  2215. vdev->bars[bar].region.size > 0 &&
  2216. vdev->bars[bar].region.size < qemu_real_host_page_size()) {
  2217. vfio_sub_page_bar_update_mapping(pdev, bar);
  2218. }
  2219. }
  2220. if (msi_enabled(pdev)) {
  2221. vfio_msi_enable(vdev);
  2222. } else if (msix_enabled(pdev)) {
  2223. vfio_msix_enable(vdev);
  2224. }
  2225. return ret;
  2226. }
  2227. static VFIODeviceOps vfio_pci_ops = {
  2228. .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
  2229. .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
  2230. .vfio_eoi = vfio_intx_eoi,
  2231. .vfio_get_object = vfio_pci_get_object,
  2232. .vfio_save_config = vfio_pci_save_config,
  2233. .vfio_load_config = vfio_pci_load_config,
  2234. };
  2235. bool vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp)
  2236. {
  2237. VFIODevice *vbasedev = &vdev->vbasedev;
  2238. g_autofree struct vfio_region_info *reg_info = NULL;
  2239. int ret;
  2240. ret = vfio_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, &reg_info);
  2241. if (ret) {
  2242. error_setg_errno(errp, -ret,
  2243. "failed getting region info for VGA region index %d",
  2244. VFIO_PCI_VGA_REGION_INDEX);
  2245. return false;
  2246. }
  2247. if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) ||
  2248. !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) ||
  2249. reg_info->size < 0xbffff + 1) {
  2250. error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx",
  2251. (unsigned long)reg_info->flags,
  2252. (unsigned long)reg_info->size);
  2253. return false;
  2254. }
  2255. vdev->vga = g_new0(VFIOVGA, 1);
  2256. vdev->vga->fd_offset = reg_info->offset;
  2257. vdev->vga->fd = vdev->vbasedev.fd;
  2258. vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
  2259. vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
  2260. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks);
  2261. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
  2262. OBJECT(vdev), &vfio_vga_ops,
  2263. &vdev->vga->region[QEMU_PCI_VGA_MEM],
  2264. "vfio-vga-mmio@0xa0000",
  2265. QEMU_PCI_VGA_MEM_SIZE);
  2266. vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
  2267. vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
  2268. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks);
  2269. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
  2270. OBJECT(vdev), &vfio_vga_ops,
  2271. &vdev->vga->region[QEMU_PCI_VGA_IO_LO],
  2272. "vfio-vga-io@0x3b0",
  2273. QEMU_PCI_VGA_IO_LO_SIZE);
  2274. vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
  2275. vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
  2276. QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks);
  2277. memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
  2278. OBJECT(vdev), &vfio_vga_ops,
  2279. &vdev->vga->region[QEMU_PCI_VGA_IO_HI],
  2280. "vfio-vga-io@0x3c0",
  2281. QEMU_PCI_VGA_IO_HI_SIZE);
  2282. pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
  2283. &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
  2284. &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem);
  2285. return true;
  2286. }
  2287. static bool vfio_populate_device(VFIOPCIDevice *vdev, Error **errp)
  2288. {
  2289. VFIODevice *vbasedev = &vdev->vbasedev;
  2290. g_autofree struct vfio_region_info *reg_info = NULL;
  2291. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
  2292. int i, ret = -1;
  2293. /* Sanity check device */
  2294. if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
  2295. error_setg(errp, "this isn't a PCI device");
  2296. return false;
  2297. }
  2298. if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
  2299. error_setg(errp, "unexpected number of io regions %u",
  2300. vbasedev->num_regions);
  2301. return false;
  2302. }
  2303. if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
  2304. error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs);
  2305. return false;
  2306. }
  2307. for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
  2308. char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i);
  2309. ret = vfio_region_setup(OBJECT(vdev), vbasedev,
  2310. &vdev->bars[i].region, i, name);
  2311. g_free(name);
  2312. if (ret) {
  2313. error_setg_errno(errp, -ret, "failed to get region %d info", i);
  2314. return false;
  2315. }
  2316. QLIST_INIT(&vdev->bars[i].quirks);
  2317. }
  2318. ret = vfio_get_region_info(vbasedev,
  2319. VFIO_PCI_CONFIG_REGION_INDEX, &reg_info);
  2320. if (ret) {
  2321. error_setg_errno(errp, -ret, "failed to get config info");
  2322. return false;
  2323. }
  2324. trace_vfio_populate_device_config(vdev->vbasedev.name,
  2325. (unsigned long)reg_info->size,
  2326. (unsigned long)reg_info->offset,
  2327. (unsigned long)reg_info->flags);
  2328. vdev->config_size = reg_info->size;
  2329. if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
  2330. vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
  2331. }
  2332. vdev->config_offset = reg_info->offset;
  2333. if (vdev->features & VFIO_FEATURE_ENABLE_VGA) {
  2334. if (!vfio_populate_vga(vdev, errp)) {
  2335. error_append_hint(errp, "device does not support "
  2336. "requested feature x-vga\n");
  2337. return false;
  2338. }
  2339. }
  2340. irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
  2341. ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
  2342. if (ret) {
  2343. /* This can fail for an old kernel or legacy PCI dev */
  2344. trace_vfio_populate_device_get_irq_info_failure(strerror(errno));
  2345. } else if (irq_info.count == 1) {
  2346. vdev->pci_aer = true;
  2347. } else {
  2348. warn_report(VFIO_MSG_PREFIX
  2349. "Could not enable error recovery for the device",
  2350. vbasedev->name);
  2351. }
  2352. return true;
  2353. }
  2354. static void vfio_pci_put_device(VFIOPCIDevice *vdev)
  2355. {
  2356. vfio_detach_device(&vdev->vbasedev);
  2357. g_free(vdev->vbasedev.name);
  2358. g_free(vdev->msix);
  2359. }
  2360. static void vfio_err_notifier_handler(void *opaque)
  2361. {
  2362. VFIOPCIDevice *vdev = opaque;
  2363. if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
  2364. return;
  2365. }
  2366. /*
  2367. * TBD. Retrieve the error details and decide what action
  2368. * needs to be taken. One of the actions could be to pass
  2369. * the error to the guest and have the guest driver recover
  2370. * from the error. This requires that PCIe capabilities be
  2371. * exposed to the guest. For now, we just terminate the
  2372. * guest to contain the error.
  2373. */
  2374. error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name);
  2375. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2376. }
  2377. /*
  2378. * Registers error notifier for devices supporting error recovery.
  2379. * If we encounter a failure in this function, we report an error
  2380. * and continue after disabling error recovery support for the
  2381. * device.
  2382. */
  2383. static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
  2384. {
  2385. Error *err = NULL;
  2386. int32_t fd;
  2387. if (!vdev->pci_aer) {
  2388. return;
  2389. }
  2390. if (event_notifier_init(&vdev->err_notifier, 0)) {
  2391. error_report("vfio: Unable to init event notifier for error detection");
  2392. vdev->pci_aer = false;
  2393. return;
  2394. }
  2395. fd = event_notifier_get_fd(&vdev->err_notifier);
  2396. qemu_set_fd_handler(fd, vfio_err_notifier_handler, NULL, vdev);
  2397. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
  2398. VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
  2399. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2400. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  2401. event_notifier_cleanup(&vdev->err_notifier);
  2402. vdev->pci_aer = false;
  2403. }
  2404. }
  2405. static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
  2406. {
  2407. Error *err = NULL;
  2408. if (!vdev->pci_aer) {
  2409. return;
  2410. }
  2411. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
  2412. VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
  2413. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2414. }
  2415. qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
  2416. NULL, NULL, vdev);
  2417. event_notifier_cleanup(&vdev->err_notifier);
  2418. }
  2419. static void vfio_req_notifier_handler(void *opaque)
  2420. {
  2421. VFIOPCIDevice *vdev = opaque;
  2422. Error *err = NULL;
  2423. if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
  2424. return;
  2425. }
  2426. qdev_unplug(DEVICE(vdev), &err);
  2427. if (err) {
  2428. warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2429. }
  2430. }
  2431. static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
  2432. {
  2433. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
  2434. .index = VFIO_PCI_REQ_IRQ_INDEX };
  2435. Error *err = NULL;
  2436. int32_t fd;
  2437. if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
  2438. return;
  2439. }
  2440. if (ioctl(vdev->vbasedev.fd,
  2441. VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
  2442. return;
  2443. }
  2444. if (event_notifier_init(&vdev->req_notifier, 0)) {
  2445. error_report("vfio: Unable to init event notifier for device request");
  2446. return;
  2447. }
  2448. fd = event_notifier_get_fd(&vdev->req_notifier);
  2449. qemu_set_fd_handler(fd, vfio_req_notifier_handler, NULL, vdev);
  2450. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
  2451. VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
  2452. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2453. qemu_set_fd_handler(fd, NULL, NULL, vdev);
  2454. event_notifier_cleanup(&vdev->req_notifier);
  2455. } else {
  2456. vdev->req_enabled = true;
  2457. }
  2458. }
  2459. static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
  2460. {
  2461. Error *err = NULL;
  2462. if (!vdev->req_enabled) {
  2463. return;
  2464. }
  2465. if (!vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
  2466. VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
  2467. error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
  2468. }
  2469. qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
  2470. NULL, NULL, vdev);
  2471. event_notifier_cleanup(&vdev->req_notifier);
  2472. vdev->req_enabled = false;
  2473. }
  2474. static void vfio_realize(PCIDevice *pdev, Error **errp)
  2475. {
  2476. ERRP_GUARD();
  2477. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  2478. VFIODevice *vbasedev = &vdev->vbasedev;
  2479. int i, ret;
  2480. char uuid[UUID_STR_LEN];
  2481. g_autofree char *name = NULL;
  2482. if (vbasedev->fd < 0 && !vbasedev->sysfsdev) {
  2483. if (!(~vdev->host.domain || ~vdev->host.bus ||
  2484. ~vdev->host.slot || ~vdev->host.function)) {
  2485. error_setg(errp, "No provided host device");
  2486. error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
  2487. #ifdef CONFIG_IOMMUFD
  2488. "or -device vfio-pci,fd=DEVICE_FD "
  2489. #endif
  2490. "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
  2491. return;
  2492. }
  2493. vbasedev->sysfsdev =
  2494. g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
  2495. vdev->host.domain, vdev->host.bus,
  2496. vdev->host.slot, vdev->host.function);
  2497. }
  2498. if (!vfio_device_get_name(vbasedev, errp)) {
  2499. return;
  2500. }
  2501. /*
  2502. * Mediated devices *might* operate compatibly with discarding of RAM, but
  2503. * we cannot know for certain, it depends on whether the mdev vendor driver
  2504. * stays in sync with the active working set of the guest driver. Prevent
  2505. * the x-balloon-allowed option unless this is minimally an mdev device.
  2506. */
  2507. vbasedev->mdev = vfio_device_is_mdev(vbasedev);
  2508. trace_vfio_mdev(vbasedev->name, vbasedev->mdev);
  2509. if (vbasedev->ram_block_discard_allowed && !vbasedev->mdev) {
  2510. error_setg(errp, "x-balloon-allowed only potentially compatible "
  2511. "with mdev devices");
  2512. goto error;
  2513. }
  2514. if (!qemu_uuid_is_null(&vdev->vf_token)) {
  2515. qemu_uuid_unparse(&vdev->vf_token, uuid);
  2516. name = g_strdup_printf("%s vf_token=%s", vbasedev->name, uuid);
  2517. } else {
  2518. name = g_strdup(vbasedev->name);
  2519. }
  2520. if (!vfio_attach_device(name, vbasedev,
  2521. pci_device_iommu_address_space(pdev), errp)) {
  2522. goto error;
  2523. }
  2524. if (!vfio_populate_device(vdev, errp)) {
  2525. goto error;
  2526. }
  2527. /* Get a copy of config space */
  2528. ret = pread(vbasedev->fd, vdev->pdev.config,
  2529. MIN(pci_config_size(&vdev->pdev), vdev->config_size),
  2530. vdev->config_offset);
  2531. if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
  2532. ret = ret < 0 ? -errno : -EFAULT;
  2533. error_setg_errno(errp, -ret, "failed to read device config space");
  2534. goto error;
  2535. }
  2536. /* vfio emulates a lot for us, but some bits need extra love */
  2537. vdev->emulated_config_bits = g_malloc0(vdev->config_size);
  2538. /* QEMU can choose to expose the ROM or not */
  2539. memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
  2540. /* QEMU can also add or extend BARs */
  2541. memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4);
  2542. /*
  2543. * The PCI spec reserves vendor ID 0xffff as an invalid value. The
  2544. * device ID is managed by the vendor and need only be a 16-bit value.
  2545. * Allow any 16-bit value for subsystem so they can be hidden or changed.
  2546. */
  2547. if (vdev->vendor_id != PCI_ANY_ID) {
  2548. if (vdev->vendor_id >= 0xffff) {
  2549. error_setg(errp, "invalid PCI vendor ID provided");
  2550. goto error;
  2551. }
  2552. vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
  2553. trace_vfio_pci_emulated_vendor_id(vbasedev->name, vdev->vendor_id);
  2554. } else {
  2555. vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
  2556. }
  2557. if (vdev->device_id != PCI_ANY_ID) {
  2558. if (vdev->device_id > 0xffff) {
  2559. error_setg(errp, "invalid PCI device ID provided");
  2560. goto error;
  2561. }
  2562. vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
  2563. trace_vfio_pci_emulated_device_id(vbasedev->name, vdev->device_id);
  2564. } else {
  2565. vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
  2566. }
  2567. if (vdev->sub_vendor_id != PCI_ANY_ID) {
  2568. if (vdev->sub_vendor_id > 0xffff) {
  2569. error_setg(errp, "invalid PCI subsystem vendor ID provided");
  2570. goto error;
  2571. }
  2572. vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
  2573. vdev->sub_vendor_id, ~0);
  2574. trace_vfio_pci_emulated_sub_vendor_id(vbasedev->name,
  2575. vdev->sub_vendor_id);
  2576. }
  2577. if (vdev->sub_device_id != PCI_ANY_ID) {
  2578. if (vdev->sub_device_id > 0xffff) {
  2579. error_setg(errp, "invalid PCI subsystem device ID provided");
  2580. goto error;
  2581. }
  2582. vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
  2583. trace_vfio_pci_emulated_sub_device_id(vbasedev->name,
  2584. vdev->sub_device_id);
  2585. }
  2586. /* QEMU can change multi-function devices to single function, or reverse */
  2587. vdev->emulated_config_bits[PCI_HEADER_TYPE] =
  2588. PCI_HEADER_TYPE_MULTI_FUNCTION;
  2589. /* Restore or clear multifunction, this is always controlled by QEMU */
  2590. if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
  2591. vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
  2592. } else {
  2593. vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
  2594. }
  2595. /*
  2596. * Clear host resource mapping info. If we choose not to register a
  2597. * BAR, such as might be the case with the option ROM, we can get
  2598. * confusing, unwritable, residual addresses from the host here.
  2599. */
  2600. memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
  2601. memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
  2602. vfio_pci_size_rom(vdev);
  2603. vfio_bars_prepare(vdev);
  2604. if (!vfio_msix_early_setup(vdev, errp)) {
  2605. goto error;
  2606. }
  2607. vfio_bars_register(vdev);
  2608. if (!vbasedev->mdev &&
  2609. !pci_device_set_iommu_device(pdev, vbasedev->hiod, errp)) {
  2610. error_prepend(errp, "Failed to set iommu_device: ");
  2611. goto out_teardown;
  2612. }
  2613. if (!vfio_add_capabilities(vdev, errp)) {
  2614. goto out_unset_idev;
  2615. }
  2616. if (vdev->vga) {
  2617. vfio_vga_quirk_setup(vdev);
  2618. }
  2619. for (i = 0; i < PCI_ROM_SLOT; i++) {
  2620. vfio_bar_quirk_setup(vdev, i);
  2621. }
  2622. if (!vdev->igd_opregion &&
  2623. vdev->features & VFIO_FEATURE_ENABLE_IGD_OPREGION) {
  2624. g_autofree struct vfio_region_info *opregion = NULL;
  2625. if (vdev->pdev.qdev.hotplugged) {
  2626. error_setg(errp,
  2627. "cannot support IGD OpRegion feature on hotplugged "
  2628. "device");
  2629. goto out_unset_idev;
  2630. }
  2631. ret = vfio_get_dev_region_info(vbasedev,
  2632. VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
  2633. VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
  2634. if (ret) {
  2635. error_setg_errno(errp, -ret,
  2636. "does not support requested IGD OpRegion feature");
  2637. goto out_unset_idev;
  2638. }
  2639. if (!vfio_pci_igd_opregion_init(vdev, opregion, errp)) {
  2640. goto out_unset_idev;
  2641. }
  2642. }
  2643. /* QEMU emulates all of MSI & MSIX */
  2644. if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
  2645. memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
  2646. MSIX_CAP_LENGTH);
  2647. }
  2648. if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
  2649. memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
  2650. vdev->msi_cap_size);
  2651. }
  2652. if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
  2653. vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
  2654. vfio_intx_mmap_enable, vdev);
  2655. pci_device_set_intx_routing_notifier(&vdev->pdev,
  2656. vfio_intx_routing_notifier);
  2657. vdev->irqchip_change_notifier.notify = vfio_irqchip_change;
  2658. kvm_irqchip_add_change_notifier(&vdev->irqchip_change_notifier);
  2659. if (!vfio_intx_enable(vdev, errp)) {
  2660. goto out_deregister;
  2661. }
  2662. }
  2663. if (vdev->display != ON_OFF_AUTO_OFF) {
  2664. if (!vfio_display_probe(vdev, errp)) {
  2665. goto out_deregister;
  2666. }
  2667. }
  2668. if (vdev->enable_ramfb && vdev->dpy == NULL) {
  2669. error_setg(errp, "ramfb=on requires display=on");
  2670. goto out_deregister;
  2671. }
  2672. if (vdev->display_xres || vdev->display_yres) {
  2673. if (vdev->dpy == NULL) {
  2674. error_setg(errp, "xres and yres properties require display=on");
  2675. goto out_deregister;
  2676. }
  2677. if (vdev->dpy->edid_regs == NULL) {
  2678. error_setg(errp, "xres and yres properties need edid support");
  2679. goto out_deregister;
  2680. }
  2681. }
  2682. if (vdev->ramfb_migrate == ON_OFF_AUTO_ON && !vdev->enable_ramfb) {
  2683. warn_report("x-ramfb-migrate=on but ramfb=off. "
  2684. "Forcing x-ramfb-migrate to off.");
  2685. vdev->ramfb_migrate = ON_OFF_AUTO_OFF;
  2686. }
  2687. if (vbasedev->enable_migration == ON_OFF_AUTO_OFF) {
  2688. if (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO) {
  2689. vdev->ramfb_migrate = ON_OFF_AUTO_OFF;
  2690. } else if (vdev->ramfb_migrate == ON_OFF_AUTO_ON) {
  2691. error_setg(errp, "x-ramfb-migrate requires enable-migration");
  2692. goto out_deregister;
  2693. }
  2694. }
  2695. if (!pdev->failover_pair_id) {
  2696. if (!vfio_migration_realize(vbasedev, errp)) {
  2697. goto out_deregister;
  2698. }
  2699. }
  2700. vfio_register_err_notifier(vdev);
  2701. vfio_register_req_notifier(vdev);
  2702. vfio_setup_resetfn_quirk(vdev);
  2703. return;
  2704. out_deregister:
  2705. if (vdev->interrupt == VFIO_INT_INTx) {
  2706. vfio_intx_disable(vdev);
  2707. }
  2708. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  2709. if (vdev->irqchip_change_notifier.notify) {
  2710. kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
  2711. }
  2712. if (vdev->intx.mmap_timer) {
  2713. timer_free(vdev->intx.mmap_timer);
  2714. }
  2715. out_unset_idev:
  2716. if (!vbasedev->mdev) {
  2717. pci_device_unset_iommu_device(pdev);
  2718. }
  2719. out_teardown:
  2720. vfio_teardown_msi(vdev);
  2721. vfio_bars_exit(vdev);
  2722. error:
  2723. error_prepend(errp, VFIO_MSG_PREFIX, vbasedev->name);
  2724. }
  2725. static void vfio_instance_finalize(Object *obj)
  2726. {
  2727. VFIOPCIDevice *vdev = VFIO_PCI(obj);
  2728. vfio_display_finalize(vdev);
  2729. vfio_bars_finalize(vdev);
  2730. g_free(vdev->emulated_config_bits);
  2731. g_free(vdev->rom);
  2732. /*
  2733. * XXX Leaking igd_opregion is not an oversight, we can't remove the
  2734. * fw_cfg entry therefore leaking this allocation seems like the safest
  2735. * option.
  2736. *
  2737. * g_free(vdev->igd_opregion);
  2738. */
  2739. vfio_pci_put_device(vdev);
  2740. }
  2741. static void vfio_exitfn(PCIDevice *pdev)
  2742. {
  2743. VFIOPCIDevice *vdev = VFIO_PCI(pdev);
  2744. VFIODevice *vbasedev = &vdev->vbasedev;
  2745. vfio_unregister_req_notifier(vdev);
  2746. vfio_unregister_err_notifier(vdev);
  2747. pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
  2748. if (vdev->irqchip_change_notifier.notify) {
  2749. kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
  2750. }
  2751. vfio_disable_interrupts(vdev);
  2752. if (vdev->intx.mmap_timer) {
  2753. timer_free(vdev->intx.mmap_timer);
  2754. }
  2755. vfio_teardown_msi(vdev);
  2756. vfio_pci_disable_rp_atomics(vdev);
  2757. vfio_bars_exit(vdev);
  2758. vfio_migration_exit(vbasedev);
  2759. if (!vbasedev->mdev) {
  2760. pci_device_unset_iommu_device(pdev);
  2761. }
  2762. }
  2763. static void vfio_pci_reset(DeviceState *dev)
  2764. {
  2765. VFIOPCIDevice *vdev = VFIO_PCI(dev);
  2766. trace_vfio_pci_reset(vdev->vbasedev.name);
  2767. vfio_pci_pre_reset(vdev);
  2768. if (vdev->display != ON_OFF_AUTO_OFF) {
  2769. vfio_display_reset(vdev);
  2770. }
  2771. if (vdev->resetfn && !vdev->resetfn(vdev)) {
  2772. goto post_reset;
  2773. }
  2774. if (vdev->vbasedev.reset_works &&
  2775. (vdev->has_flr || !vdev->has_pm_reset) &&
  2776. !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
  2777. trace_vfio_pci_reset_flr(vdev->vbasedev.name);
  2778. goto post_reset;
  2779. }
  2780. /* See if we can do our own bus reset */
  2781. if (!vfio_pci_hot_reset_one(vdev)) {
  2782. goto post_reset;
  2783. }
  2784. /* If nothing else works and the device supports PM reset, use it */
  2785. if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
  2786. !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
  2787. trace_vfio_pci_reset_pm(vdev->vbasedev.name);
  2788. goto post_reset;
  2789. }
  2790. post_reset:
  2791. vfio_pci_post_reset(vdev);
  2792. }
  2793. static void vfio_instance_init(Object *obj)
  2794. {
  2795. PCIDevice *pci_dev = PCI_DEVICE(obj);
  2796. VFIOPCIDevice *vdev = VFIO_PCI(obj);
  2797. VFIODevice *vbasedev = &vdev->vbasedev;
  2798. device_add_bootindex_property(obj, &vdev->bootindex,
  2799. "bootindex", NULL,
  2800. &pci_dev->qdev);
  2801. vdev->host.domain = ~0U;
  2802. vdev->host.bus = ~0U;
  2803. vdev->host.slot = ~0U;
  2804. vdev->host.function = ~0U;
  2805. vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_PCI, &vfio_pci_ops,
  2806. DEVICE(vdev), false);
  2807. vdev->nv_gpudirect_clique = 0xFF;
  2808. /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
  2809. * line, therefore, no need to wait to realize like other devices */
  2810. pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
  2811. }
  2812. static const Property vfio_pci_dev_properties[] = {
  2813. DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
  2814. DEFINE_PROP_UUID_NODEFAULT("vf-token", VFIOPCIDevice, vf_token),
  2815. DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev),
  2816. DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice,
  2817. vbasedev.pre_copy_dirty_page_tracking,
  2818. ON_OFF_AUTO_ON),
  2819. DEFINE_PROP_ON_OFF_AUTO("x-device-dirty-page-tracking", VFIOPCIDevice,
  2820. vbasedev.device_dirty_page_tracking,
  2821. ON_OFF_AUTO_ON),
  2822. DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice,
  2823. display, ON_OFF_AUTO_OFF),
  2824. DEFINE_PROP_UINT32("xres", VFIOPCIDevice, display_xres, 0),
  2825. DEFINE_PROP_UINT32("yres", VFIOPCIDevice, display_yres, 0),
  2826. DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
  2827. intx.mmap_timeout, 1100),
  2828. DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
  2829. VFIO_FEATURE_ENABLE_VGA_BIT, false),
  2830. DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
  2831. VFIO_FEATURE_ENABLE_REQ_BIT, true),
  2832. DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features,
  2833. VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, false),
  2834. DEFINE_PROP_ON_OFF_AUTO("enable-migration", VFIOPCIDevice,
  2835. vbasedev.enable_migration, ON_OFF_AUTO_AUTO),
  2836. DEFINE_PROP_BOOL("migration-events", VFIOPCIDevice,
  2837. vbasedev.migration_events, false),
  2838. DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
  2839. DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice,
  2840. vbasedev.ram_block_discard_allowed, false),
  2841. DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
  2842. DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
  2843. DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
  2844. DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice,
  2845. no_geforce_quirks, false),
  2846. DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice, no_kvm_ioeventfd,
  2847. false),
  2848. DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice, no_vfio_ioeventfd,
  2849. false),
  2850. DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID),
  2851. DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID),
  2852. DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice,
  2853. sub_vendor_id, PCI_ANY_ID),
  2854. DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice,
  2855. sub_device_id, PCI_ANY_ID),
  2856. DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0),
  2857. DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice,
  2858. nv_gpudirect_clique,
  2859. qdev_prop_nv_gpudirect_clique, uint8_t),
  2860. DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
  2861. OFF_AUTO_PCIBAR_OFF),
  2862. #ifdef CONFIG_IOMMUFD
  2863. DEFINE_PROP_LINK("iommufd", VFIOPCIDevice, vbasedev.iommufd,
  2864. TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *),
  2865. #endif
  2866. DEFINE_PROP_BOOL("skip-vsc-check", VFIOPCIDevice, skip_vsc_check, true),
  2867. };
  2868. #ifdef CONFIG_IOMMUFD
  2869. static void vfio_pci_set_fd(Object *obj, const char *str, Error **errp)
  2870. {
  2871. vfio_device_set_fd(&VFIO_PCI(obj)->vbasedev, str, errp);
  2872. }
  2873. #endif
  2874. static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
  2875. {
  2876. DeviceClass *dc = DEVICE_CLASS(klass);
  2877. PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
  2878. device_class_set_legacy_reset(dc, vfio_pci_reset);
  2879. device_class_set_props(dc, vfio_pci_dev_properties);
  2880. #ifdef CONFIG_IOMMUFD
  2881. object_class_property_add_str(klass, "fd", NULL, vfio_pci_set_fd);
  2882. #endif
  2883. dc->desc = "VFIO-based PCI device assignment";
  2884. set_bit(DEVICE_CATEGORY_MISC, dc->categories);
  2885. pdc->realize = vfio_realize;
  2886. pdc->exit = vfio_exitfn;
  2887. pdc->config_read = vfio_pci_read_config;
  2888. pdc->config_write = vfio_pci_write_config;
  2889. }
  2890. static const TypeInfo vfio_pci_dev_info = {
  2891. .name = TYPE_VFIO_PCI,
  2892. .parent = TYPE_PCI_DEVICE,
  2893. .instance_size = sizeof(VFIOPCIDevice),
  2894. .class_init = vfio_pci_dev_class_init,
  2895. .instance_init = vfio_instance_init,
  2896. .instance_finalize = vfio_instance_finalize,
  2897. .interfaces = (InterfaceInfo[]) {
  2898. { INTERFACE_PCIE_DEVICE },
  2899. { INTERFACE_CONVENTIONAL_PCI_DEVICE },
  2900. { }
  2901. },
  2902. };
  2903. static const Property vfio_pci_dev_nohotplug_properties[] = {
  2904. DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice, enable_ramfb, false),
  2905. DEFINE_PROP_ON_OFF_AUTO("x-ramfb-migrate", VFIOPCIDevice, ramfb_migrate,
  2906. ON_OFF_AUTO_AUTO),
  2907. };
  2908. static void vfio_pci_nohotplug_dev_class_init(ObjectClass *klass, void *data)
  2909. {
  2910. DeviceClass *dc = DEVICE_CLASS(klass);
  2911. device_class_set_props(dc, vfio_pci_dev_nohotplug_properties);
  2912. dc->hotpluggable = false;
  2913. }
  2914. static const TypeInfo vfio_pci_nohotplug_dev_info = {
  2915. .name = TYPE_VFIO_PCI_NOHOTPLUG,
  2916. .parent = TYPE_VFIO_PCI,
  2917. .instance_size = sizeof(VFIOPCIDevice),
  2918. .class_init = vfio_pci_nohotplug_dev_class_init,
  2919. };
  2920. static void register_vfio_pci_dev_type(void)
  2921. {
  2922. type_register_static(&vfio_pci_dev_info);
  2923. type_register_static(&vfio_pci_nohotplug_dev_info);
  2924. }
  2925. type_init(register_vfio_pci_dev_type)