kvm-all.c 121 KB

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