2
0

kvm-all.c 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376
  1. /*
  2. * QEMU KVM support
  3. *
  4. * Copyright IBM, Corp. 2008
  5. * Red Hat, Inc. 2008
  6. *
  7. * Authors:
  8. * Anthony Liguori <aliguori@us.ibm.com>
  9. * Glauber Costa <gcosta@redhat.com>
  10. *
  11. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  12. * See the COPYING file in the top-level directory.
  13. *
  14. */
  15. #include "qemu/osdep.h"
  16. #include <sys/ioctl.h>
  17. #include <poll.h>
  18. #include <linux/kvm.h>
  19. #include "qemu/atomic.h"
  20. #include "qemu/option.h"
  21. #include "qemu/config-file.h"
  22. #include "qemu/error-report.h"
  23. #include "qapi/error.h"
  24. #include "hw/pci/msi.h"
  25. #include "hw/pci/msix.h"
  26. #include "hw/s390x/adapter.h"
  27. #include "gdbstub/enums.h"
  28. #include "sysemu/kvm_int.h"
  29. #include "sysemu/runstate.h"
  30. #include "sysemu/cpus.h"
  31. #include "sysemu/accel-blocker.h"
  32. #include "qemu/bswap.h"
  33. #include "exec/memory.h"
  34. #include "exec/ram_addr.h"
  35. #include "qemu/event_notifier.h"
  36. #include "qemu/main-loop.h"
  37. #include "trace.h"
  38. #include "hw/irq.h"
  39. #include "qapi/visitor.h"
  40. #include "qapi/qapi-types-common.h"
  41. #include "qapi/qapi-visit-common.h"
  42. #include "sysemu/reset.h"
  43. #include "qemu/guest-random.h"
  44. #include "sysemu/hw_accel.h"
  45. #include "kvm-cpus.h"
  46. #include "sysemu/dirtylimit.h"
  47. #include "qemu/range.h"
  48. #include "hw/boards.h"
  49. #include "sysemu/stats.h"
  50. /* This check must be after config-host.h is included */
  51. #ifdef CONFIG_EVENTFD
  52. #include <sys/eventfd.h>
  53. #endif
  54. /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
  55. * need to use the real host PAGE_SIZE, as that's what KVM will use.
  56. */
  57. #ifdef PAGE_SIZE
  58. #undef PAGE_SIZE
  59. #endif
  60. #define PAGE_SIZE qemu_real_host_page_size()
  61. #ifndef KVM_GUESTDBG_BLOCKIRQ
  62. #define KVM_GUESTDBG_BLOCKIRQ 0
  63. #endif
  64. struct KVMParkedVcpu {
  65. unsigned long vcpu_id;
  66. int kvm_fd;
  67. QLIST_ENTRY(KVMParkedVcpu) node;
  68. };
  69. KVMState *kvm_state;
  70. bool kvm_kernel_irqchip;
  71. bool kvm_split_irqchip;
  72. bool kvm_async_interrupts_allowed;
  73. bool kvm_halt_in_kernel_allowed;
  74. bool kvm_resamplefds_allowed;
  75. bool kvm_msi_via_irqfd_allowed;
  76. bool kvm_gsi_routing_allowed;
  77. bool kvm_gsi_direct_mapping;
  78. bool kvm_allowed;
  79. bool kvm_readonly_mem_allowed;
  80. bool kvm_vm_attributes_allowed;
  81. bool kvm_msi_use_devid;
  82. static bool kvm_has_guest_debug;
  83. static int kvm_sstep_flags;
  84. static bool kvm_immediate_exit;
  85. static uint64_t kvm_supported_memory_attributes;
  86. static bool kvm_guest_memfd_supported;
  87. static hwaddr kvm_max_slot_size = ~0;
  88. static const KVMCapabilityInfo kvm_required_capabilites[] = {
  89. KVM_CAP_INFO(USER_MEMORY),
  90. KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
  91. KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
  92. KVM_CAP_INFO(INTERNAL_ERROR_DATA),
  93. KVM_CAP_INFO(IOEVENTFD),
  94. KVM_CAP_INFO(IOEVENTFD_ANY_LENGTH),
  95. KVM_CAP_LAST_INFO
  96. };
  97. static NotifierList kvm_irqchip_change_notifiers =
  98. NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
  99. struct KVMResampleFd {
  100. int gsi;
  101. EventNotifier *resample_event;
  102. QLIST_ENTRY(KVMResampleFd) node;
  103. };
  104. typedef struct KVMResampleFd KVMResampleFd;
  105. /*
  106. * Only used with split irqchip where we need to do the resample fd
  107. * kick for the kernel from userspace.
  108. */
  109. static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
  110. QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
  111. static QemuMutex kml_slots_lock;
  112. #define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
  113. #define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
  114. static void kvm_slot_init_dirty_bitmap(KVMSlot *mem);
  115. static inline void kvm_resample_fd_remove(int gsi)
  116. {
  117. KVMResampleFd *rfd;
  118. QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
  119. if (rfd->gsi == gsi) {
  120. QLIST_REMOVE(rfd, node);
  121. g_free(rfd);
  122. break;
  123. }
  124. }
  125. }
  126. static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
  127. {
  128. KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
  129. rfd->gsi = gsi;
  130. rfd->resample_event = event;
  131. QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
  132. }
  133. void kvm_resample_fd_notify(int gsi)
  134. {
  135. KVMResampleFd *rfd;
  136. QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
  137. if (rfd->gsi == gsi) {
  138. event_notifier_set(rfd->resample_event);
  139. trace_kvm_resample_fd_notify(gsi);
  140. return;
  141. }
  142. }
  143. }
  144. unsigned int kvm_get_max_memslots(void)
  145. {
  146. KVMState *s = KVM_STATE(current_accel());
  147. return s->nr_slots;
  148. }
  149. unsigned int kvm_get_free_memslots(void)
  150. {
  151. unsigned int used_slots = 0;
  152. KVMState *s = kvm_state;
  153. int i;
  154. kvm_slots_lock();
  155. for (i = 0; i < s->nr_as; i++) {
  156. if (!s->as[i].ml) {
  157. continue;
  158. }
  159. used_slots = MAX(used_slots, s->as[i].ml->nr_used_slots);
  160. }
  161. kvm_slots_unlock();
  162. return s->nr_slots - used_slots;
  163. }
  164. /* Called with KVMMemoryListener.slots_lock held */
  165. static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
  166. {
  167. KVMState *s = kvm_state;
  168. int i;
  169. for (i = 0; i < s->nr_slots; i++) {
  170. if (kml->slots[i].memory_size == 0) {
  171. return &kml->slots[i];
  172. }
  173. }
  174. return NULL;
  175. }
  176. /* Called with KVMMemoryListener.slots_lock held */
  177. static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
  178. {
  179. KVMSlot *slot = kvm_get_free_slot(kml);
  180. if (slot) {
  181. return slot;
  182. }
  183. fprintf(stderr, "%s: no free slot available\n", __func__);
  184. abort();
  185. }
  186. static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
  187. hwaddr start_addr,
  188. hwaddr size)
  189. {
  190. KVMState *s = kvm_state;
  191. int i;
  192. for (i = 0; i < s->nr_slots; i++) {
  193. KVMSlot *mem = &kml->slots[i];
  194. if (start_addr == mem->start_addr && size == mem->memory_size) {
  195. return mem;
  196. }
  197. }
  198. return NULL;
  199. }
  200. /*
  201. * Calculate and align the start address and the size of the section.
  202. * Return the size. If the size is 0, the aligned section is empty.
  203. */
  204. static hwaddr kvm_align_section(MemoryRegionSection *section,
  205. hwaddr *start)
  206. {
  207. hwaddr size = int128_get64(section->size);
  208. hwaddr delta, aligned;
  209. /* kvm works in page size chunks, but the function may be called
  210. with sub-page size and unaligned start address. Pad the start
  211. address to next and truncate size to previous page boundary. */
  212. aligned = ROUND_UP(section->offset_within_address_space,
  213. qemu_real_host_page_size());
  214. delta = aligned - section->offset_within_address_space;
  215. *start = aligned;
  216. if (delta > size) {
  217. return 0;
  218. }
  219. return (size - delta) & qemu_real_host_page_mask();
  220. }
  221. int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
  222. hwaddr *phys_addr)
  223. {
  224. KVMMemoryListener *kml = &s->memory_listener;
  225. int i, ret = 0;
  226. kvm_slots_lock();
  227. for (i = 0; i < s->nr_slots; i++) {
  228. KVMSlot *mem = &kml->slots[i];
  229. if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
  230. *phys_addr = mem->start_addr + (ram - mem->ram);
  231. ret = 1;
  232. break;
  233. }
  234. }
  235. kvm_slots_unlock();
  236. return ret;
  237. }
  238. static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
  239. {
  240. KVMState *s = kvm_state;
  241. struct kvm_userspace_memory_region2 mem;
  242. int ret;
  243. mem.slot = slot->slot | (kml->as_id << 16);
  244. mem.guest_phys_addr = slot->start_addr;
  245. mem.userspace_addr = (unsigned long)slot->ram;
  246. mem.flags = slot->flags;
  247. mem.guest_memfd = slot->guest_memfd;
  248. mem.guest_memfd_offset = slot->guest_memfd_offset;
  249. if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
  250. /* Set the slot size to 0 before setting the slot to the desired
  251. * value. This is needed based on KVM commit 75d61fbc. */
  252. mem.memory_size = 0;
  253. if (kvm_guest_memfd_supported) {
  254. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
  255. } else {
  256. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  257. }
  258. if (ret < 0) {
  259. goto err;
  260. }
  261. }
  262. mem.memory_size = slot->memory_size;
  263. if (kvm_guest_memfd_supported) {
  264. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
  265. } else {
  266. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  267. }
  268. slot->old_flags = mem.flags;
  269. err:
  270. trace_kvm_set_user_memory(mem.slot >> 16, (uint16_t)mem.slot, mem.flags,
  271. mem.guest_phys_addr, mem.memory_size,
  272. mem.userspace_addr, mem.guest_memfd,
  273. mem.guest_memfd_offset, ret);
  274. if (ret < 0) {
  275. if (kvm_guest_memfd_supported) {
  276. error_report("%s: KVM_SET_USER_MEMORY_REGION2 failed, slot=%d,"
  277. " start=0x%" PRIx64 ", size=0x%" PRIx64 ","
  278. " flags=0x%" PRIx32 ", guest_memfd=%" PRId32 ","
  279. " guest_memfd_offset=0x%" PRIx64 ": %s",
  280. __func__, mem.slot, slot->start_addr,
  281. (uint64_t)mem.memory_size, mem.flags,
  282. mem.guest_memfd, (uint64_t)mem.guest_memfd_offset,
  283. strerror(errno));
  284. } else {
  285. error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
  286. " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
  287. __func__, mem.slot, slot->start_addr,
  288. (uint64_t)mem.memory_size, strerror(errno));
  289. }
  290. }
  291. return ret;
  292. }
  293. void kvm_park_vcpu(CPUState *cpu)
  294. {
  295. struct KVMParkedVcpu *vcpu;
  296. trace_kvm_park_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  297. vcpu = g_malloc0(sizeof(*vcpu));
  298. vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
  299. vcpu->kvm_fd = cpu->kvm_fd;
  300. QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
  301. }
  302. int kvm_unpark_vcpu(KVMState *s, unsigned long vcpu_id)
  303. {
  304. struct KVMParkedVcpu *cpu;
  305. int kvm_fd = -ENOENT;
  306. QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
  307. if (cpu->vcpu_id == vcpu_id) {
  308. QLIST_REMOVE(cpu, node);
  309. kvm_fd = cpu->kvm_fd;
  310. g_free(cpu);
  311. break;
  312. }
  313. }
  314. trace_kvm_unpark_vcpu(vcpu_id, kvm_fd > 0 ? "unparked" : "!found parked");
  315. return kvm_fd;
  316. }
  317. int kvm_create_vcpu(CPUState *cpu)
  318. {
  319. unsigned long vcpu_id = kvm_arch_vcpu_id(cpu);
  320. KVMState *s = kvm_state;
  321. int kvm_fd;
  322. /* check if the KVM vCPU already exist but is parked */
  323. kvm_fd = kvm_unpark_vcpu(s, vcpu_id);
  324. if (kvm_fd < 0) {
  325. /* vCPU not parked: create a new KVM vCPU */
  326. kvm_fd = kvm_vm_ioctl(s, KVM_CREATE_VCPU, vcpu_id);
  327. if (kvm_fd < 0) {
  328. error_report("KVM_CREATE_VCPU IOCTL failed for vCPU %lu", vcpu_id);
  329. return kvm_fd;
  330. }
  331. }
  332. cpu->kvm_fd = kvm_fd;
  333. cpu->kvm_state = s;
  334. cpu->vcpu_dirty = true;
  335. cpu->dirty_pages = 0;
  336. cpu->throttle_us_per_full = 0;
  337. trace_kvm_create_vcpu(cpu->cpu_index, vcpu_id, kvm_fd);
  338. return 0;
  339. }
  340. int kvm_create_and_park_vcpu(CPUState *cpu)
  341. {
  342. int ret = 0;
  343. ret = kvm_create_vcpu(cpu);
  344. if (!ret) {
  345. kvm_park_vcpu(cpu);
  346. }
  347. return ret;
  348. }
  349. static int do_kvm_destroy_vcpu(CPUState *cpu)
  350. {
  351. KVMState *s = kvm_state;
  352. int mmap_size;
  353. int ret = 0;
  354. trace_kvm_destroy_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  355. ret = kvm_arch_destroy_vcpu(cpu);
  356. if (ret < 0) {
  357. goto err;
  358. }
  359. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  360. if (mmap_size < 0) {
  361. ret = mmap_size;
  362. trace_kvm_failed_get_vcpu_mmap_size();
  363. goto err;
  364. }
  365. ret = munmap(cpu->kvm_run, mmap_size);
  366. if (ret < 0) {
  367. goto err;
  368. }
  369. if (cpu->kvm_dirty_gfns) {
  370. ret = munmap(cpu->kvm_dirty_gfns, s->kvm_dirty_ring_bytes);
  371. if (ret < 0) {
  372. goto err;
  373. }
  374. }
  375. kvm_park_vcpu(cpu);
  376. err:
  377. return ret;
  378. }
  379. void kvm_destroy_vcpu(CPUState *cpu)
  380. {
  381. if (do_kvm_destroy_vcpu(cpu) < 0) {
  382. error_report("kvm_destroy_vcpu failed");
  383. exit(EXIT_FAILURE);
  384. }
  385. }
  386. int kvm_init_vcpu(CPUState *cpu, Error **errp)
  387. {
  388. KVMState *s = kvm_state;
  389. int mmap_size;
  390. int ret;
  391. trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  392. ret = kvm_create_vcpu(cpu);
  393. if (ret < 0) {
  394. error_setg_errno(errp, -ret,
  395. "kvm_init_vcpu: kvm_create_vcpu failed (%lu)",
  396. kvm_arch_vcpu_id(cpu));
  397. goto err;
  398. }
  399. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  400. if (mmap_size < 0) {
  401. ret = mmap_size;
  402. error_setg_errno(errp, -mmap_size,
  403. "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
  404. goto err;
  405. }
  406. cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
  407. cpu->kvm_fd, 0);
  408. if (cpu->kvm_run == MAP_FAILED) {
  409. ret = -errno;
  410. error_setg_errno(errp, ret,
  411. "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
  412. kvm_arch_vcpu_id(cpu));
  413. goto err;
  414. }
  415. if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
  416. s->coalesced_mmio_ring =
  417. (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
  418. }
  419. if (s->kvm_dirty_ring_size) {
  420. /* Use MAP_SHARED to share pages with the kernel */
  421. cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
  422. PROT_READ | PROT_WRITE, MAP_SHARED,
  423. cpu->kvm_fd,
  424. PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
  425. if (cpu->kvm_dirty_gfns == MAP_FAILED) {
  426. ret = -errno;
  427. goto err;
  428. }
  429. }
  430. ret = kvm_arch_init_vcpu(cpu);
  431. if (ret < 0) {
  432. error_setg_errno(errp, -ret,
  433. "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
  434. kvm_arch_vcpu_id(cpu));
  435. }
  436. cpu->kvm_vcpu_stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
  437. err:
  438. return ret;
  439. }
  440. /*
  441. * dirty pages logging control
  442. */
  443. static int kvm_mem_flags(MemoryRegion *mr)
  444. {
  445. bool readonly = mr->readonly || memory_region_is_romd(mr);
  446. int flags = 0;
  447. if (memory_region_get_dirty_log_mask(mr) != 0) {
  448. flags |= KVM_MEM_LOG_DIRTY_PAGES;
  449. }
  450. if (readonly && kvm_readonly_mem_allowed) {
  451. flags |= KVM_MEM_READONLY;
  452. }
  453. if (memory_region_has_guest_memfd(mr)) {
  454. assert(kvm_guest_memfd_supported);
  455. flags |= KVM_MEM_GUEST_MEMFD;
  456. }
  457. return flags;
  458. }
  459. /* Called with KVMMemoryListener.slots_lock held */
  460. static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
  461. MemoryRegion *mr)
  462. {
  463. mem->flags = kvm_mem_flags(mr);
  464. /* If nothing changed effectively, no need to issue ioctl */
  465. if (mem->flags == mem->old_flags) {
  466. return 0;
  467. }
  468. kvm_slot_init_dirty_bitmap(mem);
  469. return kvm_set_user_memory_region(kml, mem, false);
  470. }
  471. static int kvm_section_update_flags(KVMMemoryListener *kml,
  472. MemoryRegionSection *section)
  473. {
  474. hwaddr start_addr, size, slot_size;
  475. KVMSlot *mem;
  476. int ret = 0;
  477. size = kvm_align_section(section, &start_addr);
  478. if (!size) {
  479. return 0;
  480. }
  481. kvm_slots_lock();
  482. while (size && !ret) {
  483. slot_size = MIN(kvm_max_slot_size, size);
  484. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  485. if (!mem) {
  486. /* We don't have a slot if we want to trap every access. */
  487. goto out;
  488. }
  489. ret = kvm_slot_update_flags(kml, mem, section->mr);
  490. start_addr += slot_size;
  491. size -= slot_size;
  492. }
  493. out:
  494. kvm_slots_unlock();
  495. return ret;
  496. }
  497. static void kvm_log_start(MemoryListener *listener,
  498. MemoryRegionSection *section,
  499. int old, int new)
  500. {
  501. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  502. int r;
  503. if (old != 0) {
  504. return;
  505. }
  506. r = kvm_section_update_flags(kml, section);
  507. if (r < 0) {
  508. abort();
  509. }
  510. }
  511. static void kvm_log_stop(MemoryListener *listener,
  512. MemoryRegionSection *section,
  513. int old, int new)
  514. {
  515. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  516. int r;
  517. if (new != 0) {
  518. return;
  519. }
  520. r = kvm_section_update_flags(kml, section);
  521. if (r < 0) {
  522. abort();
  523. }
  524. }
  525. /* get kvm's dirty pages bitmap and update qemu's */
  526. static void kvm_slot_sync_dirty_pages(KVMSlot *slot)
  527. {
  528. ram_addr_t start = slot->ram_start_offset;
  529. ram_addr_t pages = slot->memory_size / qemu_real_host_page_size();
  530. cpu_physical_memory_set_dirty_lebitmap(slot->dirty_bmap, start, pages);
  531. }
  532. static void kvm_slot_reset_dirty_pages(KVMSlot *slot)
  533. {
  534. memset(slot->dirty_bmap, 0, slot->dirty_bmap_size);
  535. }
  536. #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
  537. /* Allocate the dirty bitmap for a slot */
  538. static void kvm_slot_init_dirty_bitmap(KVMSlot *mem)
  539. {
  540. if (!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) || mem->dirty_bmap) {
  541. return;
  542. }
  543. /*
  544. * XXX bad kernel interface alert
  545. * For dirty bitmap, kernel allocates array of size aligned to
  546. * bits-per-long. But for case when the kernel is 64bits and
  547. * the userspace is 32bits, userspace can't align to the same
  548. * bits-per-long, since sizeof(long) is different between kernel
  549. * and user space. This way, userspace will provide buffer which
  550. * may be 4 bytes less than the kernel will use, resulting in
  551. * userspace memory corruption (which is not detectable by valgrind
  552. * too, in most cases).
  553. * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
  554. * a hope that sizeof(long) won't become >8 any time soon.
  555. *
  556. * Note: the granule of kvm dirty log is qemu_real_host_page_size.
  557. * And mem->memory_size is aligned to it (otherwise this mem can't
  558. * be registered to KVM).
  559. */
  560. hwaddr bitmap_size = ALIGN(mem->memory_size / qemu_real_host_page_size(),
  561. /*HOST_LONG_BITS*/ 64) / 8;
  562. mem->dirty_bmap = g_malloc0(bitmap_size);
  563. mem->dirty_bmap_size = bitmap_size;
  564. }
  565. /*
  566. * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
  567. * succeeded, false otherwise
  568. */
  569. static bool kvm_slot_get_dirty_log(KVMState *s, KVMSlot *slot)
  570. {
  571. struct kvm_dirty_log d = {};
  572. int ret;
  573. d.dirty_bitmap = slot->dirty_bmap;
  574. d.slot = slot->slot | (slot->as_id << 16);
  575. ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
  576. if (ret == -ENOENT) {
  577. /* kernel does not have dirty bitmap in this slot */
  578. ret = 0;
  579. }
  580. if (ret) {
  581. error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
  582. __func__, ret);
  583. }
  584. return ret == 0;
  585. }
  586. /* Should be with all slots_lock held for the address spaces. */
  587. static void kvm_dirty_ring_mark_page(KVMState *s, uint32_t as_id,
  588. uint32_t slot_id, uint64_t offset)
  589. {
  590. KVMMemoryListener *kml;
  591. KVMSlot *mem;
  592. if (as_id >= s->nr_as) {
  593. return;
  594. }
  595. kml = s->as[as_id].ml;
  596. mem = &kml->slots[slot_id];
  597. if (!mem->memory_size || offset >=
  598. (mem->memory_size / qemu_real_host_page_size())) {
  599. return;
  600. }
  601. set_bit(offset, mem->dirty_bmap);
  602. }
  603. static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
  604. {
  605. /*
  606. * Read the flags before the value. Pairs with barrier in
  607. * KVM's kvm_dirty_ring_push() function.
  608. */
  609. return qatomic_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
  610. }
  611. static void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
  612. {
  613. /*
  614. * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
  615. * sees the full content of the ring:
  616. *
  617. * CPU0 CPU1 CPU2
  618. * ------------------------------------------------------------------------------
  619. * fill gfn0
  620. * store-rel flags for gfn0
  621. * load-acq flags for gfn0
  622. * store-rel RESET for gfn0
  623. * ioctl(RESET_RINGS)
  624. * load-acq flags for gfn0
  625. * check if flags have RESET
  626. *
  627. * The synchronization goes from CPU2 to CPU0 to CPU1.
  628. */
  629. qatomic_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
  630. }
  631. /*
  632. * Should be with all slots_lock held for the address spaces. It returns the
  633. * dirty page we've collected on this dirty ring.
  634. */
  635. static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
  636. {
  637. struct kvm_dirty_gfn *dirty_gfns = cpu->kvm_dirty_gfns, *cur;
  638. uint32_t ring_size = s->kvm_dirty_ring_size;
  639. uint32_t count = 0, fetch = cpu->kvm_fetch_index;
  640. /*
  641. * It's possible that we race with vcpu creation code where the vcpu is
  642. * put onto the vcpus list but not yet initialized the dirty ring
  643. * structures. If so, skip it.
  644. */
  645. if (!cpu->created) {
  646. return 0;
  647. }
  648. assert(dirty_gfns && ring_size);
  649. trace_kvm_dirty_ring_reap_vcpu(cpu->cpu_index);
  650. while (true) {
  651. cur = &dirty_gfns[fetch % ring_size];
  652. if (!dirty_gfn_is_dirtied(cur)) {
  653. break;
  654. }
  655. kvm_dirty_ring_mark_page(s, cur->slot >> 16, cur->slot & 0xffff,
  656. cur->offset);
  657. dirty_gfn_set_collected(cur);
  658. trace_kvm_dirty_ring_page(cpu->cpu_index, fetch, cur->offset);
  659. fetch++;
  660. count++;
  661. }
  662. cpu->kvm_fetch_index = fetch;
  663. cpu->dirty_pages += count;
  664. return count;
  665. }
  666. /* Must be with slots_lock held */
  667. static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
  668. {
  669. int ret;
  670. uint64_t total = 0;
  671. int64_t stamp;
  672. stamp = get_clock();
  673. if (cpu) {
  674. total = kvm_dirty_ring_reap_one(s, cpu);
  675. } else {
  676. CPU_FOREACH(cpu) {
  677. total += kvm_dirty_ring_reap_one(s, cpu);
  678. }
  679. }
  680. if (total) {
  681. ret = kvm_vm_ioctl(s, KVM_RESET_DIRTY_RINGS);
  682. assert(ret == total);
  683. }
  684. stamp = get_clock() - stamp;
  685. if (total) {
  686. trace_kvm_dirty_ring_reap(total, stamp / 1000);
  687. }
  688. return total;
  689. }
  690. /*
  691. * Currently for simplicity, we must hold BQL before calling this. We can
  692. * consider to drop the BQL if we're clear with all the race conditions.
  693. */
  694. static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
  695. {
  696. uint64_t total;
  697. /*
  698. * We need to lock all kvm slots for all address spaces here,
  699. * because:
  700. *
  701. * (1) We need to mark dirty for dirty bitmaps in multiple slots
  702. * and for tons of pages, so it's better to take the lock here
  703. * once rather than once per page. And more importantly,
  704. *
  705. * (2) We must _NOT_ publish dirty bits to the other threads
  706. * (e.g., the migration thread) via the kvm memory slot dirty
  707. * bitmaps before correctly re-protect those dirtied pages.
  708. * Otherwise we can have potential risk of data corruption if
  709. * the page data is read in the other thread before we do
  710. * reset below.
  711. */
  712. kvm_slots_lock();
  713. total = kvm_dirty_ring_reap_locked(s, cpu);
  714. kvm_slots_unlock();
  715. return total;
  716. }
  717. static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
  718. {
  719. /* No need to do anything */
  720. }
  721. /*
  722. * Kick all vcpus out in a synchronized way. When returned, we
  723. * guarantee that every vcpu has been kicked and at least returned to
  724. * userspace once.
  725. */
  726. static void kvm_cpu_synchronize_kick_all(void)
  727. {
  728. CPUState *cpu;
  729. CPU_FOREACH(cpu) {
  730. run_on_cpu(cpu, do_kvm_cpu_synchronize_kick, RUN_ON_CPU_NULL);
  731. }
  732. }
  733. /*
  734. * Flush all the existing dirty pages to the KVM slot buffers. When
  735. * this call returns, we guarantee that all the touched dirty pages
  736. * before calling this function have been put into the per-kvmslot
  737. * dirty bitmap.
  738. *
  739. * This function must be called with BQL held.
  740. */
  741. static void kvm_dirty_ring_flush(void)
  742. {
  743. trace_kvm_dirty_ring_flush(0);
  744. /*
  745. * The function needs to be serialized. Since this function
  746. * should always be with BQL held, serialization is guaranteed.
  747. * However, let's be sure of it.
  748. */
  749. assert(bql_locked());
  750. /*
  751. * First make sure to flush the hardware buffers by kicking all
  752. * vcpus out in a synchronous way.
  753. */
  754. kvm_cpu_synchronize_kick_all();
  755. kvm_dirty_ring_reap(kvm_state, NULL);
  756. trace_kvm_dirty_ring_flush(1);
  757. }
  758. /**
  759. * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
  760. *
  761. * This function will first try to fetch dirty bitmap from the kernel,
  762. * and then updates qemu's dirty bitmap.
  763. *
  764. * NOTE: caller must be with kml->slots_lock held.
  765. *
  766. * @kml: the KVM memory listener object
  767. * @section: the memory section to sync the dirty bitmap with
  768. */
  769. static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
  770. MemoryRegionSection *section)
  771. {
  772. KVMState *s = kvm_state;
  773. KVMSlot *mem;
  774. hwaddr start_addr, size;
  775. hwaddr slot_size;
  776. size = kvm_align_section(section, &start_addr);
  777. while (size) {
  778. slot_size = MIN(kvm_max_slot_size, size);
  779. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  780. if (!mem) {
  781. /* We don't have a slot if we want to trap every access. */
  782. return;
  783. }
  784. if (kvm_slot_get_dirty_log(s, mem)) {
  785. kvm_slot_sync_dirty_pages(mem);
  786. }
  787. start_addr += slot_size;
  788. size -= slot_size;
  789. }
  790. }
  791. /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
  792. #define KVM_CLEAR_LOG_SHIFT 6
  793. #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
  794. #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
  795. static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
  796. uint64_t size)
  797. {
  798. KVMState *s = kvm_state;
  799. uint64_t end, bmap_start, start_delta, bmap_npages;
  800. struct kvm_clear_dirty_log d;
  801. unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size();
  802. int ret;
  803. /*
  804. * We need to extend either the start or the size or both to
  805. * satisfy the KVM interface requirement. Firstly, do the start
  806. * page alignment on 64 host pages
  807. */
  808. bmap_start = start & KVM_CLEAR_LOG_MASK;
  809. start_delta = start - bmap_start;
  810. bmap_start /= psize;
  811. /*
  812. * The kernel interface has restriction on the size too, that either:
  813. *
  814. * (1) the size is 64 host pages aligned (just like the start), or
  815. * (2) the size fills up until the end of the KVM memslot.
  816. */
  817. bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
  818. << KVM_CLEAR_LOG_SHIFT;
  819. end = mem->memory_size / psize;
  820. if (bmap_npages > end - bmap_start) {
  821. bmap_npages = end - bmap_start;
  822. }
  823. start_delta /= psize;
  824. /*
  825. * Prepare the bitmap to clear dirty bits. Here we must guarantee
  826. * that we won't clear any unknown dirty bits otherwise we might
  827. * accidentally clear some set bits which are not yet synced from
  828. * the kernel into QEMU's bitmap, then we'll lose track of the
  829. * guest modifications upon those pages (which can directly lead
  830. * to guest data loss or panic after migration).
  831. *
  832. * Layout of the KVMSlot.dirty_bmap:
  833. *
  834. * |<-------- bmap_npages -----------..>|
  835. * [1]
  836. * start_delta size
  837. * |----------------|-------------|------------------|------------|
  838. * ^ ^ ^ ^
  839. * | | | |
  840. * start bmap_start (start) end
  841. * of memslot of memslot
  842. *
  843. * [1] bmap_npages can be aligned to either 64 pages or the end of slot
  844. */
  845. assert(bmap_start % BITS_PER_LONG == 0);
  846. /* We should never do log_clear before log_sync */
  847. assert(mem->dirty_bmap);
  848. if (start_delta || bmap_npages - size / psize) {
  849. /* Slow path - we need to manipulate a temp bitmap */
  850. bmap_clear = bitmap_new(bmap_npages);
  851. bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
  852. bmap_start, start_delta + size / psize);
  853. /*
  854. * We need to fill the holes at start because that was not
  855. * specified by the caller and we extended the bitmap only for
  856. * 64 pages alignment
  857. */
  858. bitmap_clear(bmap_clear, 0, start_delta);
  859. d.dirty_bitmap = bmap_clear;
  860. } else {
  861. /*
  862. * Fast path - both start and size align well with BITS_PER_LONG
  863. * (or the end of memory slot)
  864. */
  865. d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
  866. }
  867. d.first_page = bmap_start;
  868. /* It should never overflow. If it happens, say something */
  869. assert(bmap_npages <= UINT32_MAX);
  870. d.num_pages = bmap_npages;
  871. d.slot = mem->slot | (as_id << 16);
  872. ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
  873. if (ret < 0 && ret != -ENOENT) {
  874. error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
  875. "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
  876. __func__, d.slot, (uint64_t)d.first_page,
  877. (uint32_t)d.num_pages, ret);
  878. } else {
  879. ret = 0;
  880. trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
  881. }
  882. /*
  883. * After we have updated the remote dirty bitmap, we update the
  884. * cached bitmap as well for the memslot, then if another user
  885. * clears the same region we know we shouldn't clear it again on
  886. * the remote otherwise it's data loss as well.
  887. */
  888. bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
  889. size / psize);
  890. /* This handles the NULL case well */
  891. g_free(bmap_clear);
  892. return ret;
  893. }
  894. /**
  895. * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
  896. *
  897. * NOTE: this will be a no-op if we haven't enabled manual dirty log
  898. * protection in the host kernel because in that case this operation
  899. * will be done within log_sync().
  900. *
  901. * @kml: the kvm memory listener
  902. * @section: the memory range to clear dirty bitmap
  903. */
  904. static int kvm_physical_log_clear(KVMMemoryListener *kml,
  905. MemoryRegionSection *section)
  906. {
  907. KVMState *s = kvm_state;
  908. uint64_t start, size, offset, count;
  909. KVMSlot *mem;
  910. int ret = 0, i;
  911. if (!s->manual_dirty_log_protect) {
  912. /* No need to do explicit clear */
  913. return ret;
  914. }
  915. start = section->offset_within_address_space;
  916. size = int128_get64(section->size);
  917. if (!size) {
  918. /* Nothing more we can do... */
  919. return ret;
  920. }
  921. kvm_slots_lock();
  922. for (i = 0; i < s->nr_slots; i++) {
  923. mem = &kml->slots[i];
  924. /* Discard slots that are empty or do not overlap the section */
  925. if (!mem->memory_size ||
  926. mem->start_addr > start + size - 1 ||
  927. start > mem->start_addr + mem->memory_size - 1) {
  928. continue;
  929. }
  930. if (start >= mem->start_addr) {
  931. /* The slot starts before section or is aligned to it. */
  932. offset = start - mem->start_addr;
  933. count = MIN(mem->memory_size - offset, size);
  934. } else {
  935. /* The slot starts after section. */
  936. offset = 0;
  937. count = MIN(mem->memory_size, size - (mem->start_addr - start));
  938. }
  939. ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
  940. if (ret < 0) {
  941. break;
  942. }
  943. }
  944. kvm_slots_unlock();
  945. return ret;
  946. }
  947. static void kvm_coalesce_mmio_region(MemoryListener *listener,
  948. MemoryRegionSection *secion,
  949. hwaddr start, hwaddr size)
  950. {
  951. KVMState *s = kvm_state;
  952. if (s->coalesced_mmio) {
  953. struct kvm_coalesced_mmio_zone zone;
  954. zone.addr = start;
  955. zone.size = size;
  956. zone.pad = 0;
  957. (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
  958. }
  959. }
  960. static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
  961. MemoryRegionSection *secion,
  962. hwaddr start, hwaddr size)
  963. {
  964. KVMState *s = kvm_state;
  965. if (s->coalesced_mmio) {
  966. struct kvm_coalesced_mmio_zone zone;
  967. zone.addr = start;
  968. zone.size = size;
  969. zone.pad = 0;
  970. (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
  971. }
  972. }
  973. static void kvm_coalesce_pio_add(MemoryListener *listener,
  974. MemoryRegionSection *section,
  975. hwaddr start, hwaddr size)
  976. {
  977. KVMState *s = kvm_state;
  978. if (s->coalesced_pio) {
  979. struct kvm_coalesced_mmio_zone zone;
  980. zone.addr = start;
  981. zone.size = size;
  982. zone.pio = 1;
  983. (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
  984. }
  985. }
  986. static void kvm_coalesce_pio_del(MemoryListener *listener,
  987. MemoryRegionSection *section,
  988. hwaddr start, hwaddr size)
  989. {
  990. KVMState *s = kvm_state;
  991. if (s->coalesced_pio) {
  992. struct kvm_coalesced_mmio_zone zone;
  993. zone.addr = start;
  994. zone.size = size;
  995. zone.pio = 1;
  996. (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
  997. }
  998. }
  999. int kvm_check_extension(KVMState *s, unsigned int extension)
  1000. {
  1001. int ret;
  1002. ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  1003. if (ret < 0) {
  1004. ret = 0;
  1005. }
  1006. return ret;
  1007. }
  1008. int kvm_vm_check_extension(KVMState *s, unsigned int extension)
  1009. {
  1010. int ret;
  1011. ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  1012. if (ret < 0) {
  1013. /* VM wide version not implemented, use global one instead */
  1014. ret = kvm_check_extension(s, extension);
  1015. }
  1016. return ret;
  1017. }
  1018. /*
  1019. * We track the poisoned pages to be able to:
  1020. * - replace them on VM reset
  1021. * - block a migration for a VM with a poisoned page
  1022. */
  1023. typedef struct HWPoisonPage {
  1024. ram_addr_t ram_addr;
  1025. QLIST_ENTRY(HWPoisonPage) list;
  1026. } HWPoisonPage;
  1027. static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
  1028. QLIST_HEAD_INITIALIZER(hwpoison_page_list);
  1029. static void kvm_unpoison_all(void *param)
  1030. {
  1031. HWPoisonPage *page, *next_page;
  1032. QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
  1033. QLIST_REMOVE(page, list);
  1034. qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
  1035. g_free(page);
  1036. }
  1037. }
  1038. void kvm_hwpoison_page_add(ram_addr_t ram_addr)
  1039. {
  1040. HWPoisonPage *page;
  1041. QLIST_FOREACH(page, &hwpoison_page_list, list) {
  1042. if (page->ram_addr == ram_addr) {
  1043. return;
  1044. }
  1045. }
  1046. page = g_new(HWPoisonPage, 1);
  1047. page->ram_addr = ram_addr;
  1048. QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
  1049. }
  1050. bool kvm_hwpoisoned_mem(void)
  1051. {
  1052. return !QLIST_EMPTY(&hwpoison_page_list);
  1053. }
  1054. static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
  1055. {
  1056. #if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
  1057. /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
  1058. * endianness, but the memory core hands them in target endianness.
  1059. * For example, PPC is always treated as big-endian even if running
  1060. * on KVM and on PPC64LE. Correct here.
  1061. */
  1062. switch (size) {
  1063. case 2:
  1064. val = bswap16(val);
  1065. break;
  1066. case 4:
  1067. val = bswap32(val);
  1068. break;
  1069. }
  1070. #endif
  1071. return val;
  1072. }
  1073. static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
  1074. bool assign, uint32_t size, bool datamatch)
  1075. {
  1076. int ret;
  1077. struct kvm_ioeventfd iofd = {
  1078. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  1079. .addr = addr,
  1080. .len = size,
  1081. .flags = 0,
  1082. .fd = fd,
  1083. };
  1084. trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
  1085. datamatch);
  1086. if (!kvm_enabled()) {
  1087. return -ENOSYS;
  1088. }
  1089. if (datamatch) {
  1090. iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  1091. }
  1092. if (!assign) {
  1093. iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  1094. }
  1095. ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
  1096. if (ret < 0) {
  1097. return -errno;
  1098. }
  1099. return 0;
  1100. }
  1101. static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
  1102. bool assign, uint32_t size, bool datamatch)
  1103. {
  1104. struct kvm_ioeventfd kick = {
  1105. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  1106. .addr = addr,
  1107. .flags = KVM_IOEVENTFD_FLAG_PIO,
  1108. .len = size,
  1109. .fd = fd,
  1110. };
  1111. int r;
  1112. trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
  1113. if (!kvm_enabled()) {
  1114. return -ENOSYS;
  1115. }
  1116. if (datamatch) {
  1117. kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  1118. }
  1119. if (!assign) {
  1120. kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  1121. }
  1122. r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
  1123. if (r < 0) {
  1124. return r;
  1125. }
  1126. return 0;
  1127. }
  1128. static const KVMCapabilityInfo *
  1129. kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
  1130. {
  1131. while (list->name) {
  1132. if (!kvm_check_extension(s, list->value)) {
  1133. return list;
  1134. }
  1135. list++;
  1136. }
  1137. return NULL;
  1138. }
  1139. void kvm_set_max_memslot_size(hwaddr max_slot_size)
  1140. {
  1141. g_assert(
  1142. ROUND_UP(max_slot_size, qemu_real_host_page_size()) == max_slot_size
  1143. );
  1144. kvm_max_slot_size = max_slot_size;
  1145. }
  1146. static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)
  1147. {
  1148. struct kvm_memory_attributes attrs;
  1149. int r;
  1150. assert((attr & kvm_supported_memory_attributes) == attr);
  1151. attrs.attributes = attr;
  1152. attrs.address = start;
  1153. attrs.size = size;
  1154. attrs.flags = 0;
  1155. r = kvm_vm_ioctl(kvm_state, KVM_SET_MEMORY_ATTRIBUTES, &attrs);
  1156. if (r) {
  1157. error_report("failed to set memory (0x%" HWADDR_PRIx "+0x%" PRIx64 ") "
  1158. "with attr 0x%" PRIx64 " error '%s'",
  1159. start, size, attr, strerror(errno));
  1160. }
  1161. return r;
  1162. }
  1163. int kvm_set_memory_attributes_private(hwaddr start, uint64_t size)
  1164. {
  1165. return kvm_set_memory_attributes(start, size, KVM_MEMORY_ATTRIBUTE_PRIVATE);
  1166. }
  1167. int kvm_set_memory_attributes_shared(hwaddr start, uint64_t size)
  1168. {
  1169. return kvm_set_memory_attributes(start, size, 0);
  1170. }
  1171. /* Called with KVMMemoryListener.slots_lock held */
  1172. static void kvm_set_phys_mem(KVMMemoryListener *kml,
  1173. MemoryRegionSection *section, bool add)
  1174. {
  1175. KVMSlot *mem;
  1176. int err;
  1177. MemoryRegion *mr = section->mr;
  1178. bool writable = !mr->readonly && !mr->rom_device;
  1179. hwaddr start_addr, size, slot_size, mr_offset;
  1180. ram_addr_t ram_start_offset;
  1181. void *ram;
  1182. if (!memory_region_is_ram(mr)) {
  1183. if (writable || !kvm_readonly_mem_allowed) {
  1184. return;
  1185. } else if (!mr->romd_mode) {
  1186. /* If the memory device is not in romd_mode, then we actually want
  1187. * to remove the kvm memory slot so all accesses will trap. */
  1188. add = false;
  1189. }
  1190. }
  1191. size = kvm_align_section(section, &start_addr);
  1192. if (!size) {
  1193. return;
  1194. }
  1195. /* The offset of the kvmslot within the memory region */
  1196. mr_offset = section->offset_within_region + start_addr -
  1197. section->offset_within_address_space;
  1198. /* use aligned delta to align the ram address and offset */
  1199. ram = memory_region_get_ram_ptr(mr) + mr_offset;
  1200. ram_start_offset = memory_region_get_ram_addr(mr) + mr_offset;
  1201. if (!add) {
  1202. do {
  1203. slot_size = MIN(kvm_max_slot_size, size);
  1204. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  1205. if (!mem) {
  1206. return;
  1207. }
  1208. if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  1209. /*
  1210. * NOTE: We should be aware of the fact that here we're only
  1211. * doing a best effort to sync dirty bits. No matter whether
  1212. * we're using dirty log or dirty ring, we ignored two facts:
  1213. *
  1214. * (1) dirty bits can reside in hardware buffers (PML)
  1215. *
  1216. * (2) after we collected dirty bits here, pages can be dirtied
  1217. * again before we do the final KVM_SET_USER_MEMORY_REGION to
  1218. * remove the slot.
  1219. *
  1220. * Not easy. Let's cross the fingers until it's fixed.
  1221. */
  1222. if (kvm_state->kvm_dirty_ring_size) {
  1223. kvm_dirty_ring_reap_locked(kvm_state, NULL);
  1224. if (kvm_state->kvm_dirty_ring_with_bitmap) {
  1225. kvm_slot_sync_dirty_pages(mem);
  1226. kvm_slot_get_dirty_log(kvm_state, mem);
  1227. }
  1228. } else {
  1229. kvm_slot_get_dirty_log(kvm_state, mem);
  1230. }
  1231. kvm_slot_sync_dirty_pages(mem);
  1232. }
  1233. /* unregister the slot */
  1234. g_free(mem->dirty_bmap);
  1235. mem->dirty_bmap = NULL;
  1236. mem->memory_size = 0;
  1237. mem->flags = 0;
  1238. err = kvm_set_user_memory_region(kml, mem, false);
  1239. if (err) {
  1240. fprintf(stderr, "%s: error unregistering slot: %s\n",
  1241. __func__, strerror(-err));
  1242. abort();
  1243. }
  1244. start_addr += slot_size;
  1245. size -= slot_size;
  1246. kml->nr_used_slots--;
  1247. } while (size);
  1248. return;
  1249. }
  1250. /* register the new slot */
  1251. do {
  1252. slot_size = MIN(kvm_max_slot_size, size);
  1253. mem = kvm_alloc_slot(kml);
  1254. mem->as_id = kml->as_id;
  1255. mem->memory_size = slot_size;
  1256. mem->start_addr = start_addr;
  1257. mem->ram_start_offset = ram_start_offset;
  1258. mem->ram = ram;
  1259. mem->flags = kvm_mem_flags(mr);
  1260. mem->guest_memfd = mr->ram_block->guest_memfd;
  1261. mem->guest_memfd_offset = (uint8_t*)ram - mr->ram_block->host;
  1262. kvm_slot_init_dirty_bitmap(mem);
  1263. err = kvm_set_user_memory_region(kml, mem, true);
  1264. if (err) {
  1265. fprintf(stderr, "%s: error registering slot: %s\n", __func__,
  1266. strerror(-err));
  1267. abort();
  1268. }
  1269. if (memory_region_has_guest_memfd(mr)) {
  1270. err = kvm_set_memory_attributes_private(start_addr, slot_size);
  1271. if (err) {
  1272. error_report("%s: failed to set memory attribute private: %s",
  1273. __func__, strerror(-err));
  1274. exit(1);
  1275. }
  1276. }
  1277. start_addr += slot_size;
  1278. ram_start_offset += slot_size;
  1279. ram += slot_size;
  1280. size -= slot_size;
  1281. kml->nr_used_slots++;
  1282. } while (size);
  1283. }
  1284. static void *kvm_dirty_ring_reaper_thread(void *data)
  1285. {
  1286. KVMState *s = data;
  1287. struct KVMDirtyRingReaper *r = &s->reaper;
  1288. rcu_register_thread();
  1289. trace_kvm_dirty_ring_reaper("init");
  1290. while (true) {
  1291. r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
  1292. trace_kvm_dirty_ring_reaper("wait");
  1293. /*
  1294. * TODO: provide a smarter timeout rather than a constant?
  1295. */
  1296. sleep(1);
  1297. /* keep sleeping so that dirtylimit not be interfered by reaper */
  1298. if (dirtylimit_in_service()) {
  1299. continue;
  1300. }
  1301. trace_kvm_dirty_ring_reaper("wakeup");
  1302. r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
  1303. bql_lock();
  1304. kvm_dirty_ring_reap(s, NULL);
  1305. bql_unlock();
  1306. r->reaper_iteration++;
  1307. }
  1308. g_assert_not_reached();
  1309. }
  1310. static void kvm_dirty_ring_reaper_init(KVMState *s)
  1311. {
  1312. struct KVMDirtyRingReaper *r = &s->reaper;
  1313. qemu_thread_create(&r->reaper_thr, "kvm-reaper",
  1314. kvm_dirty_ring_reaper_thread,
  1315. s, QEMU_THREAD_JOINABLE);
  1316. }
  1317. static int kvm_dirty_ring_init(KVMState *s)
  1318. {
  1319. uint32_t ring_size = s->kvm_dirty_ring_size;
  1320. uint64_t ring_bytes = ring_size * sizeof(struct kvm_dirty_gfn);
  1321. unsigned int capability = KVM_CAP_DIRTY_LOG_RING;
  1322. int ret;
  1323. s->kvm_dirty_ring_size = 0;
  1324. s->kvm_dirty_ring_bytes = 0;
  1325. /* Bail if the dirty ring size isn't specified */
  1326. if (!ring_size) {
  1327. return 0;
  1328. }
  1329. /*
  1330. * Read the max supported pages. Fall back to dirty logging mode
  1331. * if the dirty ring isn't supported.
  1332. */
  1333. ret = kvm_vm_check_extension(s, capability);
  1334. if (ret <= 0) {
  1335. capability = KVM_CAP_DIRTY_LOG_RING_ACQ_REL;
  1336. ret = kvm_vm_check_extension(s, capability);
  1337. }
  1338. if (ret <= 0) {
  1339. warn_report("KVM dirty ring not available, using bitmap method");
  1340. return 0;
  1341. }
  1342. if (ring_bytes > ret) {
  1343. error_report("KVM dirty ring size %" PRIu32 " too big "
  1344. "(maximum is %ld). Please use a smaller value.",
  1345. ring_size, (long)ret / sizeof(struct kvm_dirty_gfn));
  1346. return -EINVAL;
  1347. }
  1348. ret = kvm_vm_enable_cap(s, capability, 0, ring_bytes);
  1349. if (ret) {
  1350. error_report("Enabling of KVM dirty ring failed: %s. "
  1351. "Suggested minimum value is 1024.", strerror(-ret));
  1352. return -EIO;
  1353. }
  1354. /* Enable the backup bitmap if it is supported */
  1355. ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP);
  1356. if (ret > 0) {
  1357. ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP, 0);
  1358. if (ret) {
  1359. error_report("Enabling of KVM dirty ring's backup bitmap failed: "
  1360. "%s. ", strerror(-ret));
  1361. return -EIO;
  1362. }
  1363. s->kvm_dirty_ring_with_bitmap = true;
  1364. }
  1365. s->kvm_dirty_ring_size = ring_size;
  1366. s->kvm_dirty_ring_bytes = ring_bytes;
  1367. return 0;
  1368. }
  1369. static void kvm_region_add(MemoryListener *listener,
  1370. MemoryRegionSection *section)
  1371. {
  1372. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1373. KVMMemoryUpdate *update;
  1374. update = g_new0(KVMMemoryUpdate, 1);
  1375. update->section = *section;
  1376. QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
  1377. }
  1378. static void kvm_region_del(MemoryListener *listener,
  1379. MemoryRegionSection *section)
  1380. {
  1381. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1382. KVMMemoryUpdate *update;
  1383. update = g_new0(KVMMemoryUpdate, 1);
  1384. update->section = *section;
  1385. QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
  1386. }
  1387. static void kvm_region_commit(MemoryListener *listener)
  1388. {
  1389. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
  1390. listener);
  1391. KVMMemoryUpdate *u1, *u2;
  1392. bool need_inhibit = false;
  1393. if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
  1394. QSIMPLEQ_EMPTY(&kml->transaction_del)) {
  1395. return;
  1396. }
  1397. /*
  1398. * We have to be careful when regions to add overlap with ranges to remove.
  1399. * We have to simulate atomic KVM memslot updates by making sure no ioctl()
  1400. * is currently active.
  1401. *
  1402. * The lists are order by addresses, so it's easy to find overlaps.
  1403. */
  1404. u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
  1405. u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
  1406. while (u1 && u2) {
  1407. Range r1, r2;
  1408. range_init_nofail(&r1, u1->section.offset_within_address_space,
  1409. int128_get64(u1->section.size));
  1410. range_init_nofail(&r2, u2->section.offset_within_address_space,
  1411. int128_get64(u2->section.size));
  1412. if (range_overlaps_range(&r1, &r2)) {
  1413. need_inhibit = true;
  1414. break;
  1415. }
  1416. if (range_lob(&r1) < range_lob(&r2)) {
  1417. u1 = QSIMPLEQ_NEXT(u1, next);
  1418. } else {
  1419. u2 = QSIMPLEQ_NEXT(u2, next);
  1420. }
  1421. }
  1422. kvm_slots_lock();
  1423. if (need_inhibit) {
  1424. accel_ioctl_inhibit_begin();
  1425. }
  1426. /* Remove all memslots before adding the new ones. */
  1427. while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
  1428. u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
  1429. QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
  1430. kvm_set_phys_mem(kml, &u1->section, false);
  1431. memory_region_unref(u1->section.mr);
  1432. g_free(u1);
  1433. }
  1434. while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
  1435. u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
  1436. QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
  1437. memory_region_ref(u1->section.mr);
  1438. kvm_set_phys_mem(kml, &u1->section, true);
  1439. g_free(u1);
  1440. }
  1441. if (need_inhibit) {
  1442. accel_ioctl_inhibit_end();
  1443. }
  1444. kvm_slots_unlock();
  1445. }
  1446. static void kvm_log_sync(MemoryListener *listener,
  1447. MemoryRegionSection *section)
  1448. {
  1449. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1450. kvm_slots_lock();
  1451. kvm_physical_sync_dirty_bitmap(kml, section);
  1452. kvm_slots_unlock();
  1453. }
  1454. static void kvm_log_sync_global(MemoryListener *l, bool last_stage)
  1455. {
  1456. KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
  1457. KVMState *s = kvm_state;
  1458. KVMSlot *mem;
  1459. int i;
  1460. /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
  1461. kvm_dirty_ring_flush();
  1462. /*
  1463. * TODO: make this faster when nr_slots is big while there are
  1464. * only a few used slots (small VMs).
  1465. */
  1466. kvm_slots_lock();
  1467. for (i = 0; i < s->nr_slots; i++) {
  1468. mem = &kml->slots[i];
  1469. if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  1470. kvm_slot_sync_dirty_pages(mem);
  1471. if (s->kvm_dirty_ring_with_bitmap && last_stage &&
  1472. kvm_slot_get_dirty_log(s, mem)) {
  1473. kvm_slot_sync_dirty_pages(mem);
  1474. }
  1475. /*
  1476. * This is not needed by KVM_GET_DIRTY_LOG because the
  1477. * ioctl will unconditionally overwrite the whole region.
  1478. * However kvm dirty ring has no such side effect.
  1479. */
  1480. kvm_slot_reset_dirty_pages(mem);
  1481. }
  1482. }
  1483. kvm_slots_unlock();
  1484. }
  1485. static void kvm_log_clear(MemoryListener *listener,
  1486. MemoryRegionSection *section)
  1487. {
  1488. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1489. int r;
  1490. r = kvm_physical_log_clear(kml, section);
  1491. if (r < 0) {
  1492. error_report_once("%s: kvm log clear failed: mr=%s "
  1493. "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
  1494. section->mr->name, section->offset_within_region,
  1495. int128_get64(section->size));
  1496. abort();
  1497. }
  1498. }
  1499. static void kvm_mem_ioeventfd_add(MemoryListener *listener,
  1500. MemoryRegionSection *section,
  1501. bool match_data, uint64_t data,
  1502. EventNotifier *e)
  1503. {
  1504. int fd = event_notifier_get_fd(e);
  1505. int r;
  1506. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  1507. data, true, int128_get64(section->size),
  1508. match_data);
  1509. if (r < 0) {
  1510. fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
  1511. __func__, strerror(-r), -r);
  1512. abort();
  1513. }
  1514. }
  1515. static void kvm_mem_ioeventfd_del(MemoryListener *listener,
  1516. MemoryRegionSection *section,
  1517. bool match_data, uint64_t data,
  1518. EventNotifier *e)
  1519. {
  1520. int fd = event_notifier_get_fd(e);
  1521. int r;
  1522. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  1523. data, false, int128_get64(section->size),
  1524. match_data);
  1525. if (r < 0) {
  1526. fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
  1527. __func__, strerror(-r), -r);
  1528. abort();
  1529. }
  1530. }
  1531. static void kvm_io_ioeventfd_add(MemoryListener *listener,
  1532. MemoryRegionSection *section,
  1533. bool match_data, uint64_t data,
  1534. EventNotifier *e)
  1535. {
  1536. int fd = event_notifier_get_fd(e);
  1537. int r;
  1538. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  1539. data, true, int128_get64(section->size),
  1540. match_data);
  1541. if (r < 0) {
  1542. fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
  1543. __func__, strerror(-r), -r);
  1544. abort();
  1545. }
  1546. }
  1547. static void kvm_io_ioeventfd_del(MemoryListener *listener,
  1548. MemoryRegionSection *section,
  1549. bool match_data, uint64_t data,
  1550. EventNotifier *e)
  1551. {
  1552. int fd = event_notifier_get_fd(e);
  1553. int r;
  1554. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  1555. data, false, int128_get64(section->size),
  1556. match_data);
  1557. if (r < 0) {
  1558. fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
  1559. __func__, strerror(-r), -r);
  1560. abort();
  1561. }
  1562. }
  1563. void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
  1564. AddressSpace *as, int as_id, const char *name)
  1565. {
  1566. int i;
  1567. kml->slots = g_new0(KVMSlot, s->nr_slots);
  1568. kml->as_id = as_id;
  1569. for (i = 0; i < s->nr_slots; i++) {
  1570. kml->slots[i].slot = i;
  1571. }
  1572. QSIMPLEQ_INIT(&kml->transaction_add);
  1573. QSIMPLEQ_INIT(&kml->transaction_del);
  1574. kml->listener.region_add = kvm_region_add;
  1575. kml->listener.region_del = kvm_region_del;
  1576. kml->listener.commit = kvm_region_commit;
  1577. kml->listener.log_start = kvm_log_start;
  1578. kml->listener.log_stop = kvm_log_stop;
  1579. kml->listener.priority = MEMORY_LISTENER_PRIORITY_ACCEL;
  1580. kml->listener.name = name;
  1581. if (s->kvm_dirty_ring_size) {
  1582. kml->listener.log_sync_global = kvm_log_sync_global;
  1583. } else {
  1584. kml->listener.log_sync = kvm_log_sync;
  1585. kml->listener.log_clear = kvm_log_clear;
  1586. }
  1587. memory_listener_register(&kml->listener, as);
  1588. for (i = 0; i < s->nr_as; ++i) {
  1589. if (!s->as[i].as) {
  1590. s->as[i].as = as;
  1591. s->as[i].ml = kml;
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. static MemoryListener kvm_io_listener = {
  1597. .name = "kvm-io",
  1598. .coalesced_io_add = kvm_coalesce_pio_add,
  1599. .coalesced_io_del = kvm_coalesce_pio_del,
  1600. .eventfd_add = kvm_io_ioeventfd_add,
  1601. .eventfd_del = kvm_io_ioeventfd_del,
  1602. .priority = MEMORY_LISTENER_PRIORITY_DEV_BACKEND,
  1603. };
  1604. int kvm_set_irq(KVMState *s, int irq, int level)
  1605. {
  1606. struct kvm_irq_level event;
  1607. int ret;
  1608. assert(kvm_async_interrupts_enabled());
  1609. event.level = level;
  1610. event.irq = irq;
  1611. ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
  1612. if (ret < 0) {
  1613. perror("kvm_set_irq");
  1614. abort();
  1615. }
  1616. return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
  1617. }
  1618. #ifdef KVM_CAP_IRQ_ROUTING
  1619. typedef struct KVMMSIRoute {
  1620. struct kvm_irq_routing_entry kroute;
  1621. QTAILQ_ENTRY(KVMMSIRoute) entry;
  1622. } KVMMSIRoute;
  1623. static void set_gsi(KVMState *s, unsigned int gsi)
  1624. {
  1625. set_bit(gsi, s->used_gsi_bitmap);
  1626. }
  1627. static void clear_gsi(KVMState *s, unsigned int gsi)
  1628. {
  1629. clear_bit(gsi, s->used_gsi_bitmap);
  1630. }
  1631. void kvm_init_irq_routing(KVMState *s)
  1632. {
  1633. int gsi_count;
  1634. gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
  1635. if (gsi_count > 0) {
  1636. /* Round up so we can search ints using ffs */
  1637. s->used_gsi_bitmap = bitmap_new(gsi_count);
  1638. s->gsi_count = gsi_count;
  1639. }
  1640. s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
  1641. s->nr_allocated_irq_routes = 0;
  1642. kvm_arch_init_irq_routing(s);
  1643. }
  1644. void kvm_irqchip_commit_routes(KVMState *s)
  1645. {
  1646. int ret;
  1647. if (kvm_gsi_direct_mapping()) {
  1648. return;
  1649. }
  1650. if (!kvm_gsi_routing_enabled()) {
  1651. return;
  1652. }
  1653. s->irq_routes->flags = 0;
  1654. trace_kvm_irqchip_commit_routes();
  1655. ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
  1656. assert(ret == 0);
  1657. }
  1658. void kvm_add_routing_entry(KVMState *s,
  1659. struct kvm_irq_routing_entry *entry)
  1660. {
  1661. struct kvm_irq_routing_entry *new;
  1662. int n, size;
  1663. if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
  1664. n = s->nr_allocated_irq_routes * 2;
  1665. if (n < 64) {
  1666. n = 64;
  1667. }
  1668. size = sizeof(struct kvm_irq_routing);
  1669. size += n * sizeof(*new);
  1670. s->irq_routes = g_realloc(s->irq_routes, size);
  1671. s->nr_allocated_irq_routes = n;
  1672. }
  1673. n = s->irq_routes->nr++;
  1674. new = &s->irq_routes->entries[n];
  1675. *new = *entry;
  1676. set_gsi(s, entry->gsi);
  1677. }
  1678. static int kvm_update_routing_entry(KVMState *s,
  1679. struct kvm_irq_routing_entry *new_entry)
  1680. {
  1681. struct kvm_irq_routing_entry *entry;
  1682. int n;
  1683. for (n = 0; n < s->irq_routes->nr; n++) {
  1684. entry = &s->irq_routes->entries[n];
  1685. if (entry->gsi != new_entry->gsi) {
  1686. continue;
  1687. }
  1688. if(!memcmp(entry, new_entry, sizeof *entry)) {
  1689. return 0;
  1690. }
  1691. *entry = *new_entry;
  1692. return 0;
  1693. }
  1694. return -ESRCH;
  1695. }
  1696. void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
  1697. {
  1698. struct kvm_irq_routing_entry e = {};
  1699. assert(pin < s->gsi_count);
  1700. e.gsi = irq;
  1701. e.type = KVM_IRQ_ROUTING_IRQCHIP;
  1702. e.flags = 0;
  1703. e.u.irqchip.irqchip = irqchip;
  1704. e.u.irqchip.pin = pin;
  1705. kvm_add_routing_entry(s, &e);
  1706. }
  1707. void kvm_irqchip_release_virq(KVMState *s, int virq)
  1708. {
  1709. struct kvm_irq_routing_entry *e;
  1710. int i;
  1711. if (kvm_gsi_direct_mapping()) {
  1712. return;
  1713. }
  1714. for (i = 0; i < s->irq_routes->nr; i++) {
  1715. e = &s->irq_routes->entries[i];
  1716. if (e->gsi == virq) {
  1717. s->irq_routes->nr--;
  1718. *e = s->irq_routes->entries[s->irq_routes->nr];
  1719. }
  1720. }
  1721. clear_gsi(s, virq);
  1722. kvm_arch_release_virq_post(virq);
  1723. trace_kvm_irqchip_release_virq(virq);
  1724. }
  1725. void kvm_irqchip_add_change_notifier(Notifier *n)
  1726. {
  1727. notifier_list_add(&kvm_irqchip_change_notifiers, n);
  1728. }
  1729. void kvm_irqchip_remove_change_notifier(Notifier *n)
  1730. {
  1731. notifier_remove(n);
  1732. }
  1733. void kvm_irqchip_change_notify(void)
  1734. {
  1735. notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
  1736. }
  1737. int kvm_irqchip_get_virq(KVMState *s)
  1738. {
  1739. int next_virq;
  1740. /* Return the lowest unused GSI in the bitmap */
  1741. next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
  1742. if (next_virq >= s->gsi_count) {
  1743. return -ENOSPC;
  1744. } else {
  1745. return next_virq;
  1746. }
  1747. }
  1748. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1749. {
  1750. struct kvm_msi msi;
  1751. msi.address_lo = (uint32_t)msg.address;
  1752. msi.address_hi = msg.address >> 32;
  1753. msi.data = le32_to_cpu(msg.data);
  1754. msi.flags = 0;
  1755. memset(msi.pad, 0, sizeof(msi.pad));
  1756. return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
  1757. }
  1758. int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
  1759. {
  1760. struct kvm_irq_routing_entry kroute = {};
  1761. int virq;
  1762. KVMState *s = c->s;
  1763. MSIMessage msg = {0, 0};
  1764. if (pci_available && dev) {
  1765. msg = pci_get_msi_message(dev, vector);
  1766. }
  1767. if (kvm_gsi_direct_mapping()) {
  1768. return kvm_arch_msi_data_to_gsi(msg.data);
  1769. }
  1770. if (!kvm_gsi_routing_enabled()) {
  1771. return -ENOSYS;
  1772. }
  1773. virq = kvm_irqchip_get_virq(s);
  1774. if (virq < 0) {
  1775. return virq;
  1776. }
  1777. kroute.gsi = virq;
  1778. kroute.type = KVM_IRQ_ROUTING_MSI;
  1779. kroute.flags = 0;
  1780. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1781. kroute.u.msi.address_hi = msg.address >> 32;
  1782. kroute.u.msi.data = le32_to_cpu(msg.data);
  1783. if (pci_available && kvm_msi_devid_required()) {
  1784. kroute.flags = KVM_MSI_VALID_DEVID;
  1785. kroute.u.msi.devid = pci_requester_id(dev);
  1786. }
  1787. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1788. kvm_irqchip_release_virq(s, virq);
  1789. return -EINVAL;
  1790. }
  1791. if (s->irq_routes->nr < s->gsi_count) {
  1792. trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
  1793. vector, virq);
  1794. kvm_add_routing_entry(s, &kroute);
  1795. kvm_arch_add_msi_route_post(&kroute, vector, dev);
  1796. c->changes++;
  1797. } else {
  1798. kvm_irqchip_release_virq(s, virq);
  1799. return -ENOSPC;
  1800. }
  1801. return virq;
  1802. }
  1803. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
  1804. PCIDevice *dev)
  1805. {
  1806. struct kvm_irq_routing_entry kroute = {};
  1807. if (kvm_gsi_direct_mapping()) {
  1808. return 0;
  1809. }
  1810. if (!kvm_irqchip_in_kernel()) {
  1811. return -ENOSYS;
  1812. }
  1813. kroute.gsi = virq;
  1814. kroute.type = KVM_IRQ_ROUTING_MSI;
  1815. kroute.flags = 0;
  1816. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1817. kroute.u.msi.address_hi = msg.address >> 32;
  1818. kroute.u.msi.data = le32_to_cpu(msg.data);
  1819. if (pci_available && kvm_msi_devid_required()) {
  1820. kroute.flags = KVM_MSI_VALID_DEVID;
  1821. kroute.u.msi.devid = pci_requester_id(dev);
  1822. }
  1823. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1824. return -EINVAL;
  1825. }
  1826. trace_kvm_irqchip_update_msi_route(virq);
  1827. return kvm_update_routing_entry(s, &kroute);
  1828. }
  1829. static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
  1830. EventNotifier *resample, int virq,
  1831. bool assign)
  1832. {
  1833. int fd = event_notifier_get_fd(event);
  1834. int rfd = resample ? event_notifier_get_fd(resample) : -1;
  1835. struct kvm_irqfd irqfd = {
  1836. .fd = fd,
  1837. .gsi = virq,
  1838. .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
  1839. };
  1840. if (rfd != -1) {
  1841. assert(assign);
  1842. if (kvm_irqchip_is_split()) {
  1843. /*
  1844. * When the slow irqchip (e.g. IOAPIC) is in the
  1845. * userspace, KVM kernel resamplefd will not work because
  1846. * the EOI of the interrupt will be delivered to userspace
  1847. * instead, so the KVM kernel resamplefd kick will be
  1848. * skipped. The userspace here mimics what the kernel
  1849. * provides with resamplefd, remember the resamplefd and
  1850. * kick it when we receive EOI of this IRQ.
  1851. *
  1852. * This is hackery because IOAPIC is mostly bypassed
  1853. * (except EOI broadcasts) when irqfd is used. However
  1854. * this can bring much performance back for split irqchip
  1855. * with INTx IRQs (for VFIO, this gives 93% perf of the
  1856. * full fast path, which is 46% perf boost comparing to
  1857. * the INTx slow path).
  1858. */
  1859. kvm_resample_fd_insert(virq, resample);
  1860. } else {
  1861. irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
  1862. irqfd.resamplefd = rfd;
  1863. }
  1864. } else if (!assign) {
  1865. if (kvm_irqchip_is_split()) {
  1866. kvm_resample_fd_remove(virq);
  1867. }
  1868. }
  1869. return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
  1870. }
  1871. #else /* !KVM_CAP_IRQ_ROUTING */
  1872. void kvm_init_irq_routing(KVMState *s)
  1873. {
  1874. }
  1875. void kvm_irqchip_release_virq(KVMState *s, int virq)
  1876. {
  1877. }
  1878. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1879. {
  1880. abort();
  1881. }
  1882. int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
  1883. {
  1884. return -ENOSYS;
  1885. }
  1886. int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
  1887. {
  1888. return -ENOSYS;
  1889. }
  1890. int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
  1891. {
  1892. return -ENOSYS;
  1893. }
  1894. static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
  1895. EventNotifier *resample, int virq,
  1896. bool assign)
  1897. {
  1898. abort();
  1899. }
  1900. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
  1901. {
  1902. return -ENOSYS;
  1903. }
  1904. #endif /* !KVM_CAP_IRQ_ROUTING */
  1905. int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1906. EventNotifier *rn, int virq)
  1907. {
  1908. return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
  1909. }
  1910. int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1911. int virq)
  1912. {
  1913. return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
  1914. }
  1915. int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
  1916. EventNotifier *rn, qemu_irq irq)
  1917. {
  1918. gpointer key, gsi;
  1919. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1920. if (!found) {
  1921. return -ENXIO;
  1922. }
  1923. return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
  1924. }
  1925. int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
  1926. qemu_irq irq)
  1927. {
  1928. gpointer key, gsi;
  1929. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1930. if (!found) {
  1931. return -ENXIO;
  1932. }
  1933. return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
  1934. }
  1935. void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
  1936. {
  1937. g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
  1938. }
  1939. static void kvm_irqchip_create(KVMState *s)
  1940. {
  1941. int ret;
  1942. assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
  1943. if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
  1944. ;
  1945. } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
  1946. ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
  1947. if (ret < 0) {
  1948. fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
  1949. exit(1);
  1950. }
  1951. } else {
  1952. return;
  1953. }
  1954. if (kvm_check_extension(s, KVM_CAP_IRQFD) <= 0) {
  1955. fprintf(stderr, "kvm: irqfd not implemented\n");
  1956. exit(1);
  1957. }
  1958. /* First probe and see if there's a arch-specific hook to create the
  1959. * in-kernel irqchip for us */
  1960. ret = kvm_arch_irqchip_create(s);
  1961. if (ret == 0) {
  1962. if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
  1963. error_report("Split IRQ chip mode not supported.");
  1964. exit(1);
  1965. } else {
  1966. ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
  1967. }
  1968. }
  1969. if (ret < 0) {
  1970. fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
  1971. exit(1);
  1972. }
  1973. kvm_kernel_irqchip = true;
  1974. /* If we have an in-kernel IRQ chip then we must have asynchronous
  1975. * interrupt delivery (though the reverse is not necessarily true)
  1976. */
  1977. kvm_async_interrupts_allowed = true;
  1978. kvm_halt_in_kernel_allowed = true;
  1979. kvm_init_irq_routing(s);
  1980. s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
  1981. }
  1982. /* Find number of supported CPUs using the recommended
  1983. * procedure from the kernel API documentation to cope with
  1984. * older kernels that may be missing capabilities.
  1985. */
  1986. static int kvm_recommended_vcpus(KVMState *s)
  1987. {
  1988. int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
  1989. return (ret) ? ret : 4;
  1990. }
  1991. static int kvm_max_vcpus(KVMState *s)
  1992. {
  1993. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
  1994. return (ret) ? ret : kvm_recommended_vcpus(s);
  1995. }
  1996. static int kvm_max_vcpu_id(KVMState *s)
  1997. {
  1998. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
  1999. return (ret) ? ret : kvm_max_vcpus(s);
  2000. }
  2001. bool kvm_vcpu_id_is_valid(int vcpu_id)
  2002. {
  2003. KVMState *s = KVM_STATE(current_accel());
  2004. return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
  2005. }
  2006. bool kvm_dirty_ring_enabled(void)
  2007. {
  2008. return kvm_state && kvm_state->kvm_dirty_ring_size;
  2009. }
  2010. static void query_stats_cb(StatsResultList **result, StatsTarget target,
  2011. strList *names, strList *targets, Error **errp);
  2012. static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
  2013. uint32_t kvm_dirty_ring_size(void)
  2014. {
  2015. return kvm_state->kvm_dirty_ring_size;
  2016. }
  2017. static int do_kvm_create_vm(MachineState *ms, int type)
  2018. {
  2019. KVMState *s;
  2020. int ret;
  2021. s = KVM_STATE(ms->accelerator);
  2022. do {
  2023. ret = kvm_ioctl(s, KVM_CREATE_VM, type);
  2024. } while (ret == -EINTR);
  2025. if (ret < 0) {
  2026. error_report("ioctl(KVM_CREATE_VM) failed: %s", strerror(-ret));
  2027. #ifdef TARGET_S390X
  2028. if (ret == -EINVAL) {
  2029. error_printf("Host kernel setup problem detected."
  2030. " Please verify:\n");
  2031. error_printf("- for kernels supporting the"
  2032. " switch_amode or user_mode parameters, whether");
  2033. error_printf(" user space is running in primary address space\n");
  2034. error_printf("- for kernels supporting the vm.allocate_pgste"
  2035. " sysctl, whether it is enabled\n");
  2036. }
  2037. #elif defined(TARGET_PPC)
  2038. if (ret == -EINVAL) {
  2039. error_printf("PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
  2040. (type == 2) ? "pr" : "hv");
  2041. }
  2042. #endif
  2043. }
  2044. return ret;
  2045. }
  2046. static int find_kvm_machine_type(MachineState *ms)
  2047. {
  2048. MachineClass *mc = MACHINE_GET_CLASS(ms);
  2049. int type;
  2050. if (object_property_find(OBJECT(current_machine), "kvm-type")) {
  2051. g_autofree char *kvm_type;
  2052. kvm_type = object_property_get_str(OBJECT(current_machine),
  2053. "kvm-type",
  2054. &error_abort);
  2055. type = mc->kvm_type(ms, kvm_type);
  2056. } else if (mc->kvm_type) {
  2057. type = mc->kvm_type(ms, NULL);
  2058. } else {
  2059. type = kvm_arch_get_default_type(ms);
  2060. }
  2061. return type;
  2062. }
  2063. static int kvm_setup_dirty_ring(KVMState *s)
  2064. {
  2065. uint64_t dirty_log_manual_caps;
  2066. int ret;
  2067. /*
  2068. * Enable KVM dirty ring if supported, otherwise fall back to
  2069. * dirty logging mode
  2070. */
  2071. ret = kvm_dirty_ring_init(s);
  2072. if (ret < 0) {
  2073. return ret;
  2074. }
  2075. /*
  2076. * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
  2077. * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
  2078. * page is wr-protected initially, which is against how kvm dirty ring is
  2079. * usage - kvm dirty ring requires all pages are wr-protected at the very
  2080. * beginning. Enabling this feature for dirty ring causes data corruption.
  2081. *
  2082. * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
  2083. * we may expect a higher stall time when starting the migration. In the
  2084. * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
  2085. * instead of clearing dirty bit, it can be a way to explicitly wr-protect
  2086. * guest pages.
  2087. */
  2088. if (!s->kvm_dirty_ring_size) {
  2089. dirty_log_manual_caps =
  2090. kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  2091. dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
  2092. KVM_DIRTY_LOG_INITIALLY_SET);
  2093. s->manual_dirty_log_protect = dirty_log_manual_caps;
  2094. if (dirty_log_manual_caps) {
  2095. ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
  2096. dirty_log_manual_caps);
  2097. if (ret) {
  2098. warn_report("Trying to enable capability %"PRIu64" of "
  2099. "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
  2100. "Falling back to the legacy mode. ",
  2101. dirty_log_manual_caps);
  2102. s->manual_dirty_log_protect = 0;
  2103. }
  2104. }
  2105. }
  2106. return 0;
  2107. }
  2108. static int kvm_init(MachineState *ms)
  2109. {
  2110. MachineClass *mc = MACHINE_GET_CLASS(ms);
  2111. static const char upgrade_note[] =
  2112. "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
  2113. "(see http://sourceforge.net/projects/kvm).\n";
  2114. const struct {
  2115. const char *name;
  2116. int num;
  2117. } num_cpus[] = {
  2118. { "SMP", ms->smp.cpus },
  2119. { "hotpluggable", ms->smp.max_cpus },
  2120. { /* end of list */ }
  2121. }, *nc = num_cpus;
  2122. int soft_vcpus_limit, hard_vcpus_limit;
  2123. KVMState *s;
  2124. const KVMCapabilityInfo *missing_cap;
  2125. int ret;
  2126. int type;
  2127. qemu_mutex_init(&kml_slots_lock);
  2128. s = KVM_STATE(ms->accelerator);
  2129. /*
  2130. * On systems where the kernel can support different base page
  2131. * sizes, host page size may be different from TARGET_PAGE_SIZE,
  2132. * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
  2133. * page size for the system though.
  2134. */
  2135. assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
  2136. s->sigmask_len = 8;
  2137. accel_blocker_init();
  2138. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2139. QTAILQ_INIT(&s->kvm_sw_breakpoints);
  2140. #endif
  2141. QLIST_INIT(&s->kvm_parked_vcpus);
  2142. s->fd = qemu_open_old(s->device ?: "/dev/kvm", O_RDWR);
  2143. if (s->fd == -1) {
  2144. error_report("Could not access KVM kernel module: %m");
  2145. ret = -errno;
  2146. goto err;
  2147. }
  2148. ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
  2149. if (ret < KVM_API_VERSION) {
  2150. if (ret >= 0) {
  2151. ret = -EINVAL;
  2152. }
  2153. error_report("kvm version too old");
  2154. goto err;
  2155. }
  2156. if (ret > KVM_API_VERSION) {
  2157. ret = -EINVAL;
  2158. error_report("kvm version not supported");
  2159. goto err;
  2160. }
  2161. kvm_supported_memory_attributes = kvm_check_extension(s, KVM_CAP_MEMORY_ATTRIBUTES);
  2162. kvm_guest_memfd_supported =
  2163. kvm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
  2164. kvm_check_extension(s, KVM_CAP_USER_MEMORY2) &&
  2165. (kvm_supported_memory_attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE);
  2166. kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
  2167. s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
  2168. /* If unspecified, use the default value */
  2169. if (!s->nr_slots) {
  2170. s->nr_slots = 32;
  2171. }
  2172. s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
  2173. if (s->nr_as <= 1) {
  2174. s->nr_as = 1;
  2175. }
  2176. s->as = g_new0(struct KVMAs, s->nr_as);
  2177. type = find_kvm_machine_type(ms);
  2178. if (type < 0) {
  2179. ret = -EINVAL;
  2180. goto err;
  2181. }
  2182. ret = do_kvm_create_vm(ms, type);
  2183. if (ret < 0) {
  2184. goto err;
  2185. }
  2186. s->vmfd = ret;
  2187. /* check the vcpu limits */
  2188. soft_vcpus_limit = kvm_recommended_vcpus(s);
  2189. hard_vcpus_limit = kvm_max_vcpus(s);
  2190. while (nc->name) {
  2191. if (nc->num > soft_vcpus_limit) {
  2192. warn_report("Number of %s cpus requested (%d) exceeds "
  2193. "the recommended cpus supported by KVM (%d)",
  2194. nc->name, nc->num, soft_vcpus_limit);
  2195. if (nc->num > hard_vcpus_limit) {
  2196. error_report("Number of %s cpus requested (%d) exceeds "
  2197. "the maximum cpus supported by KVM (%d)",
  2198. nc->name, nc->num, hard_vcpus_limit);
  2199. exit(1);
  2200. }
  2201. }
  2202. nc++;
  2203. }
  2204. missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
  2205. if (!missing_cap) {
  2206. missing_cap =
  2207. kvm_check_extension_list(s, kvm_arch_required_capabilities);
  2208. }
  2209. if (missing_cap) {
  2210. ret = -EINVAL;
  2211. error_report("kvm does not support %s", missing_cap->name);
  2212. error_printf("%s", upgrade_note);
  2213. goto err;
  2214. }
  2215. s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
  2216. s->coalesced_pio = s->coalesced_mmio &&
  2217. kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
  2218. ret = kvm_setup_dirty_ring(s);
  2219. if (ret < 0) {
  2220. goto err;
  2221. }
  2222. #ifdef KVM_CAP_VCPU_EVENTS
  2223. s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
  2224. #endif
  2225. s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
  2226. s->irq_set_ioctl = KVM_IRQ_LINE;
  2227. if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
  2228. s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
  2229. }
  2230. kvm_readonly_mem_allowed =
  2231. (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
  2232. kvm_resamplefds_allowed =
  2233. (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
  2234. kvm_vm_attributes_allowed =
  2235. (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
  2236. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2237. kvm_has_guest_debug =
  2238. (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
  2239. #endif
  2240. kvm_sstep_flags = 0;
  2241. if (kvm_has_guest_debug) {
  2242. kvm_sstep_flags = SSTEP_ENABLE;
  2243. #if defined TARGET_KVM_HAVE_GUEST_DEBUG
  2244. int guest_debug_flags =
  2245. kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
  2246. if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
  2247. kvm_sstep_flags |= SSTEP_NOIRQ;
  2248. }
  2249. #endif
  2250. }
  2251. kvm_state = s;
  2252. ret = kvm_arch_init(ms, s);
  2253. if (ret < 0) {
  2254. goto err;
  2255. }
  2256. if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
  2257. s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
  2258. }
  2259. qemu_register_reset(kvm_unpoison_all, NULL);
  2260. if (s->kernel_irqchip_allowed) {
  2261. kvm_irqchip_create(s);
  2262. }
  2263. s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
  2264. s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
  2265. s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
  2266. s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
  2267. kvm_memory_listener_register(s, &s->memory_listener,
  2268. &address_space_memory, 0, "kvm-memory");
  2269. memory_listener_register(&kvm_io_listener,
  2270. &address_space_io);
  2271. s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
  2272. if (!s->sync_mmu) {
  2273. ret = ram_block_discard_disable(true);
  2274. assert(!ret);
  2275. }
  2276. if (s->kvm_dirty_ring_size) {
  2277. kvm_dirty_ring_reaper_init(s);
  2278. }
  2279. if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
  2280. add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
  2281. query_stats_schemas_cb);
  2282. }
  2283. return 0;
  2284. err:
  2285. assert(ret < 0);
  2286. if (s->vmfd >= 0) {
  2287. close(s->vmfd);
  2288. }
  2289. if (s->fd != -1) {
  2290. close(s->fd);
  2291. }
  2292. g_free(s->as);
  2293. g_free(s->memory_listener.slots);
  2294. return ret;
  2295. }
  2296. void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
  2297. {
  2298. s->sigmask_len = sigmask_len;
  2299. }
  2300. static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
  2301. int size, uint32_t count)
  2302. {
  2303. int i;
  2304. uint8_t *ptr = data;
  2305. for (i = 0; i < count; i++) {
  2306. address_space_rw(&address_space_io, port, attrs,
  2307. ptr, size,
  2308. direction == KVM_EXIT_IO_OUT);
  2309. ptr += size;
  2310. }
  2311. }
  2312. static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
  2313. {
  2314. int i;
  2315. fprintf(stderr, "KVM internal error. Suberror: %d\n",
  2316. run->internal.suberror);
  2317. for (i = 0; i < run->internal.ndata; ++i) {
  2318. fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
  2319. i, (uint64_t)run->internal.data[i]);
  2320. }
  2321. if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
  2322. fprintf(stderr, "emulation failure\n");
  2323. if (!kvm_arch_stop_on_emulation_error(cpu)) {
  2324. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2325. return EXCP_INTERRUPT;
  2326. }
  2327. }
  2328. /* FIXME: Should trigger a qmp message to let management know
  2329. * something went wrong.
  2330. */
  2331. return -1;
  2332. }
  2333. void kvm_flush_coalesced_mmio_buffer(void)
  2334. {
  2335. KVMState *s = kvm_state;
  2336. if (!s || s->coalesced_flush_in_progress) {
  2337. return;
  2338. }
  2339. s->coalesced_flush_in_progress = true;
  2340. if (s->coalesced_mmio_ring) {
  2341. struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
  2342. while (ring->first != ring->last) {
  2343. struct kvm_coalesced_mmio *ent;
  2344. ent = &ring->coalesced_mmio[ring->first];
  2345. if (ent->pio == 1) {
  2346. address_space_write(&address_space_io, ent->phys_addr,
  2347. MEMTXATTRS_UNSPECIFIED, ent->data,
  2348. ent->len);
  2349. } else {
  2350. cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
  2351. }
  2352. smp_wmb();
  2353. ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
  2354. }
  2355. }
  2356. s->coalesced_flush_in_progress = false;
  2357. }
  2358. static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
  2359. {
  2360. if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
  2361. Error *err = NULL;
  2362. int ret = kvm_arch_get_registers(cpu, &err);
  2363. if (ret) {
  2364. if (err) {
  2365. error_reportf_err(err, "Failed to synchronize CPU state: ");
  2366. } else {
  2367. error_report("Failed to get registers: %s", strerror(-ret));
  2368. }
  2369. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2370. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2371. }
  2372. cpu->vcpu_dirty = true;
  2373. }
  2374. }
  2375. void kvm_cpu_synchronize_state(CPUState *cpu)
  2376. {
  2377. if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
  2378. run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
  2379. }
  2380. }
  2381. static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
  2382. {
  2383. Error *err = NULL;
  2384. int ret = kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE, &err);
  2385. if (ret) {
  2386. if (err) {
  2387. error_reportf_err(err, "Restoring resisters after reset: ");
  2388. } else {
  2389. error_report("Failed to put registers after reset: %s",
  2390. strerror(-ret));
  2391. }
  2392. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2393. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2394. }
  2395. cpu->vcpu_dirty = false;
  2396. }
  2397. void kvm_cpu_synchronize_post_reset(CPUState *cpu)
  2398. {
  2399. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
  2400. }
  2401. static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
  2402. {
  2403. Error *err = NULL;
  2404. int ret = kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE, &err);
  2405. if (ret) {
  2406. if (err) {
  2407. error_reportf_err(err, "Putting registers after init: ");
  2408. } else {
  2409. error_report("Failed to put registers after init: %s",
  2410. strerror(-ret));
  2411. }
  2412. exit(1);
  2413. }
  2414. cpu->vcpu_dirty = false;
  2415. }
  2416. void kvm_cpu_synchronize_post_init(CPUState *cpu)
  2417. {
  2418. if (!kvm_state->guest_state_protected) {
  2419. /*
  2420. * This runs before the machine_init_done notifiers, and is the last
  2421. * opportunity to synchronize the state of confidential guests.
  2422. */
  2423. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
  2424. }
  2425. }
  2426. static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
  2427. {
  2428. cpu->vcpu_dirty = true;
  2429. }
  2430. void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
  2431. {
  2432. run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
  2433. }
  2434. #ifdef KVM_HAVE_MCE_INJECTION
  2435. static __thread void *pending_sigbus_addr;
  2436. static __thread int pending_sigbus_code;
  2437. static __thread bool have_sigbus_pending;
  2438. #endif
  2439. static void kvm_cpu_kick(CPUState *cpu)
  2440. {
  2441. qatomic_set(&cpu->kvm_run->immediate_exit, 1);
  2442. }
  2443. static void kvm_cpu_kick_self(void)
  2444. {
  2445. if (kvm_immediate_exit) {
  2446. kvm_cpu_kick(current_cpu);
  2447. } else {
  2448. qemu_cpu_kick_self();
  2449. }
  2450. }
  2451. static void kvm_eat_signals(CPUState *cpu)
  2452. {
  2453. struct timespec ts = { 0, 0 };
  2454. siginfo_t siginfo;
  2455. sigset_t waitset;
  2456. sigset_t chkset;
  2457. int r;
  2458. if (kvm_immediate_exit) {
  2459. qatomic_set(&cpu->kvm_run->immediate_exit, 0);
  2460. /* Write kvm_run->immediate_exit before the cpu->exit_request
  2461. * write in kvm_cpu_exec.
  2462. */
  2463. smp_wmb();
  2464. return;
  2465. }
  2466. sigemptyset(&waitset);
  2467. sigaddset(&waitset, SIG_IPI);
  2468. do {
  2469. r = sigtimedwait(&waitset, &siginfo, &ts);
  2470. if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
  2471. perror("sigtimedwait");
  2472. exit(1);
  2473. }
  2474. r = sigpending(&chkset);
  2475. if (r == -1) {
  2476. perror("sigpending");
  2477. exit(1);
  2478. }
  2479. } while (sigismember(&chkset, SIG_IPI));
  2480. }
  2481. int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
  2482. {
  2483. MemoryRegionSection section;
  2484. ram_addr_t offset;
  2485. MemoryRegion *mr;
  2486. RAMBlock *rb;
  2487. void *addr;
  2488. int ret = -1;
  2489. trace_kvm_convert_memory(start, size, to_private ? "shared_to_private" : "private_to_shared");
  2490. if (!QEMU_PTR_IS_ALIGNED(start, qemu_real_host_page_size()) ||
  2491. !QEMU_PTR_IS_ALIGNED(size, qemu_real_host_page_size())) {
  2492. return -1;
  2493. }
  2494. if (!size) {
  2495. return -1;
  2496. }
  2497. section = memory_region_find(get_system_memory(), start, size);
  2498. mr = section.mr;
  2499. if (!mr) {
  2500. /*
  2501. * Ignore converting non-assigned region to shared.
  2502. *
  2503. * TDX requires vMMIO region to be shared to inject #VE to guest.
  2504. * OVMF issues conservatively MapGPA(shared) on 32bit PCI MMIO region,
  2505. * and vIO-APIC 0xFEC00000 4K page.
  2506. * OVMF assigns 32bit PCI MMIO region to
  2507. * [top of low memory: typically 2GB=0xC000000, 0xFC00000)
  2508. */
  2509. if (!to_private) {
  2510. return 0;
  2511. }
  2512. return -1;
  2513. }
  2514. if (!memory_region_has_guest_memfd(mr)) {
  2515. /*
  2516. * Because vMMIO region must be shared, guest TD may convert vMMIO
  2517. * region to shared explicitly. Don't complain such case. See
  2518. * memory_region_type() for checking if the region is MMIO region.
  2519. */
  2520. if (!to_private &&
  2521. !memory_region_is_ram(mr) &&
  2522. !memory_region_is_ram_device(mr) &&
  2523. !memory_region_is_rom(mr) &&
  2524. !memory_region_is_romd(mr)) {
  2525. ret = 0;
  2526. } else {
  2527. error_report("Convert non guest_memfd backed memory region "
  2528. "(0x%"HWADDR_PRIx" ,+ 0x%"HWADDR_PRIx") to %s",
  2529. start, size, to_private ? "private" : "shared");
  2530. }
  2531. goto out_unref;
  2532. }
  2533. if (to_private) {
  2534. ret = kvm_set_memory_attributes_private(start, size);
  2535. } else {
  2536. ret = kvm_set_memory_attributes_shared(start, size);
  2537. }
  2538. if (ret) {
  2539. goto out_unref;
  2540. }
  2541. addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
  2542. rb = qemu_ram_block_from_host(addr, false, &offset);
  2543. if (to_private) {
  2544. if (rb->page_size != qemu_real_host_page_size()) {
  2545. /*
  2546. * shared memory is backed by hugetlb, which is supposed to be
  2547. * pre-allocated and doesn't need to be discarded
  2548. */
  2549. goto out_unref;
  2550. }
  2551. ret = ram_block_discard_range(rb, offset, size);
  2552. } else {
  2553. ret = ram_block_discard_guest_memfd_range(rb, offset, size);
  2554. }
  2555. out_unref:
  2556. memory_region_unref(mr);
  2557. return ret;
  2558. }
  2559. int kvm_cpu_exec(CPUState *cpu)
  2560. {
  2561. struct kvm_run *run = cpu->kvm_run;
  2562. int ret, run_ret;
  2563. trace_kvm_cpu_exec();
  2564. if (kvm_arch_process_async_events(cpu)) {
  2565. qatomic_set(&cpu->exit_request, 0);
  2566. return EXCP_HLT;
  2567. }
  2568. bql_unlock();
  2569. cpu_exec_start(cpu);
  2570. do {
  2571. MemTxAttrs attrs;
  2572. if (cpu->vcpu_dirty) {
  2573. Error *err = NULL;
  2574. ret = kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE, &err);
  2575. if (ret) {
  2576. if (err) {
  2577. error_reportf_err(err, "Putting registers after init: ");
  2578. } else {
  2579. error_report("Failed to put registers after init: %s",
  2580. strerror(-ret));
  2581. }
  2582. ret = -1;
  2583. break;
  2584. }
  2585. cpu->vcpu_dirty = false;
  2586. }
  2587. kvm_arch_pre_run(cpu, run);
  2588. if (qatomic_read(&cpu->exit_request)) {
  2589. trace_kvm_interrupt_exit_request();
  2590. /*
  2591. * KVM requires us to reenter the kernel after IO exits to complete
  2592. * instruction emulation. This self-signal will ensure that we
  2593. * leave ASAP again.
  2594. */
  2595. kvm_cpu_kick_self();
  2596. }
  2597. /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
  2598. * Matching barrier in kvm_eat_signals.
  2599. */
  2600. smp_rmb();
  2601. run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
  2602. attrs = kvm_arch_post_run(cpu, run);
  2603. #ifdef KVM_HAVE_MCE_INJECTION
  2604. if (unlikely(have_sigbus_pending)) {
  2605. bql_lock();
  2606. kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
  2607. pending_sigbus_addr);
  2608. have_sigbus_pending = false;
  2609. bql_unlock();
  2610. }
  2611. #endif
  2612. if (run_ret < 0) {
  2613. if (run_ret == -EINTR || run_ret == -EAGAIN) {
  2614. trace_kvm_io_window_exit();
  2615. kvm_eat_signals(cpu);
  2616. ret = EXCP_INTERRUPT;
  2617. break;
  2618. }
  2619. if (!(run_ret == -EFAULT && run->exit_reason == KVM_EXIT_MEMORY_FAULT)) {
  2620. fprintf(stderr, "error: kvm run failed %s\n",
  2621. strerror(-run_ret));
  2622. #ifdef TARGET_PPC
  2623. if (run_ret == -EBUSY) {
  2624. fprintf(stderr,
  2625. "This is probably because your SMT is enabled.\n"
  2626. "VCPU can only run on primary threads with all "
  2627. "secondary threads offline.\n");
  2628. }
  2629. #endif
  2630. ret = -1;
  2631. break;
  2632. }
  2633. }
  2634. trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
  2635. switch (run->exit_reason) {
  2636. case KVM_EXIT_IO:
  2637. /* Called outside BQL */
  2638. kvm_handle_io(run->io.port, attrs,
  2639. (uint8_t *)run + run->io.data_offset,
  2640. run->io.direction,
  2641. run->io.size,
  2642. run->io.count);
  2643. ret = 0;
  2644. break;
  2645. case KVM_EXIT_MMIO:
  2646. /* Called outside BQL */
  2647. address_space_rw(&address_space_memory,
  2648. run->mmio.phys_addr, attrs,
  2649. run->mmio.data,
  2650. run->mmio.len,
  2651. run->mmio.is_write);
  2652. ret = 0;
  2653. break;
  2654. case KVM_EXIT_IRQ_WINDOW_OPEN:
  2655. ret = EXCP_INTERRUPT;
  2656. break;
  2657. case KVM_EXIT_SHUTDOWN:
  2658. qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
  2659. ret = EXCP_INTERRUPT;
  2660. break;
  2661. case KVM_EXIT_UNKNOWN:
  2662. fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
  2663. (uint64_t)run->hw.hardware_exit_reason);
  2664. ret = -1;
  2665. break;
  2666. case KVM_EXIT_INTERNAL_ERROR:
  2667. ret = kvm_handle_internal_error(cpu, run);
  2668. break;
  2669. case KVM_EXIT_DIRTY_RING_FULL:
  2670. /*
  2671. * We shouldn't continue if the dirty ring of this vcpu is
  2672. * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
  2673. */
  2674. trace_kvm_dirty_ring_full(cpu->cpu_index);
  2675. bql_lock();
  2676. /*
  2677. * We throttle vCPU by making it sleep once it exit from kernel
  2678. * due to dirty ring full. In the dirtylimit scenario, reaping
  2679. * all vCPUs after a single vCPU dirty ring get full result in
  2680. * the miss of sleep, so just reap the ring-fulled vCPU.
  2681. */
  2682. if (dirtylimit_in_service()) {
  2683. kvm_dirty_ring_reap(kvm_state, cpu);
  2684. } else {
  2685. kvm_dirty_ring_reap(kvm_state, NULL);
  2686. }
  2687. bql_unlock();
  2688. dirtylimit_vcpu_execute(cpu);
  2689. ret = 0;
  2690. break;
  2691. case KVM_EXIT_SYSTEM_EVENT:
  2692. trace_kvm_run_exit_system_event(cpu->cpu_index, run->system_event.type);
  2693. switch (run->system_event.type) {
  2694. case KVM_SYSTEM_EVENT_SHUTDOWN:
  2695. qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
  2696. ret = EXCP_INTERRUPT;
  2697. break;
  2698. case KVM_SYSTEM_EVENT_RESET:
  2699. qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
  2700. ret = EXCP_INTERRUPT;
  2701. break;
  2702. case KVM_SYSTEM_EVENT_CRASH:
  2703. kvm_cpu_synchronize_state(cpu);
  2704. bql_lock();
  2705. qemu_system_guest_panicked(cpu_get_crash_info(cpu));
  2706. bql_unlock();
  2707. ret = 0;
  2708. break;
  2709. default:
  2710. ret = kvm_arch_handle_exit(cpu, run);
  2711. break;
  2712. }
  2713. break;
  2714. case KVM_EXIT_MEMORY_FAULT:
  2715. trace_kvm_memory_fault(run->memory_fault.gpa,
  2716. run->memory_fault.size,
  2717. run->memory_fault.flags);
  2718. if (run->memory_fault.flags & ~KVM_MEMORY_EXIT_FLAG_PRIVATE) {
  2719. error_report("KVM_EXIT_MEMORY_FAULT: Unknown flag 0x%" PRIx64,
  2720. (uint64_t)run->memory_fault.flags);
  2721. ret = -1;
  2722. break;
  2723. }
  2724. ret = kvm_convert_memory(run->memory_fault.gpa, run->memory_fault.size,
  2725. run->memory_fault.flags & KVM_MEMORY_EXIT_FLAG_PRIVATE);
  2726. break;
  2727. default:
  2728. ret = kvm_arch_handle_exit(cpu, run);
  2729. break;
  2730. }
  2731. } while (ret == 0);
  2732. cpu_exec_end(cpu);
  2733. bql_lock();
  2734. if (ret < 0) {
  2735. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2736. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2737. }
  2738. qatomic_set(&cpu->exit_request, 0);
  2739. return ret;
  2740. }
  2741. int kvm_ioctl(KVMState *s, unsigned long type, ...)
  2742. {
  2743. int ret;
  2744. void *arg;
  2745. va_list ap;
  2746. va_start(ap, type);
  2747. arg = va_arg(ap, void *);
  2748. va_end(ap);
  2749. trace_kvm_ioctl(type, arg);
  2750. ret = ioctl(s->fd, type, arg);
  2751. if (ret == -1) {
  2752. ret = -errno;
  2753. }
  2754. return ret;
  2755. }
  2756. int kvm_vm_ioctl(KVMState *s, unsigned long type, ...)
  2757. {
  2758. int ret;
  2759. void *arg;
  2760. va_list ap;
  2761. va_start(ap, type);
  2762. arg = va_arg(ap, void *);
  2763. va_end(ap);
  2764. trace_kvm_vm_ioctl(type, arg);
  2765. accel_ioctl_begin();
  2766. ret = ioctl(s->vmfd, type, arg);
  2767. accel_ioctl_end();
  2768. if (ret == -1) {
  2769. ret = -errno;
  2770. }
  2771. return ret;
  2772. }
  2773. int kvm_vcpu_ioctl(CPUState *cpu, unsigned long type, ...)
  2774. {
  2775. int ret;
  2776. void *arg;
  2777. va_list ap;
  2778. va_start(ap, type);
  2779. arg = va_arg(ap, void *);
  2780. va_end(ap);
  2781. trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
  2782. accel_cpu_ioctl_begin(cpu);
  2783. ret = ioctl(cpu->kvm_fd, type, arg);
  2784. accel_cpu_ioctl_end(cpu);
  2785. if (ret == -1) {
  2786. ret = -errno;
  2787. }
  2788. return ret;
  2789. }
  2790. int kvm_device_ioctl(int fd, unsigned long type, ...)
  2791. {
  2792. int ret;
  2793. void *arg;
  2794. va_list ap;
  2795. va_start(ap, type);
  2796. arg = va_arg(ap, void *);
  2797. va_end(ap);
  2798. trace_kvm_device_ioctl(fd, type, arg);
  2799. accel_ioctl_begin();
  2800. ret = ioctl(fd, type, arg);
  2801. accel_ioctl_end();
  2802. if (ret == -1) {
  2803. ret = -errno;
  2804. }
  2805. return ret;
  2806. }
  2807. int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
  2808. {
  2809. int ret;
  2810. struct kvm_device_attr attribute = {
  2811. .group = group,
  2812. .attr = attr,
  2813. };
  2814. if (!kvm_vm_attributes_allowed) {
  2815. return 0;
  2816. }
  2817. ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
  2818. /* kvm returns 0 on success for HAS_DEVICE_ATTR */
  2819. return ret ? 0 : 1;
  2820. }
  2821. int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
  2822. {
  2823. struct kvm_device_attr attribute = {
  2824. .group = group,
  2825. .attr = attr,
  2826. .flags = 0,
  2827. };
  2828. return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
  2829. }
  2830. int kvm_device_access(int fd, int group, uint64_t attr,
  2831. void *val, bool write, Error **errp)
  2832. {
  2833. struct kvm_device_attr kvmattr;
  2834. int err;
  2835. kvmattr.flags = 0;
  2836. kvmattr.group = group;
  2837. kvmattr.attr = attr;
  2838. kvmattr.addr = (uintptr_t)val;
  2839. err = kvm_device_ioctl(fd,
  2840. write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
  2841. &kvmattr);
  2842. if (err < 0) {
  2843. error_setg_errno(errp, -err,
  2844. "KVM_%s_DEVICE_ATTR failed: Group %d "
  2845. "attr 0x%016" PRIx64,
  2846. write ? "SET" : "GET", group, attr);
  2847. }
  2848. return err;
  2849. }
  2850. bool kvm_has_sync_mmu(void)
  2851. {
  2852. return kvm_state->sync_mmu;
  2853. }
  2854. int kvm_has_vcpu_events(void)
  2855. {
  2856. return kvm_state->vcpu_events;
  2857. }
  2858. int kvm_max_nested_state_length(void)
  2859. {
  2860. return kvm_state->max_nested_state_len;
  2861. }
  2862. int kvm_has_gsi_routing(void)
  2863. {
  2864. #ifdef KVM_CAP_IRQ_ROUTING
  2865. return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
  2866. #else
  2867. return false;
  2868. #endif
  2869. }
  2870. bool kvm_arm_supports_user_irq(void)
  2871. {
  2872. return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
  2873. }
  2874. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2875. struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu, vaddr pc)
  2876. {
  2877. struct kvm_sw_breakpoint *bp;
  2878. QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
  2879. if (bp->pc == pc) {
  2880. return bp;
  2881. }
  2882. }
  2883. return NULL;
  2884. }
  2885. int kvm_sw_breakpoints_active(CPUState *cpu)
  2886. {
  2887. return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
  2888. }
  2889. struct kvm_set_guest_debug_data {
  2890. struct kvm_guest_debug dbg;
  2891. int err;
  2892. };
  2893. static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
  2894. {
  2895. struct kvm_set_guest_debug_data *dbg_data =
  2896. (struct kvm_set_guest_debug_data *) data.host_ptr;
  2897. dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
  2898. &dbg_data->dbg);
  2899. }
  2900. int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
  2901. {
  2902. struct kvm_set_guest_debug_data data;
  2903. data.dbg.control = reinject_trap;
  2904. if (cpu->singlestep_enabled) {
  2905. data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
  2906. if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
  2907. data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
  2908. }
  2909. }
  2910. kvm_arch_update_guest_debug(cpu, &data.dbg);
  2911. run_on_cpu(cpu, kvm_invoke_set_guest_debug,
  2912. RUN_ON_CPU_HOST_PTR(&data));
  2913. return data.err;
  2914. }
  2915. bool kvm_supports_guest_debug(void)
  2916. {
  2917. /* probed during kvm_init() */
  2918. return kvm_has_guest_debug;
  2919. }
  2920. int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
  2921. {
  2922. struct kvm_sw_breakpoint *bp;
  2923. int err;
  2924. if (type == GDB_BREAKPOINT_SW) {
  2925. bp = kvm_find_sw_breakpoint(cpu, addr);
  2926. if (bp) {
  2927. bp->use_count++;
  2928. return 0;
  2929. }
  2930. bp = g_new(struct kvm_sw_breakpoint, 1);
  2931. bp->pc = addr;
  2932. bp->use_count = 1;
  2933. err = kvm_arch_insert_sw_breakpoint(cpu, bp);
  2934. if (err) {
  2935. g_free(bp);
  2936. return err;
  2937. }
  2938. QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  2939. } else {
  2940. err = kvm_arch_insert_hw_breakpoint(addr, len, type);
  2941. if (err) {
  2942. return err;
  2943. }
  2944. }
  2945. CPU_FOREACH(cpu) {
  2946. err = kvm_update_guest_debug(cpu, 0);
  2947. if (err) {
  2948. return err;
  2949. }
  2950. }
  2951. return 0;
  2952. }
  2953. int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
  2954. {
  2955. struct kvm_sw_breakpoint *bp;
  2956. int err;
  2957. if (type == GDB_BREAKPOINT_SW) {
  2958. bp = kvm_find_sw_breakpoint(cpu, addr);
  2959. if (!bp) {
  2960. return -ENOENT;
  2961. }
  2962. if (bp->use_count > 1) {
  2963. bp->use_count--;
  2964. return 0;
  2965. }
  2966. err = kvm_arch_remove_sw_breakpoint(cpu, bp);
  2967. if (err) {
  2968. return err;
  2969. }
  2970. QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  2971. g_free(bp);
  2972. } else {
  2973. err = kvm_arch_remove_hw_breakpoint(addr, len, type);
  2974. if (err) {
  2975. return err;
  2976. }
  2977. }
  2978. CPU_FOREACH(cpu) {
  2979. err = kvm_update_guest_debug(cpu, 0);
  2980. if (err) {
  2981. return err;
  2982. }
  2983. }
  2984. return 0;
  2985. }
  2986. void kvm_remove_all_breakpoints(CPUState *cpu)
  2987. {
  2988. struct kvm_sw_breakpoint *bp, *next;
  2989. KVMState *s = cpu->kvm_state;
  2990. CPUState *tmpcpu;
  2991. QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
  2992. if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
  2993. /* Try harder to find a CPU that currently sees the breakpoint. */
  2994. CPU_FOREACH(tmpcpu) {
  2995. if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
  2996. break;
  2997. }
  2998. }
  2999. }
  3000. QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
  3001. g_free(bp);
  3002. }
  3003. kvm_arch_remove_all_hw_breakpoints();
  3004. CPU_FOREACH(cpu) {
  3005. kvm_update_guest_debug(cpu, 0);
  3006. }
  3007. }
  3008. #endif /* !TARGET_KVM_HAVE_GUEST_DEBUG */
  3009. static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
  3010. {
  3011. KVMState *s = kvm_state;
  3012. struct kvm_signal_mask *sigmask;
  3013. int r;
  3014. sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
  3015. sigmask->len = s->sigmask_len;
  3016. memcpy(sigmask->sigset, sigset, sizeof(*sigset));
  3017. r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
  3018. g_free(sigmask);
  3019. return r;
  3020. }
  3021. static void kvm_ipi_signal(int sig)
  3022. {
  3023. if (current_cpu) {
  3024. assert(kvm_immediate_exit);
  3025. kvm_cpu_kick(current_cpu);
  3026. }
  3027. }
  3028. void kvm_init_cpu_signals(CPUState *cpu)
  3029. {
  3030. int r;
  3031. sigset_t set;
  3032. struct sigaction sigact;
  3033. memset(&sigact, 0, sizeof(sigact));
  3034. sigact.sa_handler = kvm_ipi_signal;
  3035. sigaction(SIG_IPI, &sigact, NULL);
  3036. pthread_sigmask(SIG_BLOCK, NULL, &set);
  3037. #if defined KVM_HAVE_MCE_INJECTION
  3038. sigdelset(&set, SIGBUS);
  3039. pthread_sigmask(SIG_SETMASK, &set, NULL);
  3040. #endif
  3041. sigdelset(&set, SIG_IPI);
  3042. if (kvm_immediate_exit) {
  3043. r = pthread_sigmask(SIG_SETMASK, &set, NULL);
  3044. } else {
  3045. r = kvm_set_signal_mask(cpu, &set);
  3046. }
  3047. if (r) {
  3048. fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
  3049. exit(1);
  3050. }
  3051. }
  3052. /* Called asynchronously in VCPU thread. */
  3053. int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
  3054. {
  3055. #ifdef KVM_HAVE_MCE_INJECTION
  3056. if (have_sigbus_pending) {
  3057. return 1;
  3058. }
  3059. have_sigbus_pending = true;
  3060. pending_sigbus_addr = addr;
  3061. pending_sigbus_code = code;
  3062. qatomic_set(&cpu->exit_request, 1);
  3063. return 0;
  3064. #else
  3065. return 1;
  3066. #endif
  3067. }
  3068. /* Called synchronously (via signalfd) in main thread. */
  3069. int kvm_on_sigbus(int code, void *addr)
  3070. {
  3071. #ifdef KVM_HAVE_MCE_INJECTION
  3072. /* Action required MCE kills the process if SIGBUS is blocked. Because
  3073. * that's what happens in the I/O thread, where we handle MCE via signalfd,
  3074. * we can only get action optional here.
  3075. */
  3076. assert(code != BUS_MCEERR_AR);
  3077. kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
  3078. return 0;
  3079. #else
  3080. return 1;
  3081. #endif
  3082. }
  3083. int kvm_create_device(KVMState *s, uint64_t type, bool test)
  3084. {
  3085. int ret;
  3086. struct kvm_create_device create_dev;
  3087. create_dev.type = type;
  3088. create_dev.fd = -1;
  3089. create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
  3090. if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
  3091. return -ENOTSUP;
  3092. }
  3093. ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
  3094. if (ret) {
  3095. return ret;
  3096. }
  3097. return test ? 0 : create_dev.fd;
  3098. }
  3099. bool kvm_device_supported(int vmfd, uint64_t type)
  3100. {
  3101. struct kvm_create_device create_dev = {
  3102. .type = type,
  3103. .fd = -1,
  3104. .flags = KVM_CREATE_DEVICE_TEST,
  3105. };
  3106. if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
  3107. return false;
  3108. }
  3109. return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
  3110. }
  3111. int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
  3112. {
  3113. struct kvm_one_reg reg;
  3114. int r;
  3115. reg.id = id;
  3116. reg.addr = (uintptr_t) source;
  3117. r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
  3118. if (r) {
  3119. trace_kvm_failed_reg_set(id, strerror(-r));
  3120. }
  3121. return r;
  3122. }
  3123. int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
  3124. {
  3125. struct kvm_one_reg reg;
  3126. int r;
  3127. reg.id = id;
  3128. reg.addr = (uintptr_t) target;
  3129. r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
  3130. if (r) {
  3131. trace_kvm_failed_reg_get(id, strerror(-r));
  3132. }
  3133. return r;
  3134. }
  3135. static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
  3136. hwaddr start_addr, hwaddr size)
  3137. {
  3138. KVMState *kvm = KVM_STATE(ms->accelerator);
  3139. int i;
  3140. for (i = 0; i < kvm->nr_as; ++i) {
  3141. if (kvm->as[i].as == as && kvm->as[i].ml) {
  3142. size = MIN(kvm_max_slot_size, size);
  3143. return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
  3144. start_addr, size);
  3145. }
  3146. }
  3147. return false;
  3148. }
  3149. static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
  3150. const char *name, void *opaque,
  3151. Error **errp)
  3152. {
  3153. KVMState *s = KVM_STATE(obj);
  3154. int64_t value = s->kvm_shadow_mem;
  3155. visit_type_int(v, name, &value, errp);
  3156. }
  3157. static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
  3158. const char *name, void *opaque,
  3159. Error **errp)
  3160. {
  3161. KVMState *s = KVM_STATE(obj);
  3162. int64_t value;
  3163. if (s->fd != -1) {
  3164. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3165. return;
  3166. }
  3167. if (!visit_type_int(v, name, &value, errp)) {
  3168. return;
  3169. }
  3170. s->kvm_shadow_mem = value;
  3171. }
  3172. static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
  3173. const char *name, void *opaque,
  3174. Error **errp)
  3175. {
  3176. KVMState *s = KVM_STATE(obj);
  3177. OnOffSplit mode;
  3178. if (s->fd != -1) {
  3179. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3180. return;
  3181. }
  3182. if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
  3183. return;
  3184. }
  3185. switch (mode) {
  3186. case ON_OFF_SPLIT_ON:
  3187. s->kernel_irqchip_allowed = true;
  3188. s->kernel_irqchip_required = true;
  3189. s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
  3190. break;
  3191. case ON_OFF_SPLIT_OFF:
  3192. s->kernel_irqchip_allowed = false;
  3193. s->kernel_irqchip_required = false;
  3194. s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
  3195. break;
  3196. case ON_OFF_SPLIT_SPLIT:
  3197. s->kernel_irqchip_allowed = true;
  3198. s->kernel_irqchip_required = true;
  3199. s->kernel_irqchip_split = ON_OFF_AUTO_ON;
  3200. break;
  3201. default:
  3202. /* The value was checked in visit_type_OnOffSplit() above. If
  3203. * we get here, then something is wrong in QEMU.
  3204. */
  3205. abort();
  3206. }
  3207. }
  3208. bool kvm_kernel_irqchip_allowed(void)
  3209. {
  3210. return kvm_state->kernel_irqchip_allowed;
  3211. }
  3212. bool kvm_kernel_irqchip_required(void)
  3213. {
  3214. return kvm_state->kernel_irqchip_required;
  3215. }
  3216. bool kvm_kernel_irqchip_split(void)
  3217. {
  3218. return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
  3219. }
  3220. static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
  3221. const char *name, void *opaque,
  3222. Error **errp)
  3223. {
  3224. KVMState *s = KVM_STATE(obj);
  3225. uint32_t value = s->kvm_dirty_ring_size;
  3226. visit_type_uint32(v, name, &value, errp);
  3227. }
  3228. static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
  3229. const char *name, void *opaque,
  3230. Error **errp)
  3231. {
  3232. KVMState *s = KVM_STATE(obj);
  3233. uint32_t value;
  3234. if (s->fd != -1) {
  3235. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3236. return;
  3237. }
  3238. if (!visit_type_uint32(v, name, &value, errp)) {
  3239. return;
  3240. }
  3241. if (value & (value - 1)) {
  3242. error_setg(errp, "dirty-ring-size must be a power of two.");
  3243. return;
  3244. }
  3245. s->kvm_dirty_ring_size = value;
  3246. }
  3247. static char *kvm_get_device(Object *obj,
  3248. Error **errp G_GNUC_UNUSED)
  3249. {
  3250. KVMState *s = KVM_STATE(obj);
  3251. return g_strdup(s->device);
  3252. }
  3253. static void kvm_set_device(Object *obj,
  3254. const char *value,
  3255. Error **errp G_GNUC_UNUSED)
  3256. {
  3257. KVMState *s = KVM_STATE(obj);
  3258. g_free(s->device);
  3259. s->device = g_strdup(value);
  3260. }
  3261. static void kvm_set_kvm_rapl(Object *obj, bool value, Error **errp)
  3262. {
  3263. KVMState *s = KVM_STATE(obj);
  3264. s->msr_energy.enable = value;
  3265. }
  3266. static void kvm_set_kvm_rapl_socket_path(Object *obj,
  3267. const char *str,
  3268. Error **errp)
  3269. {
  3270. KVMState *s = KVM_STATE(obj);
  3271. g_free(s->msr_energy.socket_path);
  3272. s->msr_energy.socket_path = g_strdup(str);
  3273. }
  3274. static void kvm_accel_instance_init(Object *obj)
  3275. {
  3276. KVMState *s = KVM_STATE(obj);
  3277. s->fd = -1;
  3278. s->vmfd = -1;
  3279. s->kvm_shadow_mem = -1;
  3280. s->kernel_irqchip_allowed = true;
  3281. s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
  3282. /* KVM dirty ring is by default off */
  3283. s->kvm_dirty_ring_size = 0;
  3284. s->kvm_dirty_ring_with_bitmap = false;
  3285. s->kvm_eager_split_size = 0;
  3286. s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
  3287. s->notify_window = 0;
  3288. s->xen_version = 0;
  3289. s->xen_gnttab_max_frames = 64;
  3290. s->xen_evtchn_max_pirq = 256;
  3291. s->device = NULL;
  3292. s->msr_energy.enable = false;
  3293. }
  3294. /**
  3295. * kvm_gdbstub_sstep_flags():
  3296. *
  3297. * Returns: SSTEP_* flags that KVM supports for guest debug. The
  3298. * support is probed during kvm_init()
  3299. */
  3300. static int kvm_gdbstub_sstep_flags(void)
  3301. {
  3302. return kvm_sstep_flags;
  3303. }
  3304. static void kvm_accel_class_init(ObjectClass *oc, void *data)
  3305. {
  3306. AccelClass *ac = ACCEL_CLASS(oc);
  3307. ac->name = "KVM";
  3308. ac->init_machine = kvm_init;
  3309. ac->has_memory = kvm_accel_has_memory;
  3310. ac->allowed = &kvm_allowed;
  3311. ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
  3312. object_class_property_add(oc, "kernel-irqchip", "on|off|split",
  3313. NULL, kvm_set_kernel_irqchip,
  3314. NULL, NULL);
  3315. object_class_property_set_description(oc, "kernel-irqchip",
  3316. "Configure KVM in-kernel irqchip");
  3317. object_class_property_add(oc, "kvm-shadow-mem", "int",
  3318. kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
  3319. NULL, NULL);
  3320. object_class_property_set_description(oc, "kvm-shadow-mem",
  3321. "KVM shadow MMU size");
  3322. object_class_property_add(oc, "dirty-ring-size", "uint32",
  3323. kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
  3324. NULL, NULL);
  3325. object_class_property_set_description(oc, "dirty-ring-size",
  3326. "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
  3327. object_class_property_add_str(oc, "device", kvm_get_device, kvm_set_device);
  3328. object_class_property_set_description(oc, "device",
  3329. "Path to the device node to use (default: /dev/kvm)");
  3330. object_class_property_add_bool(oc, "rapl",
  3331. NULL,
  3332. kvm_set_kvm_rapl);
  3333. object_class_property_set_description(oc, "rapl",
  3334. "Allow energy related MSRs for RAPL interface in Guest");
  3335. object_class_property_add_str(oc, "rapl-helper-socket", NULL,
  3336. kvm_set_kvm_rapl_socket_path);
  3337. object_class_property_set_description(oc, "rapl-helper-socket",
  3338. "Socket Path for comminucating with the Virtual MSR helper daemon");
  3339. kvm_arch_accel_class_init(oc);
  3340. }
  3341. static const TypeInfo kvm_accel_type = {
  3342. .name = TYPE_KVM_ACCEL,
  3343. .parent = TYPE_ACCEL,
  3344. .instance_init = kvm_accel_instance_init,
  3345. .class_init = kvm_accel_class_init,
  3346. .instance_size = sizeof(KVMState),
  3347. };
  3348. static void kvm_type_init(void)
  3349. {
  3350. type_register_static(&kvm_accel_type);
  3351. }
  3352. type_init(kvm_type_init);
  3353. typedef struct StatsArgs {
  3354. union StatsResultsType {
  3355. StatsResultList **stats;
  3356. StatsSchemaList **schema;
  3357. } result;
  3358. strList *names;
  3359. Error **errp;
  3360. } StatsArgs;
  3361. static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
  3362. uint64_t *stats_data,
  3363. StatsList *stats_list,
  3364. Error **errp)
  3365. {
  3366. Stats *stats;
  3367. uint64List *val_list = NULL;
  3368. /* Only add stats that we understand. */
  3369. switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
  3370. case KVM_STATS_TYPE_CUMULATIVE:
  3371. case KVM_STATS_TYPE_INSTANT:
  3372. case KVM_STATS_TYPE_PEAK:
  3373. case KVM_STATS_TYPE_LINEAR_HIST:
  3374. case KVM_STATS_TYPE_LOG_HIST:
  3375. break;
  3376. default:
  3377. return stats_list;
  3378. }
  3379. switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
  3380. case KVM_STATS_UNIT_NONE:
  3381. case KVM_STATS_UNIT_BYTES:
  3382. case KVM_STATS_UNIT_CYCLES:
  3383. case KVM_STATS_UNIT_SECONDS:
  3384. case KVM_STATS_UNIT_BOOLEAN:
  3385. break;
  3386. default:
  3387. return stats_list;
  3388. }
  3389. switch (pdesc->flags & KVM_STATS_BASE_MASK) {
  3390. case KVM_STATS_BASE_POW10:
  3391. case KVM_STATS_BASE_POW2:
  3392. break;
  3393. default:
  3394. return stats_list;
  3395. }
  3396. /* Alloc and populate data list */
  3397. stats = g_new0(Stats, 1);
  3398. stats->name = g_strdup(pdesc->name);
  3399. stats->value = g_new0(StatsValue, 1);
  3400. if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
  3401. stats->value->u.boolean = *stats_data;
  3402. stats->value->type = QTYPE_QBOOL;
  3403. } else if (pdesc->size == 1) {
  3404. stats->value->u.scalar = *stats_data;
  3405. stats->value->type = QTYPE_QNUM;
  3406. } else {
  3407. int i;
  3408. for (i = 0; i < pdesc->size; i++) {
  3409. QAPI_LIST_PREPEND(val_list, stats_data[i]);
  3410. }
  3411. stats->value->u.list = val_list;
  3412. stats->value->type = QTYPE_QLIST;
  3413. }
  3414. QAPI_LIST_PREPEND(stats_list, stats);
  3415. return stats_list;
  3416. }
  3417. static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
  3418. StatsSchemaValueList *list,
  3419. Error **errp)
  3420. {
  3421. StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
  3422. schema_entry->value = g_new0(StatsSchemaValue, 1);
  3423. switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
  3424. case KVM_STATS_TYPE_CUMULATIVE:
  3425. schema_entry->value->type = STATS_TYPE_CUMULATIVE;
  3426. break;
  3427. case KVM_STATS_TYPE_INSTANT:
  3428. schema_entry->value->type = STATS_TYPE_INSTANT;
  3429. break;
  3430. case KVM_STATS_TYPE_PEAK:
  3431. schema_entry->value->type = STATS_TYPE_PEAK;
  3432. break;
  3433. case KVM_STATS_TYPE_LINEAR_HIST:
  3434. schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
  3435. schema_entry->value->bucket_size = pdesc->bucket_size;
  3436. schema_entry->value->has_bucket_size = true;
  3437. break;
  3438. case KVM_STATS_TYPE_LOG_HIST:
  3439. schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
  3440. break;
  3441. default:
  3442. goto exit;
  3443. }
  3444. switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
  3445. case KVM_STATS_UNIT_NONE:
  3446. break;
  3447. case KVM_STATS_UNIT_BOOLEAN:
  3448. schema_entry->value->has_unit = true;
  3449. schema_entry->value->unit = STATS_UNIT_BOOLEAN;
  3450. break;
  3451. case KVM_STATS_UNIT_BYTES:
  3452. schema_entry->value->has_unit = true;
  3453. schema_entry->value->unit = STATS_UNIT_BYTES;
  3454. break;
  3455. case KVM_STATS_UNIT_CYCLES:
  3456. schema_entry->value->has_unit = true;
  3457. schema_entry->value->unit = STATS_UNIT_CYCLES;
  3458. break;
  3459. case KVM_STATS_UNIT_SECONDS:
  3460. schema_entry->value->has_unit = true;
  3461. schema_entry->value->unit = STATS_UNIT_SECONDS;
  3462. break;
  3463. default:
  3464. goto exit;
  3465. }
  3466. schema_entry->value->exponent = pdesc->exponent;
  3467. if (pdesc->exponent) {
  3468. switch (pdesc->flags & KVM_STATS_BASE_MASK) {
  3469. case KVM_STATS_BASE_POW10:
  3470. schema_entry->value->has_base = true;
  3471. schema_entry->value->base = 10;
  3472. break;
  3473. case KVM_STATS_BASE_POW2:
  3474. schema_entry->value->has_base = true;
  3475. schema_entry->value->base = 2;
  3476. break;
  3477. default:
  3478. goto exit;
  3479. }
  3480. }
  3481. schema_entry->value->name = g_strdup(pdesc->name);
  3482. schema_entry->next = list;
  3483. return schema_entry;
  3484. exit:
  3485. g_free(schema_entry->value);
  3486. g_free(schema_entry);
  3487. return list;
  3488. }
  3489. /* Cached stats descriptors */
  3490. typedef struct StatsDescriptors {
  3491. const char *ident; /* cache key, currently the StatsTarget */
  3492. struct kvm_stats_desc *kvm_stats_desc;
  3493. struct kvm_stats_header kvm_stats_header;
  3494. QTAILQ_ENTRY(StatsDescriptors) next;
  3495. } StatsDescriptors;
  3496. static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
  3497. QTAILQ_HEAD_INITIALIZER(stats_descriptors);
  3498. /*
  3499. * Return the descriptors for 'target', that either have already been read
  3500. * or are retrieved from 'stats_fd'.
  3501. */
  3502. static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
  3503. Error **errp)
  3504. {
  3505. StatsDescriptors *descriptors;
  3506. const char *ident;
  3507. struct kvm_stats_desc *kvm_stats_desc;
  3508. struct kvm_stats_header *kvm_stats_header;
  3509. size_t size_desc;
  3510. ssize_t ret;
  3511. ident = StatsTarget_str(target);
  3512. QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
  3513. if (g_str_equal(descriptors->ident, ident)) {
  3514. return descriptors;
  3515. }
  3516. }
  3517. descriptors = g_new0(StatsDescriptors, 1);
  3518. /* Read stats header */
  3519. kvm_stats_header = &descriptors->kvm_stats_header;
  3520. ret = pread(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header), 0);
  3521. if (ret != sizeof(*kvm_stats_header)) {
  3522. error_setg(errp, "KVM stats: failed to read stats header: "
  3523. "expected %zu actual %zu",
  3524. sizeof(*kvm_stats_header), ret);
  3525. g_free(descriptors);
  3526. return NULL;
  3527. }
  3528. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3529. /* Read stats descriptors */
  3530. kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
  3531. ret = pread(stats_fd, kvm_stats_desc,
  3532. size_desc * kvm_stats_header->num_desc,
  3533. kvm_stats_header->desc_offset);
  3534. if (ret != size_desc * kvm_stats_header->num_desc) {
  3535. error_setg(errp, "KVM stats: failed to read stats descriptors: "
  3536. "expected %zu actual %zu",
  3537. size_desc * kvm_stats_header->num_desc, ret);
  3538. g_free(descriptors);
  3539. g_free(kvm_stats_desc);
  3540. return NULL;
  3541. }
  3542. descriptors->kvm_stats_desc = kvm_stats_desc;
  3543. descriptors->ident = ident;
  3544. QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
  3545. return descriptors;
  3546. }
  3547. static void query_stats(StatsResultList **result, StatsTarget target,
  3548. strList *names, int stats_fd, CPUState *cpu,
  3549. Error **errp)
  3550. {
  3551. struct kvm_stats_desc *kvm_stats_desc;
  3552. struct kvm_stats_header *kvm_stats_header;
  3553. StatsDescriptors *descriptors;
  3554. g_autofree uint64_t *stats_data = NULL;
  3555. struct kvm_stats_desc *pdesc;
  3556. StatsList *stats_list = NULL;
  3557. size_t size_desc, size_data = 0;
  3558. ssize_t ret;
  3559. int i;
  3560. descriptors = find_stats_descriptors(target, stats_fd, errp);
  3561. if (!descriptors) {
  3562. return;
  3563. }
  3564. kvm_stats_header = &descriptors->kvm_stats_header;
  3565. kvm_stats_desc = descriptors->kvm_stats_desc;
  3566. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3567. /* Tally the total data size; read schema data */
  3568. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3569. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3570. size_data += pdesc->size * sizeof(*stats_data);
  3571. }
  3572. stats_data = g_malloc0(size_data);
  3573. ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
  3574. if (ret != size_data) {
  3575. error_setg(errp, "KVM stats: failed to read data: "
  3576. "expected %zu actual %zu", size_data, ret);
  3577. return;
  3578. }
  3579. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3580. uint64_t *stats;
  3581. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3582. /* Add entry to the list */
  3583. stats = (void *)stats_data + pdesc->offset;
  3584. if (!apply_str_list_filter(pdesc->name, names)) {
  3585. continue;
  3586. }
  3587. stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
  3588. }
  3589. if (!stats_list) {
  3590. return;
  3591. }
  3592. switch (target) {
  3593. case STATS_TARGET_VM:
  3594. add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
  3595. break;
  3596. case STATS_TARGET_VCPU:
  3597. add_stats_entry(result, STATS_PROVIDER_KVM,
  3598. cpu->parent_obj.canonical_path,
  3599. stats_list);
  3600. break;
  3601. default:
  3602. g_assert_not_reached();
  3603. }
  3604. }
  3605. static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
  3606. int stats_fd, Error **errp)
  3607. {
  3608. struct kvm_stats_desc *kvm_stats_desc;
  3609. struct kvm_stats_header *kvm_stats_header;
  3610. StatsDescriptors *descriptors;
  3611. struct kvm_stats_desc *pdesc;
  3612. StatsSchemaValueList *stats_list = NULL;
  3613. size_t size_desc;
  3614. int i;
  3615. descriptors = find_stats_descriptors(target, stats_fd, errp);
  3616. if (!descriptors) {
  3617. return;
  3618. }
  3619. kvm_stats_header = &descriptors->kvm_stats_header;
  3620. kvm_stats_desc = descriptors->kvm_stats_desc;
  3621. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3622. /* Tally the total data size; read schema data */
  3623. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3624. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3625. stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
  3626. }
  3627. add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
  3628. }
  3629. static void query_stats_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
  3630. {
  3631. int stats_fd = cpu->kvm_vcpu_stats_fd;
  3632. Error *local_err = NULL;
  3633. if (stats_fd == -1) {
  3634. error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
  3635. error_propagate(kvm_stats_args->errp, local_err);
  3636. return;
  3637. }
  3638. query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
  3639. kvm_stats_args->names, stats_fd, cpu,
  3640. kvm_stats_args->errp);
  3641. }
  3642. static void query_stats_schema_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
  3643. {
  3644. int stats_fd = cpu->kvm_vcpu_stats_fd;
  3645. Error *local_err = NULL;
  3646. if (stats_fd == -1) {
  3647. error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
  3648. error_propagate(kvm_stats_args->errp, local_err);
  3649. return;
  3650. }
  3651. query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
  3652. kvm_stats_args->errp);
  3653. }
  3654. static void query_stats_cb(StatsResultList **result, StatsTarget target,
  3655. strList *names, strList *targets, Error **errp)
  3656. {
  3657. KVMState *s = kvm_state;
  3658. CPUState *cpu;
  3659. int stats_fd;
  3660. switch (target) {
  3661. case STATS_TARGET_VM:
  3662. {
  3663. stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
  3664. if (stats_fd == -1) {
  3665. error_setg_errno(errp, errno, "KVM stats: ioctl failed");
  3666. return;
  3667. }
  3668. query_stats(result, target, names, stats_fd, NULL, errp);
  3669. close(stats_fd);
  3670. break;
  3671. }
  3672. case STATS_TARGET_VCPU:
  3673. {
  3674. StatsArgs stats_args;
  3675. stats_args.result.stats = result;
  3676. stats_args.names = names;
  3677. stats_args.errp = errp;
  3678. CPU_FOREACH(cpu) {
  3679. if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
  3680. continue;
  3681. }
  3682. query_stats_vcpu(cpu, &stats_args);
  3683. }
  3684. break;
  3685. }
  3686. default:
  3687. break;
  3688. }
  3689. }
  3690. void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
  3691. {
  3692. StatsArgs stats_args;
  3693. KVMState *s = kvm_state;
  3694. int stats_fd;
  3695. stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
  3696. if (stats_fd == -1) {
  3697. error_setg_errno(errp, errno, "KVM stats: ioctl failed");
  3698. return;
  3699. }
  3700. query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
  3701. close(stats_fd);
  3702. if (first_cpu) {
  3703. stats_args.result.schema = result;
  3704. stats_args.errp = errp;
  3705. query_stats_schema_vcpu(first_cpu, &stats_args);
  3706. }
  3707. }
  3708. void kvm_mark_guest_state_protected(void)
  3709. {
  3710. kvm_state->guest_state_protected = true;
  3711. }
  3712. int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
  3713. {
  3714. int fd;
  3715. struct kvm_create_guest_memfd guest_memfd = {
  3716. .size = size,
  3717. .flags = flags,
  3718. };
  3719. if (!kvm_guest_memfd_supported) {
  3720. error_setg(errp, "KVM does not support guest_memfd");
  3721. return -1;
  3722. }
  3723. fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
  3724. if (fd < 0) {
  3725. error_setg_errno(errp, errno, "Error creating KVM guest_memfd");
  3726. return -1;
  3727. }
  3728. return fd;
  3729. }